0

我使用 mysql 5.1。

这是我的数据库架构:

id     user_id     type     created_at
1       32          X       2012-11-19
2       32          Y       2012-11-18
3       30          X       2012-11-16
4       32          Z       2012-11-17
5       31          Y       2012-11-13
6       32          Z       2012-11-9

我希望我的 SQL 查询返回每种类型的user_idtype和最新 的。created_at我试图提出这个请求: SELECT max(type) FROM notification WHERE user_id=34 ORDER BY type但它只返回最新的created_at.

4

5 回答 5

1
select n.id, n.user_id, n.type, m.max_created_at
from notification n
     inner join
     (
         select   type, max(created_at) as max_created_at
         from     notification
         group by type
     ) m  on n.type = m.type and 
             m.max_created_at = n.created_at

请注意,这确实假设没有两条具有相同类型和 created_at 日期的记录。

于 2012-11-20T09:26:02.920 回答
1

您不能在非常简单的查询中执行此操作,因为GROUP BY(顺便说一下您在查询中遗漏了)不能保证它不会返回来自多行的混合值。

SELECT * FROM notifications AS t1
INNER JOIN (
    SELECT type, MAX(`created_at`) AS max_created_at
    FROM notification
    WHERE user_id=34
    GROUP BY `type`
) AS t2
    ON t1.type = t2.type
        AND t1.created_at = t2.max_created_at
于 2012-11-20T09:26:53.183 回答
0

以下查询created_at为每种类型选择最高的:

SELECT type, MAX(created_at) FROM notification GROUP BY type ORDER BY type

不知道你想如何将它与用户结合起来,你的问题不够精确。

以下查询created_at为特定用户的每种类型选择最高值:

SELECT user, type, MAX(created_at) 
  FROM notification 
 WHERE user = 34
 GROUP BY type, user 
 ORDER BY type, user
于 2012-11-20T09:24:14.513 回答
0
SELECT user_id, type, max(created_at) FROM notification WHERE user_id=34 GROUP BY user_id,type ORDER BY type
于 2012-11-20T09:25:17.163 回答
0
SELECT max(type) FROM notification WHERE user_id=34 ORDER BY type

试着像这样修改

SELECT user_id, type,created_at FROM notification WHERE user_id=34 ORDER BY type

那么如果你想从最新到最旧或从最旧到最新

添加ASCDESC订购

于 2012-11-20T09:25:18.413 回答