mysql连接表
我是连接表的新手。
ClassList
========================
ID Level
1 2
2 2
3 4
4 1
5 3
6 7
BoysList
========================
ID Name Age
1 Alex 13
2 Arnold 16
3 Barny 15
GirlsList
========================
ID Name Age
4 Arnie 12
5 Martha 17
6 Beth 15
我能够加入两张桌子。但是,如果在这种情况下,您必须首先合并两个表(BoysList 和 GirlsList),然后将其与 ClassList 连接,该怎么办?
结果集将是:
Result
================================================
ID Name
4 Arnie
6 Beth
5 Martha
1 Alex
2 Arnold
3 Barny
结果的顺序将是男孩女孩在前的列表,名称为 ASC。如何实现这一点?
I am new with joining tables.
ClassList
========================
ID Level
1 2
2 2
3 4
4 1
5 3
6 7
BoysList
========================
ID Name Age
1 Alex 13
2 Arnold 16
3 Barny 15
GirlsList
========================
ID Name Age
4 Arnie 12
5 Martha 17
6 Beth 15
I was able to join two tables. But, what if, in this situation, you have to combine first the two tables (BoysList and GirlsList) and then join it with ClassList.
The Resultset would be:
Result
================================================
ID Name
4 Arnie
6 Beth
5 Martha
1 Alex
2 Arnold
3 Barny
order of the result would be list of boys girls first, name ASC. How do accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您要做的第一件事就是
UNION
BoysList 和 GirlsList,然后INNER JOIN
将其与 ClassListthe first thing you will do is to
UNION
the BoysList and GirlsList thenINNER JOIN
it with ClassList您可以使用 union all
(希望这个查询没有错误)
选择 cl.id、bl.name
来自 ClassList cl、BoysList bl
其中 cl.id = bl.id
按 bl.name 排序
联合所有
选择 cl.id、gl.name
来自 ClassList cl、GirlsList gl
其中 cl.id = gl.id
按 cl.name 排序
修改后的查询:
select cl.id, bl.name, 'A' as ket
来自 boyList bl、classList cl
其中 bl.id = cl.id
联合所有
选择 cl.id、gl.name、'B' 作为 ket
来自girlList gl、classList cl
其中 gl.id = cl.id
按 ket desc、名称排序
You can use union all
(hope this query isn't error)
select cl.id, bl.name
from ClassList cl, BoysList bl
where cl.id = bl.id
order by bl.name
union all
select cl.id, gl.name
from ClassList cl, GirlsList gl
where cl.id = gl.id
order by cl.name
Revised query:
select cl.id, bl.name, 'A' as ket
from boyList bl, classList cl
where bl.id = cl.id
union all
select cl.id, gl.name, 'B' as ket
from girlList gl, classList cl
where gl.id = cl.id
order by ket desc, name
除了
UNION
之外,您还可以使用OUTER JOIN
:Besides
UNION
, you can useOUTER JOIN
: