我有以下五个表:
company type branch company_type company_branch
------- ---- ------ ------------- --------------
c_id t_id b_id c_id | t_id c_id | b_id
---- --- ---- ----------- --------------
1 1 1 1 1 1 1
2 2 2 1 2 1 2
3 3 2 1 2 1
2 3 2 3
以下两个查询工作正常:
SELECT DISTINCT `co`.`c_id`
FROM (`company` co)
JOIN `company_type` t ON `t`.`c_id` = `co`.`c_id`
WHERE `co`.`status` = 1
GROUP BY `co`.`c_id`
HAVING sum(if(`t`.`t_id` in (1,2),1,0)) = 2 (---> returns 1 ) Correct !
SELECT DISTINCT `co`.`c_id`
FROM (`company` co)
JOIN `company_branch` b ON `b`.`c_id` = `co`.`id`
WHERE `co`.`status` = 1
GROUP BY `co`.`id`
HAVING sum(if(`b`.`b_id` in (1,2),1,0)) = 2 (---> returns 1 ) Correct !
但是当我尝试像下面这样组合它们时,它给了我一个空的结果:
SELECT DISTINCT `co`.`c_id`
FROM (`company` co)
JOIN `company_branch` b ON `b`.`c_id` = `co`.`id`
JOIN `company_type` t ON `t`.`c_id` = `co`.`id`
WHERE `co`.`status` = 1
GROUP BY `co`.`id`
HAVING sum(if(`b`.`b_id` in (1,2),1,0)) = 2 AND sum(if(`t`.`t_id` in (1,2),1,0)) = 2
我的猜测是这两个条件之间的 AND 是罪魁祸首!有人有线索吗??或解决方法?
预期结果:1