如何在mysql中加入3个表
Posted
技术标签:
【中文标题】如何在mysql中加入3个表【英文标题】:how to left join 3 tables in mysql 【发布时间】:2013-12-01 08:43:00 【问题描述】:我有 3 张桌子:
成员(网名,姓名)
奖项(nic,aw_name)
冠军(nic,ch_name)
一个人可以拥有多个奖项或冠军。比如 Richard 有 2 个奖项和 3 个冠军,而 Steve 没有任何奖项和冠军。
现在我想列出获得奖项和冠军的人。例如:
| nic | name | aw_name | ch_name |
|----------|------------|-------------|-------------------|
| 1 | Richard | award 1 | championship 1 |
| 1 | Richard | award 2 | championship 2 |
| 1 | Richard | | championship 3 |
| 2 | Steve | | |
谁能帮帮我?谢谢!
【问题讨论】:
如何你认为你可以做到..? ***.com/questions/9853586/sql-join-multiple-tables 【参考方案1】:试试这个:
SELECT
members.nic,
members.name,
awards.aw_name,
championships.ch_name
FROM
(
SELECT
CASE WHEN @curNic = members.nic THEN @curRow := @curRow + 1 ELSE @curRow := 1 END num,
@curNic := members.nic nic,
name
FROM
members LEFT JOIN
(
SELECT nic FROM awards UNION ALL
SELECT nic FROM championships
) tmp ON tmp.nic = members.nic JOIN
(SELECT @curNic := null, @curRow := 0) r
) members LEFT JOIN
(
SELECT
CASE WHEN @curNic1 = nic THEN @curRow1 := @curRow1 + 1 ELSE @curRow1 := 1 END num,
@curNic1 := nic nic,
aw_name
FROM
awards JOIN
(SELECT @curNic1 := null, @curRow1 := 0) r
) awards ON awards.nic = members.nic AND awards.num = members.num LEFT JOIN
(
SELECT
CASE WHEN @curNic2 = nic THEN @curRow2 := @curRow2 + 1 ELSE @curRow2 := 1 END num,
@curNic2 := nic nic,
ch_name
FROM
championships JOIN
(SELECT @curNic2 := null, @curRow2 := 0) r
) championships ON championships.nic = members.nic AND championships.num = members.num
WHERE
awards.nic IS NOT NULL OR championships.nic IS NOT NULL OR members.num = 1
如果mysql中有FULL OUTER JOIN会更容易,但是没有。
小提琴:http://www.sqlfiddle.com/#!2/31d47/43
【讨论】:
但这会为理查德返回 6 行并重复获奖和冠军 @MohamadMehdiHabibi 使用这种模式并不容易,但请参阅我的更新。【参考方案2】:试试这个。
SELECT m.nic,
m.name,
a.aw_name,
c.ch_name
FROM members m
LEFT JOIN awards AS a ON m.nic = a.nic
LEFT JOIN championships AS c ON m.nic = c.nic
GROUP BY m.nic, m.name
【讨论】:
【参考方案3】:您可以根据自己的要求使用连接来合并表。
SELECT mem.nic,mem.name, awd.aw_name, chm.ch_name
FROM members mem
LEFT JOIN awards AS awd ON mem.nic = awd.nic
LEFT JOIN championship AS chm ON mem.nic = chm.nic
GROUP BY mem.nic, mem.name;
更多请点击:http://www.w3schools.com/sql/sql_join.asp
【讨论】:
以上是关于如何在mysql中加入3个表的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 eloquent hasmanythrough 或 hasonethrough 在 laravel 中加入 3 个表