从1:n表中检索单个查询中的最新备注(按时间戳记) [英] Retrieving the latest note (by timestamp) in a single query from a 1:n table

查看:114
本文介绍了从1:n表中检索单个查询中的最新备注(按时间戳记)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个表,用户和注释。假设模式如下所示:

  users 
id,name,field2,field3

notes
id,user_id,subject,heading,body,timestamp

要做的是选择每个用户,以及每个用户根据时间戳发布的LATEST(只有1个)注释,以显示在概览报告中。



这样做?请注意,数据库是MySQL。



谢谢!

解决方案

$ p> select users.name,notes.subject,notes.heading,notes.body
from users,notes
其中users.id = notes.user_id
notes.timestamp =(从user_id = users.id的笔记中选择max(timestamp))


Let's say I have two tables, users and notes. Let's say the schemas look like this:

users
id, name, field2, field3

notes
id, user_id, subject, heading, body, timestamp

What I want to do is select every user, and the LATEST (just 1) note posted by each user based on the timestamp to show in an overview report.

How would I go about doing this? Please note that the DB is MySQL.

Thanks!

解决方案

 select users.name, notes.subject, notes.heading, notes.body
 from users, notes
 where users.id = notes.user_id
 and notes.timestamp = (select max(timestamp) from notes where user_id = users.id)

这篇关于从1:n表中检索单个查询中的最新备注(按时间戳记)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆