簡體   English   中英

在兩個表之間加入

[英]Join between two tables

table1 - 醫生

+---------+--------+------+
| country |  state |  doc |
+---------+--------+------+
| india   |  AP    | 20   |
+---------+--------+------+
| india   |  TN    | 30   |
+---------+--------+------+
| india   |  KA    | 10   |
+---------+--------+------+
| US      |  LA    | 30   |
+---------+--------+------+
| US      |  CA    | 10   |
+---------+--------+------+
| US      |  NY    | 50   |
+---------+--------+------+

table2 - 工程師

+---------+--------+-------+
| country |  state |  engg |
+---------+--------+-------+
| india   |  AP    | 100   |
+---------+--------+-------+
| india   |  TN    | 400   |
+---------+--------+-------+
| india   |  KA    | 250   |
+---------+--------+-------+
| US      |  LA    | 140   |
+---------+--------+-------+
| US      |  CA    | 120   |
+---------+--------+-------+
| US      |  NY    | 150   |
+---------+--------+-------+

期望的輸出:

+---------+------+-------+
| country |  doc |  engg |
+---------+------+-------+
| india   | 60   | 750   |
+---------+------+-------+
| US      | 90   | 410   |
+---------+------+-------+

我嘗試了下面的查詢,但我得到了更多的docs和engg。 有人請糾正我..

select country, sum(a.doc), sum(b.engg) 
  from table1 a join table2 b on (a.country = b.country) 

我認為您的問題是,您正在使用這些值集合獲得兩個表的交叉產品。

嘗試使用:

tableA NATURAL JOIN tableB.

你可以使用UNION ALL

SELECT
    country,
    SUM(doc) AS doc,
    SUM(engg) AS engg
FROM
    (SELECT
        country,
        doc,
        0 AS engg
     FROM
        doctors
     UNION ALL
     SELECT
        country,
        0,
        engg
     FROM
        engineers
    ) a
GROUP BY
    country

您需要按國家/地區分組。

select a.country, sum(docSum), sum(enggSum) from
  (select country, sum(doc) docSum from doctors) a
inner join
  (select country, sum(engg) enggSum from engineers)
on a.country = b.country
group by a.country

暫無
暫無

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

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