sql对面的加入

时间:2013-02-11 08:18:36

标签: sql join

我有两个表通过MAP表组合

Table ANIMAL:
+------+--------------+
| id   |  description |
+------+--------------+
|  2   |  Ape         |
|  3   |  Lion        |
+------+--------------+


Table MAP:
+-----------+---------+
| animal_id | legs_id |
+-----------+---------+
|   2       | 11      |
+-----------+---------+


Table LEGS:
+------+--------------+
|  id  |     legs     |
+------+--------------+
| 10   |      4       |
| 11   |      2       |
+------+--------------+

我需要在LEGS表中没有地图条目的动物,如下所示:

 !(select *  
  from ANIMAL as a  
  JOIN MAP as m ON (a.id = m.animal_id)  
  JOIN LEGS as l ON (m.legs_id = l.id) )

应该给我'狮子'作为结果

4 个答案:

答案 0 :(得分:6)

使用LEFT JOIN

SELECT  a.*
FROM    animal a
        LEFT JOIN Map b
            On a.id = b.animal_id
WHERE   b.animal_id IS NULL

要进一步了解联接,请访问以下链接:

答案 1 :(得分:4)

Select * from Animal A
left join Map M on A.id=M.animal_id
where M.animal_id is null;

答案 2 :(得分:4)

试试这个:

SELECT a.*
FROM animal a
WHERE a.id NOT IN (SELECT animal_id FROM Map m JOIN Legs l
                   ON m.legs_id = l.id)

答案 3 :(得分:0)

你能不能做一个简单的查询来返回没有相关地图记录的所有动物......即

SELECT
   *
FROM
   Animal
WHERE
   animal_id not in (SELECT animal_id FROM Map)