[英]SQL query to select rows having 2 columns equal value
Let's say I have the following table: 假设我有下表:
id || name || published
--------------------------
1 || john || 1
7 || alex || 0
1 || roco || 0
4 || mika || 0
16 || mika || 1
8 || zack || 1
8 || alfi || 1
Which sql query should I run to return IDs 16 and 8? 我应该运行哪个SQL查询来返回ID 16和8?
I tried the following but I'm always having IDs 1, 16 and 8: 我尝试了以下操作,但是我始终具有ID 1、16和8:
SELECT A.*
FROM table A
INNER JOIN (SELECT id, published
FROM table
WHERE published > 0
GROUP BY id) B
ON A.id = B.id AND A.published = B.published
GROUP BY id
Any ideas ? 有任何想法吗 ?
You seems want NOT EXISTS
: 您似乎想要
NOT EXISTS
:
SELECT a.*
FROM table a
WHERE NOT EXISTS (SELECT 1 FROM table a1 WHERE a1.id = a.id AND a1.published = 0);
You can use Group By
with conditional aggregation in Having
clause to consider only those where published has never been zero. 您可以使用
Group By
有条件的聚集Having
条款只考虑那些发表 从未为零。
SELECT id
FROM table_name
GROUP BY id
HAVING SUM(published = 0) = 0
Alternatively, as @Gordon Linoff suggested , you can use the following as well: 或者,如@Gordon Linoff 建议的那样 ,您也可以使用以下内容:
SELECT id
FROM table_name
GROUP BY id
HAVING MIN(published) > 0
You could use not in
你可以用
not in
select t.* from your_table t
where t.id not in (
select id from your_table t1
where t1.published=0
)
output 输出
id name published
16 mika 1
8 alif 1
8 zack 1
it can be achieved using 可以使用
SELECT name, published
FROM A
WHERE id IN (16, 8)
ORDER BY id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.