Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a join table so that multiple criteria are met?

Tags:

sql

select

mysql

I have a table with 2 columns (see below). A member can have multiple responses to a question:

RESPONSES
---------
member_id  INT
response_id  INT
SAMPLE DATA
member_id -- response_id
    1     --     3
    1     --     5
    2     --     1
    2     --     5
    2     --     9
    3     --     1
    3     --     5
    3     --     6

What I need to do is query the table for member that meet ALL response criteria. For example I need to select all members that have a response_id of 1 AND 5. I am using the following query:

SELECT DISTINCT member_id 
FROM responses 
WHERE response_id = 1 AND response_id = 5

I would expect to get back member_id's 2 and 3. However I am getting nothing returned. I used EXPLAIN and it shows there is an error in my where query. What am I doing wrong?

Also, is there a function similar to IN where all the criteria must be met in order to return true?

like image 417
Mark J Avatar asked Sep 08 '12 03:09

Mark J


People also ask

How retrieve data from multiple tables in join?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

Can we use WHERE condition in joins?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

What is the most efficient way of joining 2 table in same database?

Relational algebra is the most common way of writing a query and also the most natural way to do so. The code is clean, easy to troubleshoot, and unsurprisingly, it is also the most efficient way to join two tables.


1 Answers

This should work:

SELECT member_ID
FROM responses
WHERE response_ID IN (1,5)
GROUP BY member_ID
HAVING COUNT(DISTINCT response_id) = 2

You need to count the number of records returned which is equal to the number of values supplied in your IN clause.

SQLFiddle Demo

like image 193
John Woo Avatar answered Sep 20 '22 04:09

John Woo