简体   繁体   中英

Join two columns of one table to the same column of another table

I have two tables User and task.

User Table                    
int id
fname
lname

Task Table
int id
int assigned_by
int assigned_to

assigned_by and assigned_to store the id values of the user.I have to display assigned_by and assigned_to values in the same query.

select u.fname+ +u.lname 
from user u,task t 
where u.id=t.assigned_by;

How to add u.id=t.assigned_to in the same query.

You need to join the user table twice with different alias names

select CONCAT_WS(' ', u_by.fname, u_by.lname) as by_name,
       CONCAT_WS(' ', u_to.fname, u_to.lname) as to_name
from task t 
join user u_by on u_by.id = t.assigned_by
join user u_to on u_to.id = t.assigned_to

Use explicit join and concat for string addition

select concat(u1.fname ,u2.lname) as assigned_by_name,
 concat(u2.fname,u2.lname) as assigned_to_name
from task t 
join user u1 on u1.id = t.assigned_by
join user u2 on u2.id = t.assigned_to

Note Avoid this old method join from user u,task t where u.id=t.assigned_by

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