Sql Inner Join with Two Conditions on Same Field
table_a
:
id label
-----------------
1 l1
2 l2
3 l3
table_b
:
table_a_id table_c_id
---------------------------
1 1
1 3
1 4
2 2
2 4
3 1
3 4
3 8
How can I select all records from table_a
that are associated with both table_c_id 1 AND 4? Is it possible to have n table_c_id conditions?
The following is wrong, but it illustrates what is needed.
SELECT table_a.*
FROM table_a
JOIN table_b ON ( table_a_id = id
AND table_c_id = 1
AND table_c_id = 4 )
Use an IN clause.
EDIT: Updated the query based on the comments posted.
SELECT a.*
FROM table_a a INNER JOIN
(
SELECT table_a_id
FROM table_b
WHERE table_c_id IN(1,4)
GROUP BY table_a_id
HAVING COUNT(DISTINCT table_c_id) > 1
--HAVING COUNT(1) > 1 --This scenario will not address repeating table_c_id's
) b
ON a.id = b.table_a_id
If I understand correctly, you want:
SELECT a.*
FROM table_a a
JOIN (SELECT t.table_a_id
FROM table_b t
WHERE t.table_c_id IN (1, 4)
GROUP BY t.table_a_id
HAVING COUNT(DISTINCT t.table_c_id) = 2) b ON b.table_a_id = a.id
To get matching table_a rows which are associated to table_c's 1 & 4 as a pair.
SELECT a.* , b.table_c_id
FROM table_b b
LEFT JOIN table_a a ON table_a_id = a.id
WHERE b.table_c_id =1
OR b.table_c_id =4
精彩评论