具有特定条件的SQL合并列

时间:2014-09-01 15:52:41

标签: sql

假设您有两个表:

         table customer     
id  username    startcity   finalcity
1   a               S1         F1
2   b               S2         F2
3   c               S3         F3
4   d               S4         F4

table client        
id  username1   startcity1  finalcity1
5   k               K1          F2
6   l               S6          F3
7   m               S2          F9
8   n               S4          G8

如果我从表客户中选择一个用户名,我想创建一个新表,第一行将包含与我选择的用户名对应的用户名,startcity和finalcity,以下行将包含用户名,startcity1和finalcity1来自表客户端,它具有startcity1 == startcity或finalcity1 == finalcity

例如..如果我从表customer中选择用户名b,则新表应为:

new table   
b   S2  F2
m   S2  F9
k   K1  F2

提前致谢

1 个答案:

答案 0 :(得分:0)

这基本上是union all查询。但是,不保证SQL语句以特定顺序返回结果,因此您需要显式排序:

select id, startcity, endcity
from (select c.id, c.startcity, c.endcity, 1 as ordering
      from customer c
      where c.username = USERNAME
      union all
      select  cl.id, cl.startcity, cl.endcity, 2 as ordering
      from client cl join
           customer c
           on cl.startcity = c.startcity or cl.endcity = c.endcity
     ) c
order by ordering;