SELECTING with multiple WHERE conditions on the same column
P粉384366923
2023-08-23 19:08:16
<p>Okay, I think I might be overlooking something obvious/simple here... but I need to write a query that only returns records that match multiple criteria on the same column... </ p>
<p>My table is a very simple link setup for applying flags to users...</p>
<pre class="brush:php;toolbar:false;">ID contactid flag flag_type
----------------------------------
118 99 Volunteer 1
119 99 Uploaded 2
120 100 Via Import 3
121 100 Volunteer 1
122 100 Uploaded 2</pre>
<p>Wait... In this case, you'll see that contacts 99 and 100 are both marked as "Volunteer" and "Uploaded"...</p>
<p>All I need to do is return those contactids that match multiple criteria entered via the search form... the contactid must match all selected flags... In my head, the SQL should look like: < ; /p>
</p>
<pre class="brush:php;toolbar:false;">SELECT contactid
WHERE flag = 'Volunteer'
AND flag = 'Uploaded'...</pre>
<p>But... nothing is returned... What am I doing wrong here? </p>
use:
The key is that the count of
t.flag
needs to be equal to the number of parameters in theIN
clause.The use of
COUNT(DISTINCT t.flag)
is to prevent the combination of contactid and flag from not having a unique constraint - if there is no chance of duplication, you can omit the DISTINCT from the query:You can use
GROUP BY
andHAVING COUNT(*) = _
:(assuming
contact_id, flag
are unique).Or use connection:
If the flag list is long and there are many matches, the first one may be faster. If the flag list is short and there are few matches, you may find the second one to be faster. If performance is an issue, try testing it on your data to see which one works best.