Mysql查询:JOINS

时间:2016-06-22 10:17:00

标签: mysql

我有以下表格:

转移表:

ID | storagefrom | storageto 
1  | 2           | 3

存储表:

ID | Name
2  | Kitchen
3  | Main

我想得到以下结果:

Storage1 | Storage2 
Kitchen   | Main

这是我的疑问:

SELECT storages.name as Storage1, storages.name as Storage2
FROM transfers 
LEFT JOIN storages ON storages.id = transfers.storagefrom
LEFT JOIN storages ON storages.id = transfers.storageto

任何提示?

3 个答案:

答案 0 :(得分:1)

只需使用CASE EXPRESSION和1 JOIN的条件聚合:

SELECT t.id,
       MAX(CASE WHEN s.id = t.storagefrom THEN s.name END) as storage_1,
       MAX(CASE WHEN s.id = t.storageto THEN s.name END) as storage_2
FROM transfer t
LEFT JOIN storages s 
 ON(s.id IN(t.storagefrom,t.storageto))
GROUP BY t.id

如果它只有1条记录且您不关心transfer.id而不是从选择列表中删除它并删除GROUP BY条款。

答案 1 :(得分:1)

只是为你的表添加别名

SELECT s1.name as Storage1, s2.name as Storage2
FROM transfers 
LEFT JOIN storages AS s1 ON s1.id = transfers.storagefrom
LEFT JOIN storages AS s2 ON s2.id = transfers.storageto

答案 2 :(得分:1)

尝试

SELECT T.ID,
       S1.Name Storage1,
       S2.name Storage2 
FROM transfers T
LEFT JOIN storages S1 ON S1.ID = T.storagefrom
LEFT JOIN storages S2 ON S2.ID = T.storageto
  

参考:SQL Fiddle