[英]How to combine multiple tables with different columns
I have 3 tables.我有 3 张桌子。 I want the
school
table to set the data of major_subject
and get the minor_subject
on the result.我希望
school
表设置major_subject
的数据并得到minor_subject
的结果。
And also set automatically units 3.0
for major_subject
since this table has no column.并且还自动为
major_subject
设置units 3.0
,因为该表没有列。
I tried to use UNION
but I get error since major_subject
column is not the same with minor_subject
table.我尝试使用
UNION
但我收到错误,因为major_subject
列与minor_subject
表不同。
school major_subject
| school_id | school_name | | subj_name | date_offered |
----------------------------- ---------------------------------
| 1 | schoolA | | Business101 | 2021/01/01 |
| 2 | schoolB | | Marketing101 | 2021/01/01 |
| 3 | schoolC |
minor_subject
| school_id | subj_name | units | date_offered |
----------------------------------------------------
| 1 | Math | 1.0 | 2021/01/01 |
| 1 | English | 1.0 | 2021/01/01 |
| 1 | Science | 1.0 | 2021/01/01 |
| 2 | History | 2.0 | 2021/01/01 |
And the result table would be like:结果表如下:
| school_id | subj_name | units | date_offered |
---------------------------------------------------------
| 1 | Business101 | 3.0 | 2021/01/01 |
| 1 | Marketing101 | 3.0 | 2021/01/01 |
| 1 | Math | 1.0 | 2021/01/01 |
| 1 | English | 1.0 | 2021/01/01 |
| 1 | Science | 1.0 | 2021/01/01 |
| 2 | Business101 | 3.0 | 2021/01/01 |
| 2 | Marketing101 | 3.0 | 2021/01/01 |
| 2 | History | 2.0 | 2021/01/01 |
| 3 | Business101 | 3.0 | 2021/01/01 |
| 3 | Marketing101 | 3.0 | 2021/01/01 |
You can CROSS
join school
to major_subject
to get all the combinations of the rows of the 2 tables and then with UNION ALL
add the rows from minor_subject
:您可以将
school
CROSS
加入major_subject
以获取 2 个表的行的所有组合,然后使用UNION ALL
添加来自minor_subject
的行:
SELECT s.school_id, m.subj_name, 3.0 units, m.date_offered
FROM school s CROSS JOIN major_subject m
UNION ALL
SELECT school_id, subj_name, units, date_offered
FROM minor_subject
ORDER BY school_id
See the demo .请参阅演示。
Results:结果:
> school_id | subj_name | units | date_offered
> --------: | :----------- | ----: | :-----------
> 1 | Business101 | 3.0 | 2021-01-01
> 1 | Marketing101 | 3.0 | 2021-01-01
> 1 | Math | 1.0 | 2021-01-01
> 1 | English | 1.0 | 2021-01-01
> 1 | Science | 1.0 | 2021-01-01
> 2 | History | 2.0 | 2021-01-01
> 2 | Marketing101 | 3.0 | 2021-01-01
> 2 | Business101 | 3.0 | 2021-01-01
> 3 | Business101 | 3.0 | 2021-01-01
> 3 | Marketing101 | 3.0 | 2021-01-01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.