2

MySQL #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

Given 1 table as following

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

Would like to select records and return the sum amount. Do not sum up the 2 highest prices' record.

SELECT SUM(Price) as total_amount
FROM `test`
WHERE Item NOT IN (
    SELECT Price 
    FROM `test`
    ORDER BY Price DESC
    LIMIT 2)

Expected Result:

total_amount
------------
   70.00

How to use JOIN or alternative LIMIT in Subquery in this query?

Thank you.

1
  • I think your subquery has a typo. Commented Aug 5, 2016 at 3:33

2 Answers 2

1

You need a temp table:

SELECT SUM(Price) FROM test WHERE Item NOT IN (
    SELECT * FROM (
        SELECT Item FROM test ORDER BY Price DESC LIMIT 2
    ) AS tmp
)
Sign up to request clarification or add additional context in comments.

Comments

1

Here's one option using a subquery with limit / offset:

select sum(price)
from (
  select *
  from test
  order by price desc
  limit 999999999
  offset 2
  ) t

Just make sure the limit value is greater than the number of potential rows (which evidently is 18446744073709551615)...

Or you could use user-defined variables:

select sum(price)
from (
  select *, @rn:=@rn + 1 rn
  from test cross join (select @rn:= 0) t
  ) t
where rn > 2

If you looking to exclude the 2 highest prices which could be more than 2 records, this will also work with 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

3 Comments

@sgeddes..when there are ties for the maximum value..this query would include the second max value in the sum.
@vkp -- good point, perhaps needs to be better defined by the OP.
@vkp -- edited with an alternative solution for both options using user-defined variables...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.