我正在实施通知系统。我的表结构有点像这样..
id(自动增量主键)
user_id(应显示通知的用户的用户ID,int)
triggered_by(触发通知的用户,int)
post_id(通知存在的帖子,int)
type(通知的类型,int)
看到(通知已被阅读,布尔)
当我标记通知时,我正在使用post_id和type,这意味着我们可以安全地假设,如果看到具有最大id的行,则会看到该post_id和type的所有先前行。
现在,我想获取与post_id和type的先前条目相结合的行,以及为该post_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'子句返回任何随机行的'seen'列,我希望它返回其他数据,然后从id最大的行开始计数。
答案 0 :(得分: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?