GROUP BY在sql中有having子句和min函数

时间:2015-02-02 12:33:47

标签: php mysql

sharedid   property  shareduser  shareddatetime 
111        32        129         2015-02-02 13:30:44
117        33        129         2015-02-02 13:41:21
119        33        129         2015-02-02 13:40:44

在上表中我展示了我得到的结果。现在我想要我的结果,比如shareduser应该是129,而shareddatetime最小的是group by属性列。 我运行了以下查询

SELECT * FROM sharing WHERE `shareduser` = 129 GROUP BY property HAVING min(shareddatetime)

结果:

sharedid   property  shareduser  shareddatetime 
111        32        129         2015-02-02 13:30:44
117        33        129         2015-02-02 13:41:21

但预期的输出不是min()。 我想要像

这样的结果
sharedid   property  shareduser  shareddatetime 
111        32        129         2015-02-02 13:30:44
119        33        129         2015-02-02 13:40:44

4 个答案:

答案 0 :(得分:1)

您的having子句不正确,请检查标准SQL语法。 您可以使用子查询来获取具有最小值的属性。

  SELECT * FROM sharing WHERE `shareduser` = 129
  and   `shareddatetime` = ( select min( `shareddatetime` )
    from  sharing  s2
    where  s2.`shareduser` = sharing.`shareduser`
    and    s2.`property`   = sharing.`property` )

http://www.sqlfiddle.com/#!2/22ee4a/3(使用Kalid架构)

答案 1 :(得分:1)

您可以使用自我联接来获得所需的结果

select s.* 
from sharing s
join( select `property`, `shareduser`,min(shareddatetime) shareddatetime
     from sharing
     where `shareduser` = 129 
     group by `property`, `shareduser`
) s1
using(`property`, `shareduser`,shareddatetime)

DEMO

答案 2 :(得分:1)

SELECT s1.* FROM sharing s1 inner join
(select min(shareddatetime) minshareddatetime FROM sharing group by property) tmp
on s1.shareddatetime = tmp.minshareddatetime
where s1.shareduser = 129;

答案 3 :(得分:0)

SELECT * FROM sharing WHERE shareduser = 129 ORDER BY shareddatatime asc 这应该这样做

对于我实际忘记你可以使用的小组:

ORDER BY property asc, shareddatatime asc