2013-03-20 50 views
0

我正在实施通知系统。我的表结构有点像这个..逐列逐行获得列值最大的行

ID(自动递增主键)
USER_ID(谁通知应显示的用户的用户ID,INT)
triggered_by(用户谁触发通知,INT)
POST_ID(交的量,通知存在,INT)
类型(该通知的类型,INT)
看出(已经通知被读取,布尔)

当我将通知标记为可见时,我使用了post_id和type,这意味着我们可以安全地假设,如果查看了具有最大id的行,则会查看该post_id和type的所有先前行。

现在,我想为该post_id和type获取与之前条目相结合的行,以及为该post_id和type注册的行数。我当前的查询是

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”的最外层查询的WHERE子句将返回任何随机行的“看到”的列,其中,因为我想它返回的其他数据则来自计数具有最大ID的行。

+0

请首先检查您的查询,您的查询不正确。你最后得到了这个组,但是最上面的选择列表有许多不在列表中的列,你确定这个查询可以运行吗? – ljh 2013-03-20 18:56:22

+0

是这个查询运行良好。 – Sourabh 2013-03-21 03:09:15

回答

0

试试这个:

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 

除非你是什么意思“结合以前的条目为POST_ID和类型”? 你是说你想让这个查询合并成一行输出,源表中不同行的值?就像从一行中获取post_id,但从一些不同的早期行中获取Triggered_By?

+0

通过与以前的条目相结合,应该将该post_id和type的所有先前条目分组,并且该计数应该在列中。 – Sourabh 2013-03-21 03:08:23