我正在努力使用户项目的通知系统尽可能简单。
"约翰·布朗和另外4人喜欢你的照片"
我试过了:
Select a.id, a.item_id, a.type u.f_name, u.l_name, count(a)
From alerts
Join users on a.user_id = u.u_id
Where owner_id = {THE_USER_ID}
但它没有"工作"
用户表
u_id | f_name | l_name
==========================
234 roy wright
654 pam brown
564 kim harris
334 tory plummer
876 rick forbes
123 paul nichol
980 mario chang
454 todd thompson
886 sam richards
215 tash gates
... ..... ........
警报表
id | item_id | type | user_id | owner_id
===================================================
1 21 like 234
2 21 comment 654
3 32 share 876
4 21 like 778
5 21 like 890
6 21 share 123
7 54 share 454
8 32 comment 655
9 60 comment 886
10 32 like 215
.. .. ...... ...
我想要的结果
id | item_id | type | u_id | f_name | l_name | amount_more
============================================================
1 21 like 234 roy wright 2
2 21 comment 654 pam brown
3 32 comment 876 rick forbes
6 21 share 123 paul nichol
7 54 share 454 todd thompson
9 60 comment 886 sam richards
10 32 like 215 tash gates
.. .. .... ... ..... ........
答案 0 :(得分:0)
SELECT
MIN(CASE WHEN RowNumber = 1 THEN id END) as Id
,item_id
,type
,MIN(CASE WHEN RowNumber = 1 THEN u_id END) as u_id
,MIN(CASE WHEN RowNumber = 1 THEN f_name END) as f_name
,MIN(CASE WHEN RowNumber = 1 THEN l_name END) as l_name
,COUNT(*) - 1 as amount_more
FROM
(
SELECT
t.*
,(@rn:= if((@item = t.item_id) AND (@type = t.type),@rn + 1,
if((@item:=t.item_id) AND (@type:=t.type),1,1)
)
) as RowNumber
FROM
(SELECT *
FROM
alerts a
LEFT JOIN usersTbl u
ON a.user_id = u.u_id
WHERE
a.owner_id = 201
ORDER BY
a.item_id
,a.type
,a.id) t
CROSS JOIN (SELECT @rn:=0,@item:=0,@type:='') var
ORDER BY
item_id
,type
,id
) t2
GROUP BY
item_id
,type
ORDER BY
id
;
因此,您需要创建一个分区行号,以识别您想要首先考虑的记录。然后使用条件聚合,您可以选择它作为您的用户。这可以在这里查看:http://rextester.com/VXZONO82847
答案 1 :(得分:-1)
在查询中,您没有正确使用别名a和u,请使用此:
Select
a.id,
a.item_id,
a.type,
u.f_name,
u.l_name,
count(a.*)
From alerts a Join users u
on(a.user_id = u.u_id)
Where owner_id = {THE_USER_ID}
group by 1,2,3,4,5;