Jump to content


Photo

Need help combining these two queries


  • Please log in to reply
3 replies to this topic

#1 darthjones

darthjones
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 19 March 2006 - 06:44 PM

I have a table called names with the following fields - id, last_name, first_name. I want to get the last 10 entries based on id and then arrange the results based on last_name. I can do both separately but I can't figure out how to do them at the same time. Can both be done in one query?

Basically, I want to combine the following -

select id from names order by id desc limit 10;
select last_name, first_name from names order by last_name;


#2 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 19 March 2006 - 08:04 PM

Assuming that you have MySQL 4.1+, you can do this easily in a subquery:

SELECT last_name, first_name FROM names WHERE id IN ( select id from names order by id desc limit 10 )

Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.

#3 wickning1

wickning1
  • Members
  • PipPipPip
  • Advanced Member
  • 405 posts

Posted 20 March 2006 - 06:08 AM

SELECT last_name, first_name FROM names WHERE id IN ( select id from names order by id desc limit 10 ) ORDER BY last_name


#4 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 20 March 2006 - 09:43 PM

Oops... I forgot to add back the ORDER BY clause, which would be the whole point! My bad.
Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users