假设您有两个表:
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
提前致谢
答案 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;