MySQL选择不等于子查询中的限制
MySQL#1235-此版本的MySQL还不支持“LIMIT&IN/ALL/ANY/SOME子查询” 给出如下表1MySQL选择不等于子查询中的限制,mysql,sql,subquery,limit,Mysql,Sql,Subquery,Limit,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 要选
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
如何在此查询中在子查询中使用联接或替代限制
谢谢。这里有一个选项,使用带有
限制/偏移量的子查询:
select sum(price)
from (
select *
from test
order by price desc
limit 999999999
offset 2
) t
只需确保限制值大于潜在行数(显然是18446744073709551615)
或者您可以使用用户定义变量
:
select sum(price)
from (
select *, @rn:=@rn + 1 rn
from test cross join (select @rn:= 0) t
) t
where rn > 2
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
如果您希望排除可能超过2条记录的2个最高价格,这也将适用于用户定义变量
:
select sum(price)
from (
select *, @rn:=@rn + 1 rn
from test cross join (select @rn:= 0) t
) t
where rn > 2
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
您需要一个临时表:
SELECT SUM(Price) FROM test WHERE Item NOT IN (
SELECT * FROM (
SELECT Item FROM test ORDER BY Price DESC LIMIT 2
) AS tmp
)
我认为您的子查询有一个输入错误。@sgedes..当最大值有联系时..此查询将在总和中包含第二个最大值。@vkp--这一点很好,可能需要由OP更好地定义。@vkp--使用用户定义变量
为这两个选项使用另一种解决方案进行编辑。。。