选择包含由连接表的不同行创建的列的语句

时间:2016-12-01 21:38:24

标签: sql

2桌

用户cols =姓名,电子邮件

joe|joe@gmail.com
sara|sara@hotmail.com
alan|alan@gmail.com

表2是extras cols = name,col,value

joe|favoritecolor|blue
joe|boss|sam
sara|favoritecolor|green

(实际上扩展了第一个表的模式,但没有让sql引擎注意到它)

让人们最喜欢的颜色

Select  name
      , value As favoritecolor
From    user
      , extras
Where   extras.name = user.name
        And extras.col = 'favoritecolor'

但我如何获得最喜欢的颜色和老板?

请注意此查询所需的输出

select name,email,favoritecolor,boss from user

joe|joe@gmail|blue|sam
sara|sara@hotmail.com|green|<null>
alan|alan@gmail.com|<null>|<null>

3 个答案:

答案 0 :(得分:5)

您可以使用别名

在同一个表上使用双联接

(如果键始终存在则连接使用内连接,否则使用左连接匹配)

 select a.name, e1.value  as favoritecolor , e2.value as boss
 from user
 INNER JOIN extras as e1 on e1.name = user.name and e1.col = 'favoritecolor'
 INNER JOIN extras as e2 on e2.name = user.name and e2.col = 'boss'

如果你的col不匹配,你应该使用左连接

 select a.name, e1.value  as favoritecolor , e2.value as boss
 from user
 left JOIN extras as e1 on e1.name = user.name and e1.col = 'favoritecolor'
 left JOIN extras as e2 on e2.name = user.name and e2.col = 'boss'

如果你总是喜欢颜色关系但不总是老板

 select a.name, e1.value  as favoritecolor , e2.value as boss
 from user
 Inner JOIN extras as e1 on e1.name = user.name and e1.col = 'favoritecolor'
 left JOIN extras as e2 on e2.name = user.name and e2.col = 'boss'

答案 1 :(得分:2)

首先,学会使用正确的JOIN语法。 从不FROM子句中使用逗号。 始终使用正确的JOIN语法。

您可以使用多个连接执行所需操作:

select u.name, efc.value as favoritecolor,
       eb.value as boss
from user u left join
     extras efc
     on efc.name = u.name and efc.col = 'favoritecolor' left join
     extras eb
     on eb.name = u.name and eb.col = 'boss';

需要left join以确保不会因为缺少特定值而过滤行。

答案 2 :(得分:0)

SELECT
   b.name    AS ExtraName,
   b.col     AS ExtraCol,
   b.value   AS ExtraValue,
   a.name    AS UserName,
   a.email   AS UserEmail
FROM User A INNER JOIN Extras B ON B.name = A.name
WHERE B.col = 'favorite color' AND b.value = 'Boss'