一道SQL题目,效率提高一个数量级
有一张表order(orderid,userid,amount),写一条查询语句,取出所有消费总额超过100的用户的所有订单号orderid。
#本人开始是这样想的
SELECT aa.userid,aa.orderid,aa.amount FROM `order` aa LEFT JOIN
(
SELECT SUM(amount) AS amount,userid FROM `order` GROUP BY `userid`
) tt ON tt.userid = aa.userid AND tt.amount > 100
#看了高人的写法,效率提高一个数量级,表只需要遍历一次
SELECT userid ,GROUP_CONCAT(`orderid`)AS order_id,SUM(amount) AS amount
FROM order
WHERE amount > 100
GROUP BY userid
转载保留链接