GrailsLearner
GrailsLearner

Reputation: 525

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.

Upvotes: 0

Views: 1148

Answers (2)

juergen d
juergen d

Reputation: 204746

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

Upvotes: 2

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

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

Upvotes: 1

Related Questions