[英]Select All Fields From Only Latest Created Record of dataset in MySQL?
I am doing a comments table, and I can't quite figure out this query. 我正在做一个注释表,但我不太清楚这个查询。 These comments will be under a particular data record in this application, which is what comment_number refers to.
这些注释将在此应用程序中的特定数据记录下,即comment_number所指。 When a comment is created, it is assigned that records 'comment number'.. The comment number + date_added identify each particular comment.
创建评论时,将分配记录“评论号”的评论。评论号+ date_add标识每个特定评论。 If a comment is updated/edited, instead of updating the record itself, it creates another entry in the table with the same comment_number and date_added, and creates a new date_modified.
如果更新/编辑了注释,则不更新记录本身,而是在表中创建具有相同comment_number和date_added的另一个条目,并创建一个新的date_modified。 This is due to compliance issues.
这是由于合规性问题。 I have to be able to go back in that particular comment's history.
我必须能够回顾该评论的历史。
Here is the table description: 这是表格说明:
+----------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------- +---------------+------+-----+---------+-------+
| comment_number | varchar(64) | YES | | NULL | |
| comment | varchar(2048) | YES | | NULL | |
| date_added | datetime | YES | | NULL | |
| date_modified | datetime | YES | | NULL | |
| is_deleted | tinyint(1) | YES | | NULL | |
| date_deleted | datetime | YES | | NULL | |
+--------------- +---------------+------+-----+---------+-------+
So different comments will have the same comment number, but will have different 'date_added' fields. 因此,不同的注释将具有相同的注释编号,但将具有不同的“ date_added”字段。 And a particular comment's different versions in history will have the same 'comment_number' and 'date_added' value, but different 'date_modified' fields.
并且特定注释在历史记录中的不同版本将具有相同的“ comment_number”和“ date_added”值,但具有不同的“ date_modified”字段。
So i need to pull all the fields of the latest modified versions of all comments. 因此,我需要提取所有注释的最新修改版本的所有字段。 I have been playing around with MAX() functions, as well as GROUP BYs, but i have not been able to get the correct results yet.
我一直在使用MAX()函数以及GROUP BY,但是我还无法获得正确的结果。
Any help would be greatly appreciated. 任何帮助将不胜感激。
您可以在查询中使用ORDER BY date_modified,然后将LIMIT设置为1。确定是否需要ASC(从低到高)或DESC(从高到低)来获取所需字段作为第一个结果。
To get the most recent date_modified for every comment, you need a query like this: 要获取每个评论的最新date_modified,您需要一个类似以下的查询:
SELECT
comment_number,
date_added,
MAX(date_edited) AS max_date_edited
FROM
tablename
GROUP BY
comment_number,
date_added
to get the latest version of the comment, you then need to join the result of this query back: 为了获得最新版本的评论,您需要将查询结果重新加入:
SELECT c.*
FROM
table_name c INNER JOIN (
SELECT
comment_number,
date_added,
MAX(date_edited) AS max_date_edited
FROM
tablename
GROUP BY
comment_number,
date_added
) m ON c.comment_number=m.comment_number
AND c.date_edited = m.max_date_edited
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.