我有多个表并做了2个子选择(UserRecord,CustomerRecord)我想合并到1个表中
UserRecord
========================
| RecordID | UserName |
========================
| 1 | Sara |
| 1 | Tom |
| 2 | Sara |
| 2 | Kurt |
| 3 | Fre |
========================
Table: CustomerRecord
============================
| RecordID | CustomerName |
============================
| 1 | Jef |
| 2 | Alex |
| 2 | Peter |
============================
Table: This should be the result
=======================================
| RecordID | UserName | CustomerName |
=======================================
| 1 | Sara | - |
| 1 | Tom | - |
| 1 | - | Jef |
| 2 | Sara | - |
| 2 | Kurt | - |
| 2 | - | Alex |
| 2 | - | Peter |
| 3 | Fre | - |
=======================================
- = null
我尝试左,右,左外,右外...加入2张桌子,但我没有得到我想要的东西。
SELECT *
FROM UserRecord AS ur
INNER JOIN CustomerRecord AS cr ON ur.RecordID = cr.RecordID;
答案 0 :(得分:0)
您可以使用简单的union
select recordid, username, null as customername from userrecord
union
select recordid, null, customername from customerrecord
答案 1 :(得分:0)
你想要的不是连接,而是UNION:
SELECT RecordID, UserName, NULL AS CustomerName FROM UserRecord
UNION
SELECT RecordID, NULL AS UserName, CustomerName FROM CustomerRecord
...只是附加两个表中的记录。
我只是添加订单将不是您在预期结果中显示的订单。如果顺序很重要,那么您应该从此UNION中选择SELECT并在此外部选择上添加显式ORDER BY子句。类似的东西:
SELECT * FROM (
SELECT RecordID, UserName, NULL AS CustomerName FROM UserRecord
UNION
SELECT RecordID, NULL AS UserName, CustomerName FROM CustomerRecord
) ORDER BY RecordID, UserName, CustomerName