如何在合并两个表后,按两个表中具有相同列名的列排序?

des4xlb0  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(411)

以下是两张表:

Create table If Not Exists Customers (Id int, Name varchar(255));
Create table If Not Exists Orders (Id int, CustomerId int);
insert into Customers (Id, Name) values ('1', 'Joe');
insert into Customers (Id, Name) values ('2', 'Henry');
insert into Customers (Id, Name) values ('3', 'Sam');
insert into Customers (Id, Name) values ('4', 'Max');
insert into Orders (Id, CustomerId) values ('1', '3');
insert into Orders (Id, CustomerId) values ('2', '1');
insert into Orders (Id, CustomerId) values ('3', '5');
insert into Orders (Id, CustomerId) values ('4', '6');

我将两个表的左连接和右连接合并:

select *
from customers as c
left join orders as o
on c.id = o.customerid

union

select *
from customers as c
right join orders as o
on c.id = o.customerid;

但是我想从表customers订购id设置的结果:

select

* 

from
customers as c
left join
orders as o
on
c.id = o.customerid

union

select

* 

from
customers as c
right join
orders as o
on
c.id = o.customerid
order by
c.id;

但是mysql的响应是“错误代码:1250。其中一个SELECT中的表'c'不能用于“全局顺序子句”。所以我把代码改成:

select

* 

from
customers as c
left join
orders as o
on
c.id = o.customerid

union

select

* 

from
customers as c
right join
orders as o
on
c.id = o.customerid
order by
id;

但是mysql的响应是“错误代码:1052。order子句中的“id”列不明确。
我真的理解这两个答复,但我也想知道如何通过id订购后,从客户联盟?

kgsdhlau

kgsdhlau1#

是的,您需要通过将当前查询作为子查询来进行全局排序,就像通过分别别名id列:

select *
  from
  (
   select c.id as c_id, c.name, o.id as o_id, o.CustomerId
     from customers as c
     left join orders as o
       on c.id = o.customerid
    union    
   select c.id as c_id, c.name, o.id as o_id, o.CustomerId
     from customers as c
    right join orders as o
       on c.id = o.customerid    
  ) q
 order by q.c_id
7rtdyuoh

7rtdyuoh2#

也许你需要:

(
select c.id c_id, c.name, o.id o_id
from Customers as c
left join Orders as o on c.id = o.customerid
)
union
(
select o.customerid, c.name, o.id
from Customers as c
right join Orders as o on c.id = o.customerid
)
order by c_id;

小提琴

相关问题