在SQL中使用UNION垂直连接表行

时间:2016-05-01 21:32:01

标签: mysql sql-server union

当我使用UNION

将他们加在一起时,我有2个表格Student and Staff
SELECT STUNAME, STUGENDER,
   FROM STUDENT
   UNION
   SELECT STFNAME, STFGENDER
   FROM STAFF
   ORDER BY 1 ASC;

这个名字在输出中是混合的,有没有办法像这样垂直地分开它们,但仍然使用UNION,我已经对此进行了分配并且仍然卡住了

STUNAME
Alvin
Jane
STFNAME
Lincoln
Kate

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你应该使用这样的东西:

(SELECT STUNAME, STUGENDER, 'student' as student FROM STUDENT)
UNION 
(SELECT STFNAME, STFGENDER, 'staff' as staff FROM STAFF)
order by 3,1 asc

答案 1 :(得分:0)

SELECT StuName as cName, StuGender as Gender, 'Student' as Status
   From Student
UNION
SELECT StfName as cName, StfGender as Gender, 'Staff' as Status
   From Staff

字段需要命名相同,Status别名字段将保存它们所属的分类。

答案 2 :(得分:0)

尝试此查询..

SELECT CONCAT('Student',@curRow := @curRow + 1) AS student,STUNAME, STUGENDER FROM STUDENT JOIN (SELECT @curRow := 0) r
UNION 
SELECT CONCAT('Staff',@curRow1 := @curRow1 + 1) AS staff,STFNAME, STFGENDER FROM STAFF JOIN (SELECT @curRow1 := 0) r1;