views:

113

answers:

4

I need to get the last inserted product by a user. This is what I've came up with

   $query = 'SELECT id
                 FROM products
                 WHERE user_id = ?
                ORDER BY id DESC
                       LIMIT 1';

It should work because the id is auto increment. To me though, it feels hacky. Is there a better way to do this?

I can't use mysql_last_insert_id() or anything like that because I need the last product by a specific user.

+1  A: 

you could use

SELECT MAX(id) FROM ...

Not sure how much better that would be, tho :)

Carlos Lima
+4  A: 

Use:

  SELECT MAX(t.id) AS id
    FROM PRODUCTS t
   WHERE t.user_id = ?

MAX is an aggregate function, returning the maximum value of the column specified. Because the query is only returning one column - the one the aggregate function is being used on - the GROUP BY clause doesn't need to be specified. But there's no harm in using:

  SELECT MAX(t.id) AS id
    FROM PRODUCTS t
   WHERE t.user_id = ?
GROUP BY t.user_id
OMG Ponies
That *is* a bit better... I feel foolish for forgetting about these things in MySQL. Thanks!
alex
This is a great solution, but you (alex) should really consider adding a 'created' field to your schema. It's a really valuable column to have if you make sure your models are filling it in properly. MySQL can do a lot of date comparison selection for you and it's a lot more surefire than the greatest record ID for something like this.
coreyward
OMG Ponies
+5  A: 

I would add a DATETIME column to your table for this purpose. I personally don't feel comfortable relying on the behavior of AUTO_INCREMENT from the standpoint of ordering. Besides, its purpose is to "generate a unique identity for new rows." Aside from that, you shouldn't really care about the value.

Andy West
That's a good idea... how would you write your query then to get the newest product?
alex
Assuming your DATETIME column stored the time the product was added (using NOW(), for example), you could just replace the id in OMG Ponies' example with the date.
Andy West
alex: just like your original but with ORDER BY datetime_column_name DESC, id DESC;
ysth
@ysth: I would say using an aggregate is normally preferred over selecting a larger set and using the LIMIT clause.
Andy West
A: 

I Agree with Datetime Column option. for e.g. you have column named LastAddedDate Datetime then you can make query like

Select top(1) Products.Id from Products where User_Id=@UserId order by LastAddedDate,Id Desc

or else in case of id also you can write query

Select top(1) Products.Id from Products where User_Id=@UserId order by Id Desc

Radhi
The question specifies MySQL, where there is no SELECT TOP(). The alternative is LIMIT, which has already been discussed.
Andy West