如果没有子查询,请为只有空帖的作者选择所有author_id。

时间:2019-05-09 23:50:26

标签: mysql

给出下表:

+----+-----------+---------+
| id | author_id | content |
+----+-----------+---------+
| 1  | 1         |         |
+----+-----------+---------+
| 2  | 2         |         |
+----+-----------+---------+
| 3  | 1         |         |
+----+-----------+---------+
| 4  | 2         | XYZ     |
+----+-----------+---------+

我该如何选择author_id的列表,这些列表仅包含没有内容的帖子,而不使用子查询?在这种情况下,我希望查询仅返回author_id 1。

这行得通,但是我想知道是否有一种方法不必为了性能而使用子查询。

SELECT author_id
FROM my_table
WHERE author_id NOT IN (
    SELECT author_id FROM my_table WHERE content != ''
)
GROUP BY author_id

这里是a fiddle

3 个答案:

答案 0 :(得分:5)

您可以使用HAVING子句过滤组:

SELECT author_id
FROM my_table
GROUP BY author_id
HAVING MAX(LENGTH(content)) = 0

或者您也可以使用JOIN尝试查找具有非空白内容的任何行,而仅选择不匹配的行。

SELECT t1.author_id
FROM my_table AS t1
LEFT OUTER JOIN my_table AS t2 ON t1.author_id = t2.author_id
  AND LENGTH(t2.content) > 0
WHERE t2.author_id IS NULL

答案 1 :(得分:3)

您可以使用自我加入,JOIN在文章中有内容的地方{@ 1}作者,然后仅选择没有内容的作者:

SELECT DISTINCT m1.author_id
FROM my_table m1
LEFT JOIN my_table m2 ON m2.author_id = m1.author_id AND m2.content != ''
WHERE m2.id IS NULL

输出:

author_id
1

Demo on dbfiddle

答案 2 :(得分:0)

您也可以使用NOT EXISTS

SELECT DISTINCT author_id
FROM my_table a
WHERE NOT EXISTS 
           (SELECT NULL
            FROM my_table b
            WHERE a.author_id = b.author_id
            AND b.content != '')