MySQL GROUP BY字段不匹配

时间:2016-06-14 05:24:33

标签: mysql group-by subquery

如果没有两个子查询,有没有办法做这个简单的事情?

这是我的基本数据:

SELECT order_detail_id, product_id, MAX(paid_price) AS max_price, order_id
FROM t_order_details
WHERE order_id = 7 OR order_id = 8
GROUP BY order_id

simple select result

我希望选择order_detail_id和product_id以最高价格,按顺序7和8顺序相同。似乎数据不符合行

SELECT order_detail_id, product_id, MAX(paid_price) AS max_price, order_id
FROM t_order_details
WHERE order_id = 7 OR order_id = 8
GROUP BY order_id

wrong result

这是我的解决方案,包含两个子查询。

SELECT order_detail_id, product_id, paid_price, order_id
FROM t_order_details
WHERE paid_price IN (
    SELECT MAX(paid_price) AS max_price
    FROM t_order_details
    WHERE order_id = 7 OR order_id = 8
    GROUP BY order_id)
AND order_id IN (
    SELECT order_id
    FROM t_order_details
    WHERE order_id = 7 OR order_id = 8
    GROUP BY order_id)
GROUP BY order_id

但我认为应该有更自然的方法来做到这一点

1 个答案:

答案 0 :(得分:0)

尝试以下内容;)

SELECT T1.order_detail_id, T1.product_id, T1.paid_price, T1.order_id
FROM t_order_details T1
INNER JOIN (
    SELECT MAX(paid_price) AS paid_price, order_id
    FROM t_order_details
    WHERE order_id IN (7, 8)
    GROUP BY order_id
) T2 ON T1.order_id = T2.order_id AND T1.paid_price = T2.paid_price
WHERE T1.order_id IN (7, 8)

已编辑(没有子查询):

SELECT T1.order_detail_id, T1.product_id, T1.paid_price, T1.order_id
FROM t_order_details T1
INNER JOIN t_order_details T2
ON T1.order_id = T2.order_id AND T1.paid_price <= T2.paid_price
WHERE T1.order_id IN (7, 8)
GROUP BY T1.order_id, T1.order_detail_id, T1.product_id
HAVING COUNT(*) <= 1