从 SQL 中选择最上面的结果
我认为这是一个简单的问题,但我似乎无法解决它。
我想从一个表中选择最新的结果并将其与另一个表中的单个元素连接。
更好地说,这是一个简单的模式:
Table 1 - Person
personId -PK - INT - AUTO ID
name - VARCHAR
Table 2 - Event
eventId - PK - INT - AUTO ID
personId - FK
timestamp - DATETIME
event - ENUM ('Went Out', 'Came back')
我想做的是返回所有人的列表以及每个人执行的最新操作
示例结果:
姓名|人员 ID |时间戳|事件 ID |活动
鲍勃 | 1 | 2011-08-7 3 | “出去了”
我做了一个简单的查询,连接两个表,然后按 personId 进行分组并按时间戳排序,但返回的结果始终是该人的第一个操作,而不是他们的最新操作。
有什么想法吗?
This is i think a simple problem but i can't seem to solve it.
I want to select the newest result from a table and join it with a single element in another table.
To put it better, here's a simple schema:
Table 1 - Person
personId -PK - INT - AUTO ID
name - VARCHAR
Table 2 - Event
eventId - PK - INT - AUTO ID
personId - FK
timestamp - DATETIME
event - ENUM ('Went Out', 'Came back')
What I'd like to do is return a list of all people and the latest action each person performed
Example Result:
name| personId | timestamp | eventId | event
bob | 1 | 2011-08-7 3 | 'went out'
I did a simple query joining the two tables and then did a group by personId and order by timestamp but the result that was returned was always the first action for the person, not their latest.
Any Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
或
PS:抱歉,但现在无法测试这两个查询
OR
PS: sorry but can't test both queries right now
你想要做一个
(降序)来获得最高的时间戳值而不是最低的
you'd want to do an
(desc from descending) to get the highest timestamp value instead of the lowest
ANSI 标准方式是:
我有一段时间没有使用 MySQL,而且我没有方便的安装,但你可能会得到你想要的:
它是非标准的,因为按照标准,选择中的任何内容都必须是在 group-by 中或作为聚合,这里我们不想这样做。但我记得 MySQL 不需要这样做,所以我会尝试一下,看看会发生什么。
The ANSI standard way would be:
I haven't used MySQL in a while and I don't have an installation handy, but you might get what you want with:
It's non-standard because by the standard, anything in the select must be in the group-by or be an aggregate, and here we don't want to do either. But as I recall MySQL doesn't require that, so I'd give this a whirl and see what happens.
另一种解决方案是使用覆盖密钥,假设
order by Id
会产生与order by timestamp
相同的结果Order by timestamp
更自然,可能更安全,但速度更快。An alternative solution, making use of a covered key, assumes that
order by Id
would yield the same results asorder by timestamp
Order by timestamp
is more natural and probably safer, but this is quicker.