[英]Mysql: Select data from one table where in table2 and values must all be 0 in table2
I want to be able to select everything from t1
where t1.active = 1
where the ID
also exists in t2
and t2.active = 0
我希望能够从
t1
中选择所有内容,其中t1.active = 1
,其中ID
也存在于t2
和t2.active = 0
But I don't want to show any entry in t1
for an ID
if the entries that match in t2
have 1 entry where t2.active = 1
但是我不想在
t1
为ID
显示任何条目,如果在t2
中匹配的条目有1个条目,其中t2.active = 1
Example: 例:
Table 1
-----------
t1id|Active|
1 | 1 |
2 | 1 |
Table 2
-----------
t2id|Active|
1 | 0 |
1 | 0 |
1 | 1 |
2 | 0 |
2 | 0 |
Should give the result of: 应给出以下结果:
t1id|Active|
2 | 1 |
I've tried: 我试过了:
SELECT * FROM t1 WHERE t1.active = 1
AND EXISTS(SELECT * FROM t2 WHERE t2.id = t1.id
AND t2.active = 0
GROUP BY t2.id, t2.active HAVING COUNT(t2.id) > 1 AND t2.active = 0)
Unfortunately this still returns entries from t1 where the id exists in t2 and has one entry where active = 1 不幸的是,它仍然从t1返回条目,其中id在t2中存在,并且有一个条目,其中active = 1
Any help would be appreciated! 任何帮助,将不胜感激!
I see two solutions. 我看到两个解决方案。
1 short, using max 1短,上限为
SELECT *
FROM t1
WHERE
t1.active = 1 AND
EXISTS(SELECT null
FROM t2 WHERE t2.id = t1.id
GROUP BY t2.id
--if the max active = 0 then it means there's no t2.active = 1
HAVING MAX(t2.active) =0)
One less elegant in code, but probably clearer to explain what you try to achieve 一种不太优雅的代码,但可能更清晰地解释了您尝试实现的目标
SELECT * FROM t1
WHERE
t1.active = 1 AND
EXISTS ( SELECT null FROM t2
WHERE t2.id = t1.id
AND t2.active = 0) AND
NOT EXISTS (SELECT null FROM t2
WHERE t2.id = t1.id
AND t2.active = 1)
Why don't you try using INNER JOIN? 为什么不尝试使用INNER JOIN?
The Query must be like that: 查询必须是这样的:
select *
from T1 a
LEFT JOIN T2 b
ON a.ID = b.ID
and b.ACTIVE = (select max(active) from T2 group by ID)
where a.ACTIVE= 1
b.ACTIVE = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.