93

Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...

My table is a very simple linking setup for applying flags to a user ...

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

etc... in this case you'll see both contact 99 and 100 are flagged as both "Volunteer" and "Uploaded"...

What I need to be able to do is return those contactid's ONLY that match multiple criteria entered via a search form...the contactid's have to match ALL chosen flags... in my head the SQL should look something like:

SELECT contactid 
 WHERE flag = 'Volunteer' 
   AND flag = 'Uploaded'...

but... that returns nothing... What am I doing wrong here?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
RyanNehring
  • 1,033
  • 1
  • 9
  • 9
  • 3
    This statement is not working because flag cannot be equal to 'Volunteer' and 'Upload' at the same time. You can use OR operator instead of AND and it will work. – Johar Zaman Feb 27 '19 at 18:07

12 Answers12

118

You can either use GROUP BY and HAVING 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

(assuming contact_id, flag is unique).

Or use joins:

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    The problem with JOINs is if there's more than one record of a contactid associated with the "Uploaded" flag, there'll be duplicates for the T1 references. – OMG Ponies Oct 28 '10 at 22:18
  • SELECT contact_id FROM your_table WHERE ( flag IN ('Volunteer', 'Uploaded', ...) and one_type = sometype_one ) AND flag IN ('someOtherVolunteer', 'Uploaded', ...) and second_type = sometype_two GROUP BY contact_id HAVING COUNT(*) = 2 Sir i have same senario like above query, but it's returning null. zero rows. – Bangash Dec 10 '18 at 13:37
  • In case of self join, for N number of values, you'll need N self join. In that example, what if you have to get the results with all these three flags "Uploaded", "Volunteer" and "Via Import " in it? So, i think using `GROUP BY` with `HAVING COUNT` makes more sense. – Sri Feb 11 '20 at 02:33
27

Use:

  SELECT t.contactid
    FROM YOUR_TABLE t
   WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
  HAVING COUNT(DISTINCT t.flag) = 2

The key thing is that the counting of t.flag needs to equal the number of arguments in the IN clause.

The use of COUNT(DISTINCT t.flag) is in case there isn't a unique constraint on the combination of contactid and flag -- if there's no chance of duplicates you can omit the DISTINCT from the query:

  SELECT t.contactid
    FROM YOUR_TABLE t
   WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
  HAVING COUNT(t.flag) = 2
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
12

Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer' 
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.

wtct
  • 167
  • 1
  • 3
  • 1
    Since the questioner tagged mysql, I think its good to point out that INTERSECT doesnt work for MySql – linkonabe Jul 12 '20 at 20:28
  • 1
    The questioner may have tagged mysql, but thumbs up for this TSQL user this worked swimmingly for. – JulieC Jan 28 '21 at 18:56
6

can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"

not really applicable seeing the formatted table.

Brandon Frohbieter
  • 17,563
  • 3
  • 40
  • 62
3

Try to use this alternate query:

SELECT A.CONTACTID 
FROM (SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'VOLUNTEER')A , 
(SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'UPLOADED') B WHERE A.CONTACTID = B.CONTACTID;
Qiu
  • 5,651
  • 10
  • 49
  • 56
0
SELECT contactid, Count(*) 
FROM <YOUR_TABLE> WHERE flag in ('Volunteer','Uploaded')  
GROUP BY contactid 
HAVING count(*)>1;
jaggi
  • 357
  • 1
  • 4
  • 17
vivek
  • 11
  • 6
    Consider improving your answer. _[Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day](http://meta.stackexchange.com/questions/148272/is-there-any-benefit-to-allowing-code-only-answers-while-blocking-code-only-ques)_ –  Aug 06 '15 at 08:22
0

something like this should work for you

SELECT * FROM `product_options` GROUP BY product_id 
HAVING COUNT(option_id IN (1,2,3) OR NULL) > 0 AND COUNT(option_id IN (7) OR NULL) > 0
Farhan
  • 1,561
  • 14
  • 12
-3

AND will return you an answer only when both volunteer and uploaded are present in your column. Otherwise it will return null value...

try using OR in your statement ...

SELECT contactid  WHERE flag = 'Volunteer' OR flag = 'Uploaded'
Mehmet Ince
  • 4,059
  • 12
  • 45
  • 65
talha
  • 5
  • This will show all entries that are `Volunteer` OR `Uploaded` but he wants entries that are twice in and have each once – kero Nov 10 '13 at 12:03
-3
select purpose.pname,company.cname
from purpose
Inner Join company
on purpose.id=company.id
where pname='Fever' and cname='ABC' in (
  select mname
  from medication
  where mname like 'A%'
  order by mname
); 
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
-3

Change AND to OR. Simple mistake. Think of it like plain English, I want to select anything with that equals this or that.

-4

Use this: For example:

select * from ACCOUNTS_DETAILS
where ACCOUNT_ID=1001
union
select * from ACCOUNTS_DETAILS
where ACCOUNT_ID=1002
Andronicus
  • 25,419
  • 17
  • 47
  • 88
-6

Sometimes you can't see the wood for the trees :)

Your original SQL ..

SELECT contactid 
 WHERE flag = 'Volunteer' 
   AND flag = 'Uploaded'...

Should be:

SELECT contactid 
 WHERE flag = 'Volunteer' 
   OR flag = 'Uploaded'...
Tisho
  • 8,320
  • 6
  • 44
  • 52
Kevin
  • 23
  • 1
  • 2
    I don't believe this will return the results the OP desired. The contactIds need to match ALL flags, not one or more of them. – Kildareflare Jul 22 '13 at 21:13