复杂的mysql查询计数来自2表和group by

时间:2014-01-23 14:46:53

标签: mysql sql

我有2个表入站,出站两个表具有相同的结构

入站

id | site_id | ip (bigint) | date
 1 | 1       | 12345678890 | 20140123
 2 | 1       | 12341234000 | 20140123

出站

id | site_id | ip          | date
 1 | 1       | 12345678890 | 20140123
 2 | 1       | 12341234000 | 20140124
 3 | 1       | 12341234000 | 20140124

我的输入只是site_id我想组合入站和出站表并获得结果

inbound_unique_ip_count |  outbound_unique_ip_count | date
                      2 |                         1 | 20140123
              0 or null |                         1 | 20140124

我认为按日期分组应该有用吗?

2 个答案:

答案 0 :(得分:0)

使用此:

select date, COUNT(distinct(a.inbound_unique_ip_count) ) as `inbound_unique_ip_count`, 
COUNT(distinct (outbound_unique_ip_count )) as `outbound_unique_ip_count` 
from inbound a JOIN outbound b on a.site_id=b.site_id 
group by 1 

答案 1 :(得分:0)

SELECT COUNT(distinct i.ip) AS inbound_unique_ip_count,
       COUNT(distinct o.ip) AS outbound_unique_ip_count,
       date
FROM inbound AS i
JOIN outbound AS o USING (site_id, date)
WHERE i.site_id = :site_id
GROUP BY date

只有当两个表都包含所有日期和输入site_id时,这才能正常工作。如果其中任何一个表都缺少其中一些,那么您需要一个FULL OUTER JOIN,MySQL不支持。如果您搜索SO,您应该能够找到解决方法,我将其留作读者练习。

相关问题