MySQL根据DISTINCT值分组多行

时间:2016-07-14 14:58:42

标签: mysql sql

我需要显示表中的最后2个结果(结果),结果由几行匹配的submissionId组成,每次提交的行数未知,当然我更喜欢单个查询。

这是数据库表结构

submissionId     input       value

     1           name         jay
     1           phone        123-4567
     1           email        test@gmail.com 
     2           name         mo
     2           age          32
     3           name         abe
     3           email        abe@gmail.com
     4           name         jack
     4           phone        123-4567
     4           email        jack@gmail.com 

Desierd结果:

submissionId     input       value

     3           name         abe
     3           email        abe@gmail.com
     4           name         jack
     4           phone        123-4567
     4           email        jack@gmail.com  

或者甚至更好,如果我可以像这样组合行:

3           name         abe    3       email        abe@gmail.com
4           name         jack   4       phone        123-4567         4           email        jack@gmail.com 

3 个答案:

答案 0 :(得分:2)

此处的一个选项是使用子查询来识别最新的submissionId的最近和次近的

SELECT submissionId, input, value
FROM yourTable
WHERE submissionId >= (SELECT MAX(submissionId) FROM yourTable) - 1
ORDER BY submissionId

在这里演示:

SQLFiddle

<强>更新

如果您的submissionId列确实是日期类型,并且您希望结果集中包含最新的两个日期,则以下查询将实现此目的。请注意,WHERE子句中的子查询虽然很丑,但与外部查询无关。这意味着MySQL优化器应该能够确定它只需要运行一次。

SELECT submissionDate, input, value
FROM yourTable
WHERE submissionDate >=
    (SELECT MAX(CASE WHEN submissionDate = (SELECT MAX(submissionDate) FROM yourTable)
                    THEN '1000-01-01'
                    ELSE submissionDate
               END) FROM yourTable)
ORDER BY submissionDate

SQLFiddle

答案 1 :(得分:2)

您可以在limit子句的子查询中使用from,因此编写此代码的典型方法是:

SELECT submissionDate, input, value
FROM t join
     (select distinct submissionDate
      from t
      order by submissionDate desc
      limit 2
     ) sd
     on t.submissionDate = sd.submissionDate;

答案 2 :(得分:0)

这就是查询现在的样子,所以我可以得到LIMIT,RANGE和id / timestamp的结果(在Tim和Gordon的帮助下):

 SELECT *
 FROM rmyTable t
 JOIN
 (SELECT DISTINCT sd.submissionId
 FROM myTable sd
 WHERE sd.questionId = yourId
 ORDER BY sd.submissionId 
 LIMIT 2
 ) t2 
 ON t.submissionId = t2.submissionId 
 WHERE t.formId = yourId
 AND dateTime BETWEEN 0000 AND 1111