加入 3 个表并 select 计数

join 3 tables and select count

我有 3 tables {网站} {帐户} {广告}

网站table

id     title    url           etc
-----------------------------------
1      site1    site1.com     ...
2      site2    site1.com     ...
3      site3    site3.com     ...

帐户table

id     websiteID   username    etc
-----------------------------------
1      1           username1   ...
2      2           username2   ...
3      1           username1   ...
4      3           username5   ...

广告 table

id     accountID   title    etc
---------------------------------
1      1           title1   ...
2      2           title1   ...
3      1           title3   ...
5      4           title4   ...

我想加入这 3 个 table 从网站 table 开始并从网站 table 获取一些数据,然后 accounts_count 与其网站相关,ads_count 与其帐户相关。我也希望计数为零或空结果。 帐户 table 中的用户名不是唯一的,可以相同。 广告中的标题 table 也不是唯一的,可以相同。

这是我的查询,但有时它 return 错误的结果!

SELECT 
    websites.id as website_id
,   websites.title as website_title
,   COUNT(accounts.websiteID) as accounts_count
,   COUNT(ads.accountID) as ads_count
,   ads.lastUpdate
,   websites.activation as website_activation 
FROM websites 
LEFT JOIN accounts 
    ON websites.id = accounts.websiteID 
LEFT JOIN ads 
    ON accounts.id = ads.accountID
GROUP BY websites.id;

你能帮我吗:{

我想在 table 中显示此结果,如下所示:

website_title     accounts_count   ads_count    last update  operations
-------------------------------------------------------------------------
website1           3               8            2017/07/27   etc...
website2           0               0            2017/07/27   etc...
website3           3               9            2017/07/27   etc...
website4           5               15           2017/07/27   etc...

问题是,当您加入 websites 帐户时,您会在 accounts 中获得每一行的行。然后,当您加入 ads 时,您会进一步增加行数。我的猜测是您现在对 accounts_countads_count 的计数相同。此外,您有来自 ads table 的 lastUpdate 列并具有聚合功能。

SELECT websites.id as website_id, websites.title as website_title,  
   ads.lastUpdate, websites.activation as website_activation 
   COUNT(accounts.websiteID) as accounts_count, COUNT(ads.accountID) as ads_count, 
FROM websites, accounts, ads
WHERE websites.id = accounts.websiteID 
   AND accounts.id = ads.accountID;

似乎计数需要更改。
ads.lastUpdate 的 MAX 会更准确。

F.e.

SELECT 
    websites.id as website_id
,   websites.title as website_title
,   COUNT(DISTINCT accounts.ID) as accounts_count
,   COUNT(ads.ID) as ads_count
,   MAX(ads.lastUpdate) as LastUpdateAds
,   websites.activation as website_activation 
FROM websites 
LEFT JOIN accounts 
    ON websites.id = accounts.websiteID 
LEFT JOIN ads 
    ON accounts.id = ads.accountID
GROUP BY websites.id;