我有三个表,user / team / user_team(多对多)
user
-----------
id name
1 Tom
2 Jerry
3 John
team
------------
id name
1 t1
2 t2
3 t3
user_team
---------------------
userid teamid isdeleted
1 t1 0 <----(0 means not deleted record, which can be searched out)
2 t2 1 <----(1 means deleted record, which can not be searched out)
我希望获得所有团队记录信息以及相关的用户信息,如下所示
--------------
tid tname username
1 t1 Tom
2 t2
3 t3
你能告诉我如何编写sql语句吗?
抱歉我的错误。我通过在团队表中再添加一条记录t3来更新我的问题。
答案 0 :(得分:0)
试一试。在这里查看演示小提琴http://sqlfiddle.com/#!2/d918a/2
select t.id as tid,
t.name as tname,
case when ut.isdeleted = 0 then u.name else '' end as username
from team t
left join user_team ut
on t.name = ut.teamid
left join user u
on ut.userid = u.id;
这将导致
答案 1 :(得分:0)
试试这个:
SELECT t.id tid, t.name tname, GROUP_CONCAT(u.name) usernames
FROM user_team ut
LEFT OUTER JOIN team t ON ut.teamid = t.id
LEFT OUTER JOIN user u ON ut.userid = u.id
GROUP BY t.id;
要包含可以搜索到的标志,请尝试此操作(仅包含标志条件):
SELECT t.id tid, t.name tname, GROUP_CONCAT(u.name) usernames
FROM user_team ut
LEFT OUTER JOIN team t ON ut.teamid = t.id
LEFT OUTER JOIN user u ON ut.userid = u.id
AND ut.isdeleted = 1 --this will add a condition for deleted teams
GROUP BY t.id;
答案 2 :(得分:0)
试试这个:
Select a.id as tid
a.name as tname
b.name as username
from team a
LEFT JOIN user_team c on a.name = c.teamid and c.isdeleted = 0
LEFT JOIN user b on b.id = c.userid
答案 3 :(得分:0)
我认为您正在寻找的是一个简单的OUTER JOIN
:
select t.id as tid,
t.name as tname,
u.name as username
from team t
left join user_team ut on t.id = ut.teamid and ut.isdeleted = 0
left join user u on ut.userid = u.id