用户表
id | name | role
1 | samjad | user
2 | saneer | constructor
项目表
id | name | user_id | constructor_id |
1 | school | 1 | 2 |
如何根据项目表ID从一个表中获取所有详细信息。
我想选择
projectname username, constroctorname, user_id, constroctor_id
在一行
答案 0 :(得分:1)
事实上你在项目表和用户之间有两个关系(一个用户用户,一个用于constroctor)你可以使用用户连接两次
select p.name, u1.username, u2.username, p.user_id, p.constroctor_id
from projects as p
inner join user as u1 on p.user_id = u1.id
inner join user as u2 on p.constroctor_id = u2.id
答案 1 :(得分:1)
您可以将用户表加入两次 - 一次作为用户,然后作为构造函数。
select p.name as projectname,
u.name as username,
c.name as contructorname,
p.user_id,
p.contructor_id
from projects p
left join user u on p.user_id = u.id
left join user c on p.contructor_id = c.id
where u.role = 'user' -- check if the said user has role "user"
and c.role = 'constructor'; -- check if the said constructor has role "constructor"
答案 2 :(得分:0)
您可以使用concat()函数:
SELECT CONCAT(field1, field2, field3);
https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat
或CONCAT_WS(分隔符,str1,str2,...)
答案 3 :(得分:0)
假设有一个名为Constructor的表,其中包含列名和constructor_id,那么您的查询将是
select
p.name as projectname,
u.name as username,
c.name as constructorname,
u.id as userid,
c.id as constructorid
from
projects p
inner join user u on p.user_id=u.id
inner join constructor c on p.constructor_id=c.id
答案 4 :(得分:0)
使用联接。你可能想要一个INNER JOIN:
SELECT * -- actually include only the fields you need
FROM Projects p
INNER JOIN Users u ON u.id = p.user_id
INNER JOIN Users uc ON uc.id = p.constructor_id
答案 5 :(得分:0)
您需要在其键上加入表格。在这种情况下,如下所示:
select p.name as projectname
, u.name as username
, if(u.role='constructor',u.name,null) as constructorname
, p.user_id, p.constructor_id
from users u
join projects p
on p.user_id = u.id;