简体   繁体   English

将一个表的两列连接到另一表的同一列

[英]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.

相关问题 Sequelize将一张表的两列连接到另一张表的同一列 - Sequelize join two columns of one table to the same column of another table 将一个表的两列连接到另一表的一列 - Join two columns from one table to one column from another SQL连接-一列用作另一表中两列的ID - SQL join - one column serving as ID for two columns in another table 将两列与另一个表的相同字段连接起来 - join two column with same field of another table 如何将一个表中的两个或更多列与另一个表中的一个列联接在一起,即使第一个表列中的值为NULL - How to join two or more columns from one table with one column from another table, even there are NULL values in first table columns MySQL-连接两个表,表1中不同的列在表2中的同一列上 - MySQL - Join two tables, different columns in table 1 on the same column in table 2 如何将SQL表中的2列连接到另一个SQL表中的一列? - How to join 2 columns in a SQL table to one column in another SQL table? 将表1中的一列左连接到表2中的两列 - Left Join One Column in Table 1 to Two Columns in Table 2 一个表中的两列是否可以具有另一表中同一列的外键? - Can two columns from one table have a foreign key to the same column in another table? sql连接中存在相同名称的两列时,如何从一个表列获取值 - How to get value from one table column when two columns of the same name exist in an sql join
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM