Search code examples
mysqlsqlsql-order-bysql-limit

MySQL select where not in another returned data from sql statement


I have this problem where I want to first select 8 elements from a mysql database ordering by id DESC. Then I want to select another group of results (8 items), this time order by date DESC but the results here I want to ensure that they are not already on the fisrt query the one for ordering by id. The data is in the same table just with different columns like id,name,date,.

So far I have tried writing different queries to get the data but the data contains some similar items of which that is what I don't want. Here are the queries I have written;

this returns 8 items sorted by id DESC

SELECT name FROM person order by id DESC LIMIT 8;

this returns 8 items also but sorted by date DESC

SELECT name FROM person order by date DESC LIMIT 8;

the returned data contain duplicate items!


Solution

  • You could use a nested query, first select the first 8 id's, then select the first 8 records ordered by date, excluding those id's:

    SELECT name FROM person 
    WHERE id NOT IN
      (SELECT id FROM person order by id DESC LIMIT 8) AS exc
    ORDER BY date DESC LIMIT 8