MySQL 选择不同的问题

发布于 2024-11-14 14:44:44 字数 122 浏览 3 评论 0原文

我想返回表中的所有列,但仅限于“唯一”或“不同”用户。

我想从表中获取所有不同的用户,但返回所有列。

我将按时间戳对表进行排序,以便获取每个不同用户的“第一个”条目。

有什么想法吗?

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.

Any Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

稚气少女 2024-11-21 14:44:44

您应该发布表定义,但或多或​​少应该可以使用GROUP BY

SELECT col1, col2, col3, MIN(timestamp)
FROM   users
GROUP BY
       col1, col2, col3

如果任何其他列也包含变量数据(它们实际上应该在标准化表中),则必须选择要对它们使用的聚合函数。

SELECT col1, col2, col3, MAX(var1), AVG(var2), ..., MIN(timestamp)
FROM   users
GROUP BY
       col1, col2, col3

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
回忆躺在深渊里 2024-11-21 14:44:44
select * from table group by userid order by time;

不要忘记重命名用户 ID 和时间以匹配您的列名称

select * from table group by userid order by time;

Don't forget to rename userid and time to match your column names

友欢 2024-11-21 14:44:44

您是否尝试过使用 GROUP BY,即

SELECT * FROM users GROUP BY id ORDER BY ...

通常它应该可以工作,但您没有提到任何结构..

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

我的鱼塘能养鲲 2024-11-21 14:44:44

其实没必要组团。您想要的是选择表中没有具有较小(或较大)时间戳的同一用户的其他记录的每条记录,

select * from my_table t1
where not exists (select 1 from my_table t2
                   where t1.user = t2.user
                     and t1.time < t2.time)

请确保在 usertime列

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

辞取 2024-11-21 14:44:44
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文