Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.