SQL查询选择具有2列相等值的行

时间:2018-10-17 13:14:48

标签: mysql sql

假设我有下表:

id    || name  || published
--------------------------
1     || john  || 1
7     || alex  || 0
1     || roco  || 0
4     || mika  || 0
16    || mika  || 1
8     || zack  || 1
8     || alfi  || 1

我应该运行哪个sql查询以返回ID 16和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

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

您似乎想要NOT EXISTS

SELECT a.*
FROM table a
WHERE NOT EXISTS (SELECT 1 FROM table a1 WHERE a1.id = a.id AND a1.published = 0);

答案 1 :(得分:2)

您可以将Group By子句中的Having与条件聚合一起使用,以仅考虑已发布从未 为零的那些对象。

SELECT id
FROM table_name 
GROUP BY id 
HAVING SUM(published = 0) = 0

或者,作为 @Gordon Linoff suggested,您也可以使用以下内容:

SELECT id
FROM table_name 
GROUP BY id 
HAVING MIN(published) > 0

答案 2 :(得分:1)

您可以使用not in

select t.* from your_table t
where t.id not in (
                  select id from your_table t1
                  where t1.published=0
                 )

输出

id  name    published
16  mika    1
8   alif    1
8   zack    1

DEMO DB FIDDLE

答案 3 :(得分:0)

可以使用

来实现
SELECT name, published
FROM A
WHERE id IN (16, 8)
ORDER BY id;