簡體   English   中英

如何在 MySQL 中組合具有相同列名的 3 個表?

[英]How to combine 3 tables having same column names in MySQL?

如何實現目標輸出?

TABLE: degree

region       degree 
-------------------
Cavite          2
Manila          2

TABLE: nondegree

region      non-degree
----------------------
Cavite          2
Manila          2
Laguna          2

TABLE: shortcourse

region      short-course
------------------------
Cavite          2
Laguna          2


OBJECTIVE:

region    degree    non-degree  short-course   total
----------------------------------------------------
Cavite      2           2           2           6
Manila      2           2           0           4
Laguna      0           2           2           4

我試過使用 union 和 union all 但我得到的只是這種輸出

region       degree 
-------------------
Cavite          2
Manila          2
Cavite          2
Manila          2
Laguna          2
Cavite          2
Laguna          2

由於 region 列,我在加入這 3 個表時遇到了模棱兩可的錯誤。

SELECT region, 
       SUM(degree) degree, 
       SUM(nondegree) nondegree, 
       SUM(shortcourse) shortcourse, 
       SUM(degree) + SUM(nondegree) + SUM(shortcourse) total
FROM ( SELECT region, degree, 0 nondegree, 0 shortcourse
       FROM degree
     UNION  ALL
       SELECT region, 0, nondegree, 0
       FROM nondegree
     UNION  ALL
       SELECT region, 0, 0, shortcourse
       FROM shortcourse ) total_data
GROUP BY region

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM