I would like to select multiple values from a single column in a database table that equal to a number of values. I want all these values to match otherwise it should return no rows. I do not want to use “IN” as that is equal to “OR”.
The following is a basic mockup of what it should do but it needs to be dynamic as I wish to use it with a PDO statement. If the database only contains id’s 1 and 2 it should fail ie return no rows.
SELECT
id
FROM
reports
WHERE
id=1 AND id=2 AND id=3
I have the current code as follow which is incorrectly returning zero rows:
SELECT id,title
FROM reports
WHERE id IN (1,2)
GROUP BY title
HAVING COUNT(DISTINCT id) = 2
My current table structure is as follows:
http://www.sqlfiddle.com/#!2/ce4aa/1
You have to use
HAVING COUNT(id) = 3to ensure that the selected rows have all the three id’s. Something like:Or:
Note that: You have to
GROUP BY SomeOtherFieldwhereSomeOtherFieldis other field thanidbecause if youGROUP BY idwithHAVING COUNT(id)you won’t get any records, sinceCOUNT(id)will be always = 1.Edit: fixed
WHEREclause,OR‘s instead ofAND‘s.SQL Fiddle Demo