您的位置首页百科问答

mysql两表汇总后再得到两表的交集和差集,请问怎么实现?

mysql两表汇总后再得到两表的交集和差集,请问怎么实现?

CREATE TABLE A (

`C1` VARCHAR(10),

`C2` VARCHAR(10),

`C3` VARCHAR(10),

`C4` VARCHAR(10),

`C5` INT

);

INSERT INTO A

SELECT '华北', '辽宁', '沈阳', '20020202', 2 UNION ALL

SELECT '华东', '山东', '青岛', '18020133', 3 UNION ALL

SELECT '华北', '北京', '北京', '7193', 7 UNION ALL

SELECT '华北', '北京', '北京', '8358', 5 UNION ALL

SELECT '华北', '北京', '北京', '9773', 8 UNION ALL

SELECT '华东', '山东', '青岛', '18020133', 5 ;

CREATE TABLE B (

`C1` VARCHAR(10),

`C2` VARCHAR(10),

`C3` VARCHAR(10),

`C4` VARCHAR(10),

`C5` INT

);

INSERT INTO B

SELECT '华北', '辽宁', '沈阳', '20020202', 5 UNION ALL

SELECT '华东', '山东', '青岛', '18020133', 6 UNION ALL

SELECT '华北', '北京', '北京', '7193', 2 UNION ALL

SELECT '华东', '甘肃', '兰州', '7364', 3 UNION ALL

SELECT '华东', '湖北', '武汉', '7512', 7 UNION ALL

SELECT '华东', '湖北', '武汉', '7512', 2 UNION ALL

SELECT '华东', '江苏', '常州', '7582', 5 UNION ALL

SELECT '华东', '江苏', '淮安', '7670', 7;

SELECT

IFNULL(A.`C1`, B.`C1`) AS `区域`,

IFNULL(A.`C2`, B.`C2`) AS `省份`,

IFNULL(A.`C3`, B.`C3`) AS `城市`,

IFNULL(A.`C4`, B.`C4`) AS `编码`,

SUM(A.`C5`) AS `表A销量`,

SUM(B.`C5`) AS `表B销量`

FROM

A LEFT JOIN B

ON (

A.`C1` = B.`C1` AND

A.`C2` = B.`C2` AND

A.`C3` = B.`C3` AND

A.`C4` = B.`C4`

)

GROUP BY

IFNULL(A.`C1`, B.`C1`),

IFNULL(A.`C2`, B.`C2`),

IFNULL(A.`C3`, B.`C3`),

IFNULL(A.`C4`, B.`C4`)

UNION

SELECT

IFNULL(A.`C1`, B.`C1`) AS `区域`,

IFNULL(A.`C2`, B.`C2`) AS `省份`,

IFNULL(A.`C3`, B.`C3`) AS `城市`,

IFNULL(A.`C4`, B.`C4`) AS `编码`,

SUM(A.`C5`) AS `表A销量`,

SUM(B.`C5`) AS `表B销量`

FROM

A RIGHT JOIN B

ON (

A.`C1` = B.`C1` AND

A.`C2` = B.`C2` AND

A.`C3` = B.`C3` AND

A.`C4` = B.`C4`

)

GROUP BY

IFNULL(A.`C1`, B.`C1`),

IFNULL(A.`C2`, B.`C2`),

IFNULL(A.`C3`, B.`C3`),

IFNULL(A.`C4`, B.`C4`);

+------+------+------+----------+---------+---------+

| 区域 | 省份 | 城市 | 编码 | 表A销量 | 表B销量 |

+------+------+------+----------+---------+---------+

| 华北 | 辽宁 | 沈阳 | 20020202 | 2 | 5 |

| 华北 | 北京 | 北京 | 7193 | 7 | 2 |

| 华北 | 北京 | 北京 | 8358 | 5 | NULL |

| 华北 | 北京 | 北京 | 9773 | 8 | NULL |

| 华东 | 山东 | 青岛 | 18020133 | 8 | 12 |

| 华东 | 甘肃 | 兰州 | 7364 | NULL | 3 |

| 华东 | 湖北 | 武汉 | 7512 | NULL | 9 |

| 华东 | 江苏 | 常州 | 7582 | NULL | 5 |

| 华东 | 江苏 | 淮安 | 7670 | NULL | 7 |

+------+------+------+----------+---------+---------+

9 rows in set (0.00 sec)

你是要查前十个查询结果中相同的那些记录,而不求前十个相同记录吧,因为这是有差别的,按照你的语句,应该是求前者,即先求出A的前十条数据,B的前十条数据,再求它们的交集。

既然是求交集,那么这两个表的关系模式应该是相同的了,

select a.* from

(select * from table order by table.a desc limit 10) as a, (select * from table order by table.b desc limit 10) as b

where a.primary_key = b.primary_key --先将两个结果作为两张临时表,然后通过主键 primary_key来获取交集(交集肯定就是主键相等的了,因为关系模式相同)