tags:

views:

61

answers:

5

Hello.. Is it possible to execute a select query where the id column is within the last 50 rows? So like WHERE id > total id - 50.

Something like that? Not sure of the syntax! Cheers

+9  A: 

This?

SELECT *
FROM `table`
ORDER BY `id` DESC
LIMIT 50
R. Hill
A: 

You can just combine ORDER BY with LIMIT to achieve this. You can read about them in the docs on SELECT.

grossvogel
A: 

Something like:

SELECT * FROM table ORDER BY ID DESC LIMIT 50
ChrisOPeterson
A: 

Did you mean just select the last 50 rows, or select something in the last 50 rows? This is how you would select from the last 50:

SELECT *
  FROM table
 WHERE id IN ( SELECT id FROM table ORDER BY id DESC LIMIT 50 )
   AND whatImLookingFor = 'Something'

EDIT: Or in databases that use the other syntax:

SELECT *
  FROM table
 WHERE id IN ( SELECT TOP 50 id FROM table ORDER BY id DESC )
   AND whatImLookingFor = 'Something'
Brendan Long
$q = "SELECT id FROM ".TBL_CONF_RESULTS." WHERE (home_user = '$u' OR away_user = '$u') IN (SELECT id FROM ".TBL_CONF_RESULTS." ORDER BY id DESC LIMIT 100)";
Luke
This is what I have but it doesnt like it.I want to select the last 100 rows of the table and then check if home user or away user is in there!
Luke
+1  A: 

You can use the above if you just want the last 50 items, and it's probably the cleanest and best way. But if you really care about the ID for some reason, you can use the MAX function:

SELECT * 
    FROM table 
    WHERE id > (SELECT MAX( id ) FROM table) - 50 
          AND whatImLookingFor = 'Somesuch'

This of course isn't terribly efficient and is somewhat unweidly, but will do exactly what you were asking about.

cincodenada
Judging by your above comment, you should be able to add "AND (home_user = '$u' OR away_user = '$u')" to the end of my statement above and go. There also may be a more efficient way to do that, but that's the best I know.
cincodenada
I tested what I mentioned above and it worked fine, and have updated the statement above to reflect that. MySQL 5.1 at least doesn't support LIMIT in subqueries, so Brendan's solution wouldn't work for me. The above ended up being pretty snappy too, since id is indexed and all.
cincodenada
This is it mate, spot on!! That limit in subquery wasnt working no!
Luke
@cinocodenada: On MySQL, I believe the query is in the form `SELECT TOP 50 ...` rather than `SELECT ... LIMIT 50`
Brendan Long
@Brendan No, TOP is from MS SQL, MySQL uses the LIMIT syntax. It's just not supported inside the subquery in MySQL 5.1. See Wikipedia's summary of the different standards:http://en.wikipedia.org/wiki/Select_(SQL)#Result_limits
cincodenada
Oh I see. I always gets confused about the different SQL's.
Brendan Long