MySQL#1235 - 这个版本的MySQL还没有支持' LIMIT& IN / ALL / ANY / SOME子查询'
给出1个表格如下
Item | Name | Price
----- ------------ --------
1 | Adidas | 310.00
2 | Nike Run | 30.00
3 | Puma | 150.00
4 | Nike Women | 20.00
5 | NB | 20.00
想要选择记录并返回金额。不要总结2个最高价格'记录。
SELECT SUM(Price) as total_amount
FROM `test`
WHERE Item NOT IN (
SELECT Price
FROM `test`
ORDER BY Price DESC
LIMIT 2)
预期结果:
total_amount
------------
70.00
如何在此查询中使用子查询中的JOIN或替代LIMIT?
谢谢。
答案 0 :(得分:1)
这是使用带有limit / offset
的子查询的一个选项:
select sum(price)
from (
select *
from test
order by price desc
limit 999999999
offset 2
) t
确保限制值大于潜在行数(显然是18446744073709551615)......
或者您可以使用user-defined variables
:
select sum(price)
from (
select *, @rn:=@rn + 1 rn
from test cross join (select @rn:= 0) t
) t
where rn > 2
如果您要排除可能超过2条记录的2个最高价格,这也适用于user defined variables
:
select sum(price)
from (
select *, @rn:=if(@prevPrice=price, @rn,
if(@prevPrice:=price, @rn + 1, @rn + 1)) rn
from test cross join (select @rn:= 0, @prevPrice:= null) t
) t
where rn > 2
答案 1 :(得分:1)
你需要一个临时表:
SELECT SUM(Price) FROM test WHERE Item NOT IN (
SELECT * FROM (
SELECT Item FROM test ORDER BY Price DESC LIMIT 2
) AS tmp
)