每当我需要检查表中某行是否存在时,我总是倾向于编写如下条件:
SELECT a, b, c
FROM a_table
WHERE EXISTS
(SELECT * -- This is what I normally write
FROM another_table
WHERE another_table.b = a_table.b
)
Run Code Online (Sandbox Code Playgroud)
还有一些人这样写:
SELECT a, b, c
FROM a_table
WHERE EXISTS
(SELECT 1 --- This nice '1' is what I have seen other people use
FROM another_table
WHERE another_table.b = a_table.b
)
Run Code Online (Sandbox Code Playgroud)
当条件NOT EXISTS不是EXISTS: 在某些情况下,我可能会用 aLEFT JOIN和一个额外的条件(有时称为antijoin)来编写它:
SELECT a, b, c
FROM a_table
LEFT JOIN another_table ON another_table.b = …Run Code Online (Sandbox Code Playgroud)