我有4个名为student,address,phone和record的表,我可以使用第一列加入每个表。
学生
+----+-------------+
| id | studentName |
+----+-------------+
| 1 | Name_1 |
| 2 | Name_2 |
+----+-------------+
地址
+----+-------------+
| id | addressName |
+----+-------------+
| 1 | address_1 |
| 1 | address_2 |
| 2 | address_3 |
+----+-------------+
电话
+----+-------------+
| id | phoneNumber |
+----+-------------+
| 1 | 123456 |
| 2 | 987654 |
+----+-------------+
记录
+----+-----------+
| id | recNumber |
+----+-----------+
| 1 | REC001 |
| 2 | REC002 |
+----+-----------+
选择查询
select s.id,s.studentName,a.addressName,p.phoneNumber,r.recNumber
from student s
join address a on s.id=a.id
join phone p on s.id=p.id
join record r on s.id=r.id
这些表上的给了我一个输出
+----+-------------+-------------+-------------+-----------+
| id | studentName | addressName | phoneNumber | recNumber |
+----+-------------+-------------+-------------+-----------+
| 1 | Name_1 | address_1 | 123456 | REC001 |
| 1 | Name_1 | address_2 | 123456 | REC001 |
| 2 | Name_2 | address_3 | 987654 | REC002 |
+----+-------------+-------------+-------------+-----------+
我想将其转换为类似
的内容+----+-------------+-------------+-------------+-----------+-----------+
| id | studentName | addressName | phoneNumber | recNumber | flag |
+----+-------------+-------------+-------------+-----------+-----------+
| 1 | Name_1 | address_1 | null | null | address |
| 1 | Name_1 | address_2 | null | null | address |
| 2 | Name_2 | address_3 | null | null | address |
| 1 | Name_1 | null | 123456 | null | phone |
| 2 | Name_2 | null | 987654 | null | phone |
| 1 | Name_1 | null | null | REC001 | record |
| 2 | Name_2 | null | null | REC002 | record |
+----+-------------+-------------+-------------+-----------+-----------+
flag
列中的值不必是表名,任何常量都可以。
我使用temptable(通过将整个细节添加到一个临时表中并通过使用flag重新插入数据)来完成它。 有没有选择直接获得它?
带有上述数据的答案 0 :(得分:2)
您可以使用UNION
执行此操作:
SELECT id, studentName, addressName,
NULL AS phoneNumber, NULL as recNumber, 'address' as flag
FROM student s
JOIN address a ON s.id = a.id
UNION
SELECT id, studentName, NULL,
phoneNumber, NULL, 'phone' as flag
FROM student s
JOIN phone p ON s.id = p.id
UNION
SELECT id, studentName, NULL,
NULL, recNumber, 'record' as flag
FROM student s
JOIN record r ON s.id = r.id
答案 1 :(得分:0)
您应该能够在查询中使用CASE WHEN和LEFT OUTER JOIN获取额外的列
select s.id,s.studentName,a.addressName,p.phoneNumber,r.recNumber,
CASE WHEN a.addressName IS NOT NULL THEN 'address'
WHEN p.phoneNumber IS NOT NULL THEN 'phone'
ELSE 'record' AS flag
from student s
LEFT OUTER join address a on s.id=a.id
LEFT OUTER join phone p on s.id=p.id
LEFT OUTER join record r on s.id=r.id