【问题标题】:Join a columns count from another table加入来自另一个表的列数
【发布时间】:2021-02-26 20:51:39
【问题描述】:

我有 2 个表格:网址和链接。

urls
- urls.url

links
- links.source
- links.destination

我正在尝试选择所有网址并添加传入和传出网址的计数,结果应该是:

URL; Count Incoming links; Count Outgoing links

我尝试了以下方法来获取传入的 URL,但遗憾的是这些 URL 不是有效的 SQL,此时我不知道如何寻找解决此问题的方法。

SELECT * FROM urls JOIN COUNT(links.source) ON urls.url = links.source 

【问题讨论】:

  • 请提供充足的数据和期望的结果。另外,用您正在使用的数据库标记您的问题。

标签: mysql sql count pivot subquery


【解决方案1】:

嗯。 . .一种方法是关联子查询:

select u.*,
       (select count(*) from links l where l.source = u.url) as outgoing,
       (select count(*) from links l where l.destination = u.url) as incoming
from urls u;

如果您只想要links 中的网址,您可以取消透视并聚合:

select url, sum(outgoing), sum(incoming)
from ((select source as url, 1 as outgoing, 0 as incoming
       from links
      ) union all
      (select destination as url, 0 as outgoing, 1 as incoming
       from links
      )
     ) oi
group by url;

【讨论】:

    【解决方案2】:

    您可以使用相关子查询:

    select u.url,
        (select count(*) from links l where l.source      = u.url) as incoming_links,
        (select count(*) from links l where l.destination = u.url) as outgoing_links
    from urls u
    

    或者,您可以进行条件聚合:

    select u.url,
        sum(case when u.url = l.source      then 1 else 0 end) as incoming_links,
        sum(case when u.url = l.destination then 1 else 0 end) as outgoing_links 
    from urls u
    left join links l on u.url in (l.source, l.destination)
    group by u.url
    

    根据您的数据库,可能有一种更简洁的方式来表达条件和。例如,在 MySQL 中:

    sum(u.url = l.source) as incoming_links
    

    或者在 Postgres 中:

    count(*) filter(where u.url = l.source) as incoming_links
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2018-11-09
      • 2019-06-11
      • 2020-09-09
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      相关资源
      最近更新 更多