簡體   English   中英

來自2個表的復雜mysql查詢計數並按組

[英]complex mysql query count from 2 table and group by

我有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

我認為按日期分組應該工作嗎?

用這個:

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 
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此方法才能正常工作。 如果任何一個表都可能缺少其中某些表,則需要MySQL不支持的FULL OUTER JOIN 如果您對此進行搜索,那么您應該能夠找到解決方法,我將其留給讀者練習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM