MySQL选择其列总和相等的行

时间:2015-07-27 09:06:41

标签: mysql join sum

我有以下表格:

A:

+----+-----------+-------+----------+
| ID | PaymentID | Price | Quantity |
+----+-----------+-------+----------+
|  1 |         1 |   128 |        1 |
|  2 |         2 |    10 |        2 |
|  3 |         2 |    11 |        1 |
|  4 |         3 |   100 |        2 |
+----+-----------+-------+----------+

B:

+-----------+------------+
| PaymentID | TotalPrice |
+-----------+------------+
|         1 |        128 |
|         2 |         31 |
|         3 |        201 |
+-----------+------------+

并查询:

SELECT a.ID
FROM a
LEFT JOIN b ON b.PaymentID = a.PaymentID
WHERE b.TotalPrice = (a.Price * a.Quantity)

当a.PaymentID是唯一的时,它工作正常,但表A中的某些事务被分开并支付(表B)。上面的查询返回a.ID = 1,但我需要返回a.ID = 1,2,3。

a.PaymentID(1): 128 * 1 = 128 MATCH
a.PaymentID(2): 10 * 2 + 11 * 1 = 31 MATCH
a.PaymentID(3): 100 * 2 = 200 NOT MATCH

SQL Fiddle

2 个答案:

答案 0 :(得分:3)

试试这句话:

SELECT a.ID, b.totalprice
FROM a
LEFT JOIN b ON b.PaymentID = a.PaymentID
group by b.paymentID
having TotalPrice = sum(a.Price * a.Quantity)

SQLFIDDLE

更新:澄清之后:

select a.id from a where paymentId in(
  select paymentID from(
SELECT a.paymentID as paymentID, b.totalprice
FROM a
LEFT JOIN b ON b.PaymentID = a.PaymentID
group by b.paymentID
having TotalPrice = sum(a.Price * a.Quantity)) as c )

答案 1 :(得分:3)

您正尝试将表a和表b中的价格和金额的总和连同PaymentId一起使用,并将其用于连接子句,该子句将基于聚合而不是基于聚合计算。 您可能需要首先找到聚合部分,然后加入某些内容

select
a.ID
from a 
left join (
  select sum(Price*Quantity) as tot,PaymentID 
  from a group by PaymentID
)x on x.PaymentID = a.PaymentID
join b on b.PaymentID = a.PaymentID and x.tot = b.TotalPrice

http://www.sqlfiddle.com/#!9/3b261/45