且构网

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

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

更新时间:2022-02-10 22:38:30

您可以使用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是唯一的).

或使用联接:

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.