我有一个查询返回给我:
+-------------+-------------+-------------+-------------+
| L_1_teacher | L_1_student | L_2_teacher | L_2_student |
+-------------+-------------+-------------+-------------+
| 333333 | 33667 | 111111 | 33668 |
| 222222 | 33667 | 111111 | 33669 |
| 222222 | 33667 | 111111 | 33670 |
+-------------+-------------+-------------+-------------+
我需要" union"两个老师专栏。预期的输出是:
+-------------+
| teachers |
+-------------+
| 333333 |
| 222222 |
| 111111 |
+-------------+
由于这是一个很长的查询,我无法负担两次(实际上,我有两个以上的教师级别),在每个级别选择教师并将它们联合起来。
我尝试了什么:我将此查询的结果存储到临时表tree
并执行了:
SELECT L_1_teacher as "teachers" FROM tree
UNION
SELECT L_2_teacher as "teachers" FROM tree
但它给我一个错误说Error Code: 1137. Can't reopen table: 'tree'
(MySQL禁止在查询中两次使用相同的临时表)
我该如何做到这一点?
答案 0 :(得分:3)
我确认你的想法,你不能在同一个查询中引用两次到临时表。这已在MySQL doc中记录。
另一种方法是创建另一个临时表。
CREATE TEMPORARY TABLE tree2 LIKE tree;
INSERT INTO tree2 select * from tree;
SELECT L_1_teacher as "teachers" FROM tree
UNION
SELECT L_2_teacher as "teachers" FROM tree2