在两个表之间加入

时间:2015-06-29 15:00:40

标签: sql join

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) 

3 个答案:

答案 0 :(得分:2)

我认为您的问题是,您正在获得具有这些值集的两个表的交叉产品。

尝试使用:

tableA NATURAL JOIN tableB.

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分:0)

您需要按国家/地区分组。

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