如何加入/联合查询

时间:2017-06-18 19:15:21

标签: mysql

我有一个快速的问题,我无法找到答案。

(SELECT Student_Name AS 'First two from Quiz' FROM events WHERE Event_Name LIKE 'Quiz' ORDER BY Student_Name LIMIT 2)
UNION ALL
(SELECT Student_Name as 'Last two from Quiz' FROM (SELECT Student_Name FROM events WHERE Event_Name LIKE 'Quiz' ORDER BY Student_Name DESC LIMIT 2) as q ORDER BY Student_Name)
UNION ALL
(SELECT Student_Name as 'Last two from Sqlizer' FROM (SELECT Student_Name FROM events WHERE Event_Name LIKE 'Sqlizer' ORDER BY Student_Name DESC LIMIT 2) as w ORDER BY Student_Name)
UNION ALL
(SELECT Student_Name AS 'First two from Sqlizer' FROM events WHERE Event_Name LIKE 'Sqlizer' ORDER BY Student_Name LIMIT 2)

这是我的一些代码。我需要将它们彼此显示出来。就像一个接一个。由于union all,它显示在一列中。你对这个问题的解决方案有什么想法吗?拜托,这是时间问题。我想在2个小时内完成它。

1 个答案:

答案 0 :(得分:0)

我很确定有更优雅的解决方案,但这是我有时间想出来的。您可以使用连接并排放置表格,但这样可以为您提供所有可能的数据排列,这是我们不想要的。所以我为四个表中的每个表添加了一个计数器,只输出一个数据排列(计数器全部相等):

SELECT a.Student_Name AS 'First two from Quiz', b.Student_Name as 'Last two from Quiz', c.Student_Name as 'Last two from Sqlizer', d.Student_Name AS 'First two from Sqlizer'
FROM
(SELECT  @s:=@s+1 serial_no, Student_Name FROM events, (select @s:=0) as s WHERE Event_Name LIKE 'Quiz' ORDER BY Student_Name LIMIT 2) as a,
(SELECT  @s1:=@s1+1 serial_no, t2.Student_Name FROM (SELECT Student_Name FROM events WHERE Event_Name LIKE 'Quiz' ORDER BY Student_Name DESC LIMIT 2) as t2, (select @s1:=0) as s) as b,
(SELECT  @s2:=@s2+1 serial_no, t3.Student_Name FROM (SELECT Student_Name FROM events WHERE Event_Name LIKE 'Sqlizer' ORDER BY Student_Name DESC LIMIT 2) as t3, (select @s2:=0) as s) as c,
(SELECT  @s3:=@s3+1 serial_no, Student_Name FROM events, (select @s3:=0) as s WHERE Event_Name LIKE 'Sqlizer' ORDER BY Student_Name LIMIT 2) as d

WHERE a.serial_no = b.serial_no and c.serial_no = d.serial_no and b.serial_no = c.serial_no