使用MySQL从不同的表行明智地合并两列

时间:2019-03-21 00:40:01

标签: mysql sql

我有桌子 学生


 --------------
| Type | Class |
 --------------
 --------------
| Good |  12   |
 --------------
| Avg  |  11   |
 --------------

类型

 -----------------------------
| Name | Grade | Type | Class |
 -----------------------------
| John |  A+   | Good |  12   |
 -----------------------------
| Tine |  B    | Avg  |  11   |
 -----------------------------

现在我想通过逐行合并来获得结果,这样SQL查询的结果将是

lag()

1 个答案:

答案 0 :(得分:2)

假设每个表中的列数相同,则可以按行号链接它们。如果没有ORDER BY子句,尽管行号不确定,因此您不能保证结果。

在MySQL 5.7和更低版本中:

SELECT Name, Grade, Type, Class
FROM (SELECT *, @rownum := @rownum + 1 AS rownum
      FROM Student
      CROSS JOIN (SELECT @rownum := 0) r
      ) s
JOIN (SELECT *, @rownum2 := @rownum2 + 1 AS rownum
      FROM Type
      CROSS JOIN (SELECT @rownum2 := 0) r
      ) t ON t.rownum = s.rownum

在MySQL 8.0及更高版本中:

SELECT Name, Grade, Type, Class
FROM (SELECT *, ROW_NUMBER() OVER () AS rownum
      FROM Student) s
JOIN (SELECT *, ROW_NUMBER() OVER () rownum
      FROM Type) t ON t.rownum = s.rownum

输出:

Name    Grade   Type    Class
John    A+      Good    12
Tina    B       Avg     11

Demo on dbfiddle