我有两个表,我想选择出现在具有cardId 2的表位置中的所有记录,如果位置映射到location_card表中,则该位置的名称

它可以通过进行单独的查询,然后将其加入脚本中来实现,但是我想进行单个查询。我尝试使用下面的查询,但该工作。

SELECT `cl`.`locationId`, `cl`.`cardId`, `l`.`name`
FROM (`locations` as l)
JOIN `location_cards` as cl ON `l`.`cardId` = `cl`.`cardId`
WHERE `l`.`id` =  '2'



location_cards
+---+-------------+-------+
|id | locationId  |cardId |
+---+-------------+-------+
| 1 | 1           |   1   |
| 2 | 1           |   2   |
| 3 | 3           |   2   |
+---+-------------+-------+


locations
+---+-------------+-------+
|id | name        |cardId |
+---+-------------+-------+
| 1 | some        |   1   |
| 2 | pla         |   2   |
| 3 | sdsdffsdf   |   2   |
+---+-------------+-------+

最佳答案

您需要更改为LEFT JOIN,但您的WHERE子句也使用了错误的过滤器:

select c.locationid,
  c.cardid,
  l.name
from locations l
left join location_cards c
  on l.cardid = c.cardid
where l.cardid = 2


SQL Fiddle with Demo

10-08 14:27