简体   繁体   English

在两个表之间加入

[英]Join between two tables

table1 - doctors table1 - 医生

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

table2 - engineers table2 - 工程师

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

Desired output: 期望的输出:

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

I tried with the below query but am getting more count of docs and engg. 我尝试了下面的查询,但我得到了更多的docs和engg。 Someone please correct me.. 有人请纠正我..

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

I think your problem is that you are getting a cross-product of both the tables with these set of values. 我认为您的问题是,您正在使用这些值集合获得两个表的交叉产品。

Try using: 尝试使用:

tableA NATURAL JOIN tableB.

You can use UNION ALL 你可以使用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

You need to 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