表_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
如何从 table_a
中选择与 table_c_id 1 和 4 关联的所有记录?是否可以有n个table_c_id条件?
以下内容是错误的,但它说明了需要什么。
SELECT table_a.*
FROM table_a
JOIN table_b ON ( table_a_id = id
AND table_c_id = 1
AND table_c_id = 4 )
最佳答案
使用 IN 子句。
编辑:根据发布的评论更新了查询。
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
关于php - 同一字段上具有两个条件的 Sql 内连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6645065/