[英]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. Assigned_by和Assigned_to存储用户的ID值。我必须在同一查询中显示Assigned_by和Assigned_to值。
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. 如何在同一查询中添加u.id = t.assigned_to。
You need to join the user
table twice with different alias names 您需要使用不同的别名将user
表连接两次
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 使用显式联接和concat
进行字符串添加
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
注意避免 from user u,task t where u.id=t.assigned_by
旧方法 from user u,task t where u.id=t.assigned_by
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.