MySQL Select Distinct Question
I want to return all columns from a table, but only for the 'unique' or 'distinct' users.
I want to grab all the distinct users from a table, but return all columns.
I will be sorting the table by a timestamp, so as to grab the 'first' entry of each distinct user开发者_StackOverflow社区.
Any Ideas?
You should post the table definition but more or less it should be possible using a GROUP BY
.
SELECT col1, col2, col3, MIN(timestamp)
FROM users
GROUP BY
col1, col2, col3
If any of your other columns also contains variable data (as they actually should in a normalized table), you have to make a choice on what aggregrate function you wish to use on them.
SELECT col1, col2, col3, MAX(var1), AVG(var2), ..., MIN(timestamp)
FROM users
GROUP BY
col1, col2, col3
select * from table group by userid order by time;
Don't forget to rename userid and time to match your column names
Have you tried using GROUP BY, i.e.
SELECT * FROM users GROUP BY id ORDER BY ...
Generally it should work, but you haven't mentioned any structure..
You don't really need to group. What you want is select every record in your table that doesn't have another record for the same user with a lesser (or greater) timestamp
select * from my_table t1
where not exists (select 1 from my_table t2
where t1.user = t2.user
and t1.time < t2.time)
Be sure to have indexes on user
and time
columns
select *
from table a,
(select min(timestampfield) as ts, userid as userid
from table
group by userid) b
where a.userid = b.userid and a.ts = b.ts
精彩评论