0

How can I select the row with the highest id from all rows where the query conditions match?

for example this query:

SELECT * FROM tbl_pictures WHERE user='1' AND type='profilepic'

So if user1 already uploaded a few profile pictures, there will be couple rows which match the query. Since my tbl_pictures has an auto increment id i always want to get only the row which matches the query and has the highest index compared to the other matches.

How do I have to write that query?

maxischl
  • 579
  • 1
  • 11
  • 29

1 Answers1

1
SELECT * FROM tbl_pictures WHERE user='1' AND type='profilepic' ORDER BY `id` DESC LIMIT 1

Edit:

Explaining for Hallur:

ORDER BY is used to (guess what) - order the results of the query by the following column. After the column you can optionally specify ASC or DESC to order in ascending or descending order. You can optionally add more sorting condition, separating them with comma like: ORDER BY field1 ASC, field2 DESC, field3.

The LIMIT clause is used to limit the results of the query. You can use LIMIT number to return up to number results, or you can use LIMIT offset, number to indicate from which record to start (or how many records to skip) and from then on - how many to return.

Hope it's more clear :)

vuryss
  • 1,270
  • 8
  • 16