0

我有两个表我想选择出现在表位置中的所有记录,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   | 
+---+-------------+-------+
4

2 回答 2

2

您需要更改为 a但您的子句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

于 2012-09-08T18:26:32.950 回答
0

尝试更改您的JOIN连接LEFT JOIN和顺序。

SELECT `cl`.`locationId`, `cl`.`cardId`, `l`.`name`
FROM `location_cards` as cl
left JOIN `locations` as l   ON `l`.`cardId` = `cl`.`cardId`
WHERE `l`.`id` =  '2'
于 2012-09-08T18:22:07.287 回答