I needed to come up with a SQL query that returns rows that satisfy multiple conditions. This article describes what I needed to do and the solution:
http://thenoyes.com/littlenoise/?p=58
Basically it uses a bit operation to figure out if a provided string is found.. but I’m having hard time following how it works.
SET @q = 'A,B';
SELECT studentName
FROM quizAnswers
GROUP BY studentName
HAVING
BIT_OR(1 << FIND_IN_SET(question, @q) - 1)
=
(1 << LENGTH(@q) - LENGTH(REPLACE(@q, ',', '')) + 1) - 1; -- This is 2^numValues - 1
+-------------+
| studentName |
+-------------+
| seekwill |
+-------------+
I tested it and it works as expected. Can someone explain how this works?
Thanks,
Amie
I am not going to explain what BIT_OR is doing.
Alternative solution:
If it is possible, I usually prefer pure SQL solutions that do not depend on the vendor-specific features. If what you need is similar to the example in the article you refer to, then this SQL statement should run pretty much on any RDBMS and produce the desired result:
and by playing with
HAVING COUNT...you are even more flexible:Basically you just need to fill
...in partwhere question in (...)and set the value of the COUNT(…), which by default would be the number of answers to check for a Complete Set.