加入3个表格并选择计数

时间:2018-07-27 07:02:49

标签: mysql sql database-design count jointable

我有3个表{websites} {accounts} {ads}

网站表

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

帐户表

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

广告表格

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

我要从网站表开始加入这三个表,并从网站表中获取一些数据,并关联到其网站的 accounts_count 和与该帐户相关的 ads_count 。我也想计数为零或空结果。 帐户表中的用户名不是唯一的,并且可以相同。 ads表中的标题也不是唯一的,并且可以相同。

这是我的查询,但有时会返回错误的结果!

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;

你能帮我吗?{

我想在这样的表中显示此结果:

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...

3 个答案:

答案 0 :(得分:1)

似乎计数需要更改。
而且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;

答案 1 :(得分:0)

问题是,当您使用帐户加入websites时,accounts中的每一行都会得到一行。然后,当您与ads一起加入时,您会进一步乘以行数。我的猜测是,accounts_countads_count的计数现在相同。此外,您在lastUpdate表中有ads列,并且具有汇总功能。

答案 2 :(得分:0)

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;