Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a workaround for using LIMIT in a subquery in MySQL?

Here is my original query...

SELECT `id`
  FROM `properties`
 LIMIT 10, 20

The LIMIT condition is for pagination.

Now, I have to get all like before, but I need to get only a third of rows where a condition is present.

I came up with this, just throwing LIMIT 30 in before I figured out how to do (total rows matched / 3) * 2.

SELECT `id`
  FROM `properties`
 WHERE `id` NOT IN (SELECT `id` 
                      FROM `properties` 
                     WHERE `vendor` = "abc" 
                  ORDER BY RAND() 
                     LIMIT 30)
LIMIT 10, 20    

MySQL said...

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

I guess I can't use LIMIT in a subquery.

So this is a multi question but all related...

  • Is there a workaround for LIMIT in subquery?
  • Can I select a 1/3 of matched rows with MySQL?
  • Do I need to turn this into 2 queries, or just select all and unset the rows not required in PHP?
like image 861
alex Avatar asked Oct 21 '10 03:10

alex


1 Answers

Sorry I'm late, this worked for me:

   SELECT p.id 
     FROM properties p
LEFT JOIN (SELECT t.id
             FROM PROPERTIES t
            WHERE t.vendor = 'abc'
         ORDER BY RAND()
            LIMIT 30) x ON x.id = p.id
    WHERE x.id IS NULL
    LIMIT 10, 20
like image 98
OMG Ponies Avatar answered Nov 13 '22 06:11

OMG Ponies