MySQL GROUP BY 字段不匹配
MySQL GROUP BY fields mismatch
有没有办法不用两个子查询就可以完成这个简单的事情?
这是我的基本数据:
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
我想要 select 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
这是我使用两个子查询的解决方案。
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
但我认为应该有更自然的方式来做到这一点
尝试以下;)
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
有没有办法不用两个子查询就可以完成这个简单的事情?
这是我的基本数据:
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
我想要 select 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
这是我使用两个子查询的解决方案。
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
但我认为应该有更自然的方式来做到这一点
尝试以下;)
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