具有相同字段的两个条件的Sql内连接

时间:2011-07-11 01:55:59

标签: php mysql sql

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

如何从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 )

3 个答案:

答案 0 :(得分:2)

使用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          

答案 1 :(得分:1)

如果我理解正确,你想:

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 

获取与table_c的1& 1相关联的table_a行。 4作为一对。

答案 2 :(得分:0)

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