且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在同一列上使用多个 WHERE 条件进行选择

更新时间:2022-05-07 22:41:10

你可以使用 GROUP BYHAVING COUNT(*) = _:

SELECT contact_id
FROM your_table
WHERE flag IN ('Volunteer', 'Uploaded', ...)
GROUP BY contact_id
HAVING COUNT(*) = 2 -- // must match number in the WHERE flag IN (...) list

(假设 contact_id, flag 是唯一的).

(assuming contact_id, flag is unique).

或者使用连接:

SELECT T1.contact_id
FROM your_table T1
JOIN your_table T2 ON T1.contact_id = T2.contact_id AND T2.flag = 'Uploaded'
-- // more joins if necessary
WHERE T1.flag = 'Volunteer'

如果标志列表很长并且有很多匹配项,第一个可能会更快.如果标志列表很短并且匹配项很少,您可能会发现第二个更快.如果性能是一个问题,请尝试对您的数据进行测试,看看哪个效果***.

If the list of flags is very long and there are lots of matches the first is probably faster. If the list of flags is short and there are few matches, you will probably find that the second is faster. If performance is a concern try testing both on your data to see which works best.