假设我有两个结构相同的表,称它们为A&B。这个问题唯一关心的列是产品类型、价格和数量。
每种产品类型和价格的组合可以在每个表格中以不同的数量重复多次。我试图找到一个组合在一个表中的总容量不同于另一个表的实例。
这将包括表a中的组合未在表B中表示,或反之亦然。
===================
例子:
表A:
ID Product_type Price Volume
--- ------------ ----- ------
1 X $1 10
2 X $1 11
3 Z $2 10
表B:
ID Product_type Price Volume
-- ------------- ----- -------
1 X $1 21
2 Y $1 5
3 Z $2 7
4 Z $2 4
请注意,表A中X@$1的卷之和是21,这与表B相匹配。
表B中有Y@$1,但A中没有。
两个表中都有Z@$2,但它们的体积之和不同。我希望查询返回每个违反规则的产品类型和价格组合(即Y@$1和Z@$2)。
我试过使用GROUP、UNION、DISTINCT、sub查询和上面的各种组合,但似乎无法理解。
最佳答案
create table a (ID integer, Product_type char(1), Price float, Volume integer);
create table b (ID integer, Product_type char(1), Price float, Volume integer);
insert into a (ID, Product_type, Price, Volume) values
(1, 'X', 1, 10),
(2, 'X', 1, 11),
(3, 'Z', 2, 10)
;
insert into b (ID, Product_type, Price, Volume) values
(1, 'X', 1, 21),
(2, 'Y', 1, 5),
(3, 'Z', 2, 7),
(4, 'Z', 2, 4)
;
select
a.Product_type as Product_type_a,
a.Price as Price_a,
a.Volume as Volume_a,
b.Product_type as Product_type_b,
b.Price as Price_b,
b.Volume as Volume_b
from (
select Product_type, Price, sum(Volume) as Volume
from a
group by Product_type, Price
) a
full outer join (
select Product_type, Price, sum(Volume) as Volume
from b
group by Product_type, Price
) b on a.Product_type = b.Product_type and a.Price = b.Price
where
a.Volume != b.Volume
or a.Volume is null or b.Volume is null
;
product_type_a | price_a | volume_a | product_type_b | price_b | volume_b
----------------+---------+----------+----------------+---------+----------
Z | 2 | 10 | Z | 2 | 11
| | | Y | 1 | 5
关于mysql - 识别2个表中的不同行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12483582/