基本上,我有一个带有注释的MySQL表,其中提交了ID和日期,我希望用户能够编辑这些注释。编辑评论时,我想在表格中创建一个新条目,其ID与正在编辑的评论相同,但是新日期。
因此,当我选择我的评论列表时,我想使用SELECT MAX(DateSubmitted
)...分组ID
,但我也希望得到一个为每个ID分组的ID数量,因此我知道评论的编辑次数。
我认为它应该是这样的:
SELECT ID, COUNT(1) as "Number of edits"
FROM comments
GROUP BY ID;
合并:
SELECT ID, MAX(`DateSubmitted`), Comment
FROM comments
GROUP BY ID;
答案 0 :(得分:4)
如果您想获取最新的评论文本以及编辑的日期并计算:
SELECT a.ID, a. MaxDateSubmitted, a.NumComments, b.Comment
(SELECT ID,
MAX(`DateSubmitted`) as "MaxDateSubmitted",
COUNT('ID') as "NumComments"
FROM comments
GROUP BY ID) a
INNER JOIN comments b ON a.ID = b.ID and b.DateSubmitted = a.MaxDateSubmitted;
注意:这假设没有两个编辑具有完全相同的日期和时间(低至时间部分的精度)。但在这种情况下,我认为这是一个有效的假设。
如果您只想要最新的编辑日期和计数:
SELECT ID,
MAX(`DateSubmitted`) as "MaxDateSubmitted",
COUNT('ID') as "NumComments"
FROM comments
GROUP BY ID
答案 1 :(得分:2)
SELECT ID, COUNT(ID) as "Number of edits", MAX(`DateSubmitted`)
FROM comments
GROUP BY ID;