我有区域表:
table region:
id | title
地区有很多广告:
table advert:
id | region_id | ...
然后广告有很多用途(通过表adv_use多次使用):
table use:
use | slug | ...
----------------
1 | slug_1 | ...
2 | slug_2 | ...
..................
table adv_use:
adv_id | use_id
我希望选择所有带有count(*)广告的区域,这些广告与slug_1 AND slug_2一起使用。如果广告与slug_1或slug_2(或两者)无关,则不得计算。 我现在拥有的:
SELECT COUNT(DISTINCT advert.id) as count
FROM region
JOIN advert ON region.id = advert.region_id
JOIN adv_use ON advert.id = adv_use.adv_id
JOIN use ON adv_use.use_id = use.id
WHERE use.slug IN ('slug_1', 'slug_2')
GROUP BY region.id
HAVING COUNT(DISTINCT adv_use.use_id) = 2
但它的工作并不像我想要的那样。 SQLFiddle:http://sqlfiddle.com/#!2/5b4d4/1
感谢您的帮助,感谢抱歉英语不好。
答案 0 :(得分:0)
您需要使用子查询来选择使用两个slugs的adv_id
:
SELECT COUNT(DISTINCT advert.id) as count, region.id as reg_id
FROM region
JOIN advert ON region.id = advert.region_id
JOIN (SELECT adv_use.adv_id
FROM adv_use
JOIN tbl_use ON adv_use.use_id = tbl_use.id
WHERE tbl_use.slug IN ('slug1', 'slug2')
GROUP BY adv_use.adv_id
HAVING COUNT(DISTINCT adv_use.use_id) = 2) adv_use
ON advert.id = adv_use.adv_id
GROUP BY region.id
;