在RDBMS MySQL版本5.5.24-log上连接表

时间:2015-08-07 09:54:52

标签: mysql join

我使用 RDBMS MySQL 版本:

+------------+
| version()  |
+------------+
| 5.5.24-log |
+------------+

在这个数据库中,我有两个表dotablezonesdotableusers

我在这两个表上有一个查询JOIN有问题。

如果在MySQL上尝试这个简单的SELECT查询,我有正确的输出:

SELECT
    LEFT (A.Zones, 2) AS `Area`,
    SUM(A.tot_lines) AS `tot lines`,
    SUM(A.tot_users) AS `tot users`
FROM
    `dotablezones` A
GROUP BY
    `Area`;


+------+-----------+-----------+
| Area | tot lines | tot users |
+------+-----------+-----------+
| ZI   | 106438    | 2919844   |
| ZM   | 98072     | 2914742   |
| ZO   | 75518     | 2824218   |
| ZS   | 39859     | 1102431   |
+------+-----------+-----------+
4 rows in set

现在我需要加入dotablezones dotableusers并尝试此JOIN查询:

SELECT
    LEFT (A.Zones, 2) AS `Area`,
    SUM(A.tot_lines) AS `tot lines`,
    SUM(A.tot_users) AS `tot users`
FROM
    `dotablezones` A
JOIN `dotableusers` CA ON LEFT (A.Zones, 2) = LEFT (CA.Zones, 2)
GROUP BY
    `Area`;


+------+-----------+-----------+
| Area | tot lines | tot users |
+------+-----------+-----------+
| ZI   | 7876412   | 216068456 |
| ZM   | 10395632  | 308962652 |
| ZO   | 18955018  | 708878718 |
| ZS   | 1833514   | 50711826  |
+------+-----------+-----------+
4 rows in set

为什么tot linestot users与第一个简单的SELECT查询相比是Area的不同之处?

有人知道如何解决这个问题?

你能建议吗?

你能帮助我吗?

提前谢谢。

2 个答案:

答案 0 :(得分:0)

您需要了解联接的工作原理。如果表A中的一行可以连接到tableB中的两行,那么输出将导致表A行重复',即表A中的行现在将出现两次,一次对于每个表B行。

https://dev.mysql.com/doc/refman/5.0/en/join.html

来说明,如果你运行以下

SELECT
    LEFT (A.Zones, 2) AS `Area`,
    SUM(A.tot_lines) AS `tot lines`,
    SUM(A.tot_users) AS `tot users`
FROM
    (select 'ZA' as zones
      union all select 'ZA' ) A
JOIN `dotableusers` CA ON LEFT (A.Zones, 2) = LEFT (CA.Zones, 2)
GROUP BY
    `Area`;

您将在dotableusers中为所有行添加重复项,这些行可以与每个' ZA'行

答案 1 :(得分:0)

你可以做的是,分别获得金额,然后像

那样进行连接
SELECT xxx.* FROM (
SELECT
    LEFT (A.Zones, 2) AS `Area`,
    SUM(A.tot_lines) AS `tot lines`,
    SUM(A.tot_users) AS `tot users`
FROM
    `dotablezones` A
GROUP BY
    `Area` ) xxx JOIN `dotableusers` CA ON LEFT (xxx.Zones, 2) = LEFT (CA.Zones, 2)