Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按列分组以获取列中具有最大值的行_Sql_Database_Database Design_Greatest N Per Group - Fatal编程技术网

Sql 按列分组以获取列中具有最大值的行

Sql 按列分组以获取列中具有最大值的行,sql,database,database-design,greatest-n-per-group,Sql,Database,Database Design,Greatest N Per Group,我正在实施通知制度。我的桌子结构有点像这样 id(自动递增主键) 用户id(应显示通知的用户的用户id,int) 触发者(触发通知的用户,int) post\u id(存在通知的post,int) 类型(通知的类型,int) 已看到(通知是否已阅读,bool) 当我将通知标记为seen时,我使用的是post_id和type,这意味着我们可以安全地假设,如果看到具有最大id的行,那么该post_id和type的所有前面的行都将被看到 现在,我想获取与该post\u id和类型的先前条目相结合的行,

我正在实施通知制度。我的桌子结构有点像这样

id(自动递增主键)
用户id(应显示通知的用户的用户id,int)
触发者(触发通知的用户,int)
post\u id(存在通知的post,int)
类型(通知的类型,int)
已看到(通知是否已阅读,bool)

当我将通知标记为seen时,我使用的是post_id和type,这意味着我们可以安全地假设,如果看到具有最大id的行,那么该post_id和type的所有前面的行都将被看到

现在,我想获取与该post\u id和类型的先前条目相结合的行,以及为该post\u id和类型注册的行数。我现在的问题是

select max(x.id) as id, 
   x.post_id as post_id, 
   x.seen as seen, 
   x.user_id as user_id, 
   x.triggered_by as triggered_by, 
   x.type as type, 
   x.count as count
from (SELECT notification.id, 
       notification.post_id, 
       notification.user_id, 
       notification.triggered_by, 
       notification.type, 
       c.count,  notification.seen 
     FROM `notification`
         join (select post_id, type, count(id) as count 
               from notification group by post_id, type) c 
           on c.type=notification.type 
             and c.post_id=notification.post_id 
     Where notification.user_id=1) x 
Group by post_id 
Order by id desc limit 10
此查询的问题是,最外层查询的“group by”子句返回任意随机行的“SEED”列,我希望该列返回数据,然后从id最大的行中进行计数。请尝试以下操作:

 Select id, post_id, seen,
    user_id, triggered_by, type, 
   (Select Count(*) From notification
    Where type = N.Type
      And post_id = n.post_id) Count
 From Notification n
 where user_id = 1
 Order by id desc limit 10
除了你所说的“与该职位id和类型的先前条目相结合”是什么意思??
您的意思是希望此查询合并到一行输出中,即源表中不同行的值?例如从一行获取帖子id,但从其他较早的行获取触发的帖子id?

请先检查您的查询,您的查询看起来不正确。最后是group by,但顶部的选择性列表中有许多列不在group by列表中,您确定此查询可以运行吗?是的,此查询运行良好。通过与以前的条目相结合,该post_id和类型的所有以前的条目都应该分组,并且计数应该在列中。