MySql 中的复杂一对多查询
我已经搜索过,但无法将问题浓缩到足以找到相关答案。我的经验告诉我这可能是一个设计问题...
current_status
id
user_id
status_id
created
users
user_id
other...
current_status 主要用于审计目的。每次用户状态发生变化时,都会在 current_status 中插入一条新记录。一些状态示例包括“工作”、“解雇”、“已申请”、“裁员”等。
查询 - 我想返回每个用户的最新状态以及用户详细信息...
SELECT users.*, current_status.status_id AS status
FROM users
JOIN current_status ON users.user_id = current_status.user_id
WHERE users.user_id = '1'
我如何告诉查询返回用户最新的status_id?
ORDER BY current_status.created DESC LIMIT 0,1
然而,这真的是准确的方法吗?因为如果我想返回多个用户怎么办?
任何帮助将不胜感激。
I have searched but can't condense the question enough to find a relevant answer. My experience tells me this may be a design issue...
current_status
id
user_id
status_id
created
users
user_id
other...
current_status is used mostly for auditing purposes. Every time a user status changes, a new record is inserted in current_status. Some status examples are 'working', 'fired', 'applied', 'on layoff', etc.
The query - I want to return just the most recent status of each user plus the user details...
SELECT users.*, current_status.status_id AS status
FROM users
JOIN current_status ON users.user_id = current_status.user_id
WHERE users.user_id = '1'
How do I tell the query to return the most recent status_id for the user?
ORDER BY current_status.created DESC LIMIT 0,1
However, is that truly the accurate way to do it because what if I want to return multiple users?
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑 我想我现在已经掌握了您的表/列...
EDITv2 此外,如果您想加入该表以节省以后的查询,你可以使用:
EDIT Think I have the hang of your tables/columns now...
EDITv2 Also, if you want to join the table to save yourself a query later on, you can use:
也许是这样的?
Perhaps something like this?
遗憾的是 MySQL 不支持 over(order by ...) 功能。这将需要一个子查询来选择所有最后的状态:
Sadly MySQL doesn;t support
over(order by ...)
feature. That's going to take a subquery to select all last statuses: