Jump to content

Please help with a SELECT statement


accent

Recommended Posts

I have a users table and a orders table.  I need to display the all the users on the page with the latest order for each user.

Can I do that in one Select statement?

 

I tried the following but it will return all the orders. I only need one order for one user.

SELECT orders.orderid, users.username FROM orders, users WHERE orders.userid=users.id ORDER BY orders.datetime DESC;

 

Any ideas?

 

Thanks a lot!

 

Link to comment
https://forums.phpfreaks.com/topic/169294-please-help-with-a-select-statement/
Share on other sites

Hi

 

Assuming that the orderid is always ascending (so the later the order the higher the order id):-

 

SELECT *
FROM (SELECT a.userid, MAX(a.orderid) FROM orders a GROUP BY a.userid) LatestOrders
INNER JOIN Orders b ON LatestOrders.orderid = b.orderid
INNER JOIN Users c ON LatestOrders.userid = c.id

 

Narrow the SELECT * down to the particular fields you are interested in.

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.