LEFT JOIN条件在哪里

时间:2014-02-07 09:30:44

标签: mysql

使用MySQL。我有下表:

database_a.shops
+----+------------+------+---------+
| id |    xtype   | name | city_id |
+----+------------+------+---------+
|  1 | cafe       | good |         |
|  2 | restaurant | boy  |       4 |
|  3 | restaurant | does |       5 |
|  4 | restaurant | fine |       8 |
|  5 | restaurant | oh   |       9 |
+----+------------+------+---------+

database_b.cities
+----------+
| super_id |
+----------+
|        4 |
|        5 |
+----------+

expected results from database_a.shops
+----+------------+------+---------+
| id |    xtype   | name | city_id |
+----+------------+------+---------+
|  4 | restaurant | fine |       8 |
|  5 | restaurant | oh   |       9 |
+----+------------+------+---------+

我使用以下SQL查询:

SELECT * FROM database_a.shops AS shops
LEFT OUTER JOIN database_b.cities AS cities
ON shops.city_id = cities.super_id
WHERE cities.super_id IS NULL AND shops.xtype = 'restaurant'

但是database_a.shops id=1一直在出现。我应该在SQL中修复什么来获得预期的结果?感谢。

2 个答案:

答案 0 :(得分:1)

您只需要将cities.super_id IS NULL更改为cities.super_id IS NOT NULL,左连接将返回左表中的所有行,并使用cities.super_id IS NULL在哪里可以找到找不到匹配项的结果对于cities.super_id

SELECT * FROM database_a.shops AS shops
LEFT OUTER JOIN database_b.cities AS cities
ON shops.city_id = cities.super_id
WHERE cities.super_id IS NOT NULL AND shops.xtype = 'restaurant'

或者您将LEFT OUTER JOIN更改为INNER JOIN

的简单内容
SELECT * FROM database_a.shops AS shops
INNER JOIN database_b.cities AS cities
ON shops.city_id = cities.super_id
WHERE shops.xtype = 'restaurant'

修改 看到这个Fiddle它对我来说没问题

SELECT * FROM shops AS shops
LEFT OUTER JOIN cities AS cities
ON shops.city_id = cities.super_id
WHERE cities.super_id IS  NULL AND shops.xtype = 'restaurant'

答案 1 :(得分:0)

SELECT s.id,s.xtype,s.name,s.city_id FROM spots AS s
LEFT OUTER JOIN cities AS c
ON s.city_id = c.super_id where c.super_id IS NULL and s.xtype = 'restaurant'

Sql fiddle

enter image description here