[英]Mysql query counter x/y
It's possible to create a query that return the x/y number of records? 可以创建一个返回x / y记录数的查询吗?
Eg. 例如。 I have table like this
我有这样的表
ID | id_user | id_event
23 | 3 | 1
24 | 3 | 1
25 | 3 | 1
26 | 4 | 2
27 | 4 | 2
I will return something that looks like this: 我会返回看起来像这样的东西:
Event 事件
id_user 3 -> **1/3**
id_user 3 -> **2/3**
id_user 3 -> **3/3**
id_user 4 -> **1/2**
id_user 4 -> **2/2**
Any suggestion is appreciated! 任何建议表示赞赏!
Try this 尝试这个
SET @id_event := 0;
SELECT CONCAT('id_user ', id_user ,'->','**', (@id_event := @id_event + 1) ,'/', id_user ,** ) from table
This is probably a duplicate to this question . 这可能是这个问题的重复。
SELECT CONCAT('id_user ',id_user,' -> **',rank,'/',group_total,'**') FROM (
SELECT id,
group_total,
CASE id_user
WHEN @id_user THEN
CASE id_event
WHEN @id_event THEN @rowno := @rowno + 1
ELSE @rowno := 1
END
ELSE @rowno :=1
END AS rank,
@id_user := id_user AS id_user,
@id_event := id_event AS id_event
FROM event_table
JOIN (SELECT id_user, id_event, COUNT(*) group_total FROM event_table GROUP BY id_user, id_event) t USING (id_user, id_event)
JOIN (SELECT @rowno := 0, @id_user := 0, @id_event := 0) r
ORDER BY id_user, id_event
) c;
Assuming you want output like this: 假设您想要这样的输出:
id_user < id_user > **
serial number of event related to this user
/ total events related to this user
** id_user < id_user > **
serial number of event related to this user
/ total events related to this user
**
You can accomplish such result by the following query: 您可以通过以下查询完成此类结果:
SELECT
CONCAT('id_user ',UE.id_user,' -> **',IF(@userID = UE.id_user, @eventNumber := @eventNumber + 1, @eventNumber := 1),'/',t.totalEvents,'**') AS output,
@userID := UE.id_user
FROM (SELECT @userID := -1, @eventNumber := 1) var,user_events UE
INNER JOIN
(
SELECT
id_user,
COUNT(id_event) totalEvents
FROM user_events
GROUP BY id_user
) AS t
ON UE.id_user = t.id_user
ORDER BY UE.id_user;
SQL FIDDLE DEMO SQL FIDDLE DEMO
More: 更多:
SQL FIDDLE DEMO 2 SQL FIDDLE DEMO 2
This particular fiddle returns only the desired output column whereas the first fiddle contains one extra column 这个特殊的小提琴只返回所需的输出列,而第一小提琴包含一个额外的列
I played a little bit and that would be my solution: 我玩了一点,这将是我的解决方案:
SELECT id, id_user, id_event, if(@n = a.id_event, @c:=@c+1, if(@n:=a.id_event, @c:=1, @c:=1)) as count, (SELECT count(*) from TABLE b WHERE a.id_user = b.id_user) as total, from TABLE a join (SELECT @n:= "", @c:=1) c
It just have two if conditions for counting a @c up if @n and id_user matches if not @n become id_user and @c is 1 again. 如果没有@n成为id_user并且@c再次为1,那么只有两个if条件用于计算@c up @ if和id_user匹配。 The join is for initialize the var in the same query.
连接用于在同一查询中初始化var。
Thx to that question, i found the answer to a questions that i asked 4 days ago. 对于那个问题,我找到了我4天前提出的问题的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.