MySQL连接以查看其他表中是否存在记录

时间:2013-01-10 09:36:04

标签: mysql

我有以下表格:

CREATE TABLE `accommodations` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) 

CREATE TABLE `accommodations_exclude` (
  `id_accommodation` int(11) unsigned NOT NULL,
  `id_course` int(11) NOT NULL,
  UNIQUE KEY `id_course` (`id_course`,`id_accommodation`)
) 

在住宿表中有4条记录,在accommodation_exclude中还有更多。现在我希望有一个查询总是从住宿表中给我所有记录,并作为额外字段加入,以查看住宿是否也存在于accommodation_exclude表中。

例如;在accommodation_exclude中有一行id_accommodation = 2,id_course = 16。

我想要一个结果集向我展示以下内容:

accommodation.id, accommodation.name, accommodation_exclude.id_accommodation, accommodation_exclude.id_course

1,'acco 1',null,null
2,'acco 2',2,16
3,'acco 3',null,null
4,'acco 4',null,null

我现在的查询就是这个:

SELECT *
FROM accommodations a
LEFT JOIN accommodations_exclude ae ON a.id = ae.id_accommodation 
WHERE ae.id_course = 16

但这只给了我一个结果集

2,'acco 2',2,16

而不是应该具有空值的住宿

我在这里做错了什么想法?

5 个答案:

答案 0 :(得分:6)

ae.id_course = 16条款从WHERE移至LEFT JOIN

SELECT *
FROM accommodations a
LEFT JOIN accommodations_exclude ae ON
    a.id = ae.id_accommodation
    AND ae.id_course = 16

您应该将WHERE视为最终结果集的过滤器,与链接表有关的任何内容都应该是JOIN中的条件。

您的原始WHERE ae.id_course = 16过滤掉了结果集中的NULL ae.id_course行。

答案 1 :(得分:1)

accommodations_exclude表格设为左表格,或者使用RIGHT JOIN代替:

SELECT
 a.id, 
 a.name, 
 ae.id_accommodation, 
  ae.id_course
FROM accommodations a
RIGHT JOIN accommodations_exclude ae ON a.id = ae.id_accommodation;

SQL Fiddle Demo

这会给你:

| ID |   NAME | ID_ACCOMMODATION | ID_COURSE |
----------------------------------------------
|  1 | acco 1 |           (null) |    (null) |
|  2 | acco 2 |                2 |        16 |
|  3 | acco 3 |           (null) |    (null) |
|  4 | acco 4 |           (null) |    (null) |

请注意:对于您发布的示例数据,WHERE ae.id_course = 16只会返回一行ae.id_course = 16

答案 2 :(得分:0)

它不会根据你的情况再给你

WHERE ae.id_course = 16

它为您提供了正确的结果集。删除它,它将列出所有这些。

答案 3 :(得分:0)

SELECT ACCOMMODATION.ID, ACCOMMODATION.NAME,
       ACCOMMODATION_EXCLUDE.ID_ACCOMMODATION,
       ACCOMMODATION_EXCLUDE.ID_COURSE
  FROM ACCOMMODATION, ACCOMMODATION_EXCLUDE
 WHERE ACCOMMODATION.ID = ACCOMMODATION_EXCLUDE.ID_ACCOMMODATION(+)
       AND ACCOMMODATION_EXCLUDE.ID_COURSE = 16

答案 4 :(得分:0)

The answer from "Ross McNab"是最好的,但如果您在JOIN中没有使用条件,则可以使用此示例代码:

SELECT *
FROM accommodations a
LEFT JOIN accommodations_exclude ae ON a.id = ae.id_accommodation 
WHERE ae.id_course = 16 OR ae.id_course IS NULL