Reputation: 2113
I have a customers
table with its field such as userId, customerId and created.
This is the data in customers
table
userId customerId created
user_1 customer_1 2016-03-04 00:00:00
user_1 customer_2 2016-10-04 00:00:00
user_1 customer_3 2016-07-04 00:00:00
user_1 customer_4 2016-09-04 00:00:00
user_2 customer_5 2016-06-04 00:00:00
user_2 customer_6 2016-03-04 00:00:00
I used some following queries to get latest created of each user. And this is one of queries I tried
select *
from customers
order by created desc
group by userId
The above query didn't work properly. My desired result is:
user_1 customer_2 2016-10-04 00:00:00
user_2 customer_5 2016-06-04 00:00:00
Maybe I don't understand clearly about how order by
and group by
commands work. Could you give me some solutions?
Upvotes: 0
Views: 2040
Reputation: 73
If you try do in this way, you'll get the result you want:
SELECT * FROM customers
WHERE created = (select max(created) from customers a where a.userId = customers.userId )
group by clause allows you get maximum value:
select userId,max(created)
from customers
group by userId
so that you get max date for each userId and after putting it into some values you can use in the another query.
Something like that gives you only one row with maximum date:
select userId,customerId,max(created)
from customers
order by created desc
Upvotes: 0
Reputation: 6065
Try this:
SELECT
*
FROM
customers c1
WHERE
(userId, created) IN
(
SELECT userId, MAX(created)
FROM customers c2
WHERE c1.userId = c2.userId
);
Upvotes: 1
Reputation: 521073
SELECT c1.userId, c1.customerId, c1.created
FROM customers c1
INNER JOIN
(
SELECT userId, MAX(created) AS maxCreated
FROM customers
GROUP BY userId
) c2
ON c1.userId = c2.userId AND c1.created = c2.maxCreated
ORDER BY c1.created
Note that you don't need to explicitly use DESC
with the ORDER BY
clause, because MySQL sorts in descending order by default.
Upvotes: 1