简体   繁体   中英

How to order by the column which has the same column name in two tables after union two tables?

These are the two tables:

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');

And I union the left join and right join of the two tables:

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;

But I wanna order the result set by the id from table customers:

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;

But the MySQL response is "Error Code: 1250. Table 'c' from one of the SELECTs cannot be used in global ORDER clause". So I change the code into:

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;

But the MySQL response is "Error Code: 1052. Column 'id' in order clause is ambiguous".

I really understand the two responses but I also want to know how to order by id from customers after the union?

Yes you need a global ordering by making the current query a subquery as by aliasing id columns individually:

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  

Maybe you need in this:

(
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;

fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM