gpt4 book ai didi

php - MYSQL 获取每周数据的有限数据

转载 作者:可可西里 更新时间:2023-11-01 07:04:34 24 4
gpt4 key购买 nike

我正在向用户显示本周事件.. 从当前日期到当前日期值的 +7 天获取数据.. 它实现了通过使用这些查询

SELECT * from events WHERE ( start_date BETWEEN '2013-01-01' AND '2013-01-07' ) order by start_date ASC

我有问题,如果,

start_date 2013-01-01 have 10 records
start_date 2013-01-02 have 1 records
start_date 2013-01-03 have 12 records
....
...

然后从数据库中获取数据需要更多时间..所以,我每天只需要显示 3 个数据表

我的标签,

id      start_date      end_date        event_title

1 2013-01-01 2013-01-03 event_1
2 2013-01-01 2013-01-01 event_2
3 2013-01-01 2013-01-01 event_3
4 2013-01-01 2013-01-01 event_4
- 2013-01-01 2013-01-01 event_4
- 2013-01-01 2013-01-01 event_4

5 2013-01-02 2013-01-02 event_5

6 2013-01-03 2013-01-03 event_6
7 2013-01-03 2013-01-03 event_7
8 2013-01-03 2013-01-03 event_8
9 2013-01-03 2013-01-03 event_9

10 2013-01-04 2013-01-04 event_10

预期输出为,

id      start_date      end_date        event_title

1 2013-01-01 2013-01-03 event_1
2 2013-01-01 2013-01-01 event_2
3 2013-01-01 2013-01-01 event_3

4 2013-01-02 2013-01-02 event_5

5 2013-01-03 2013-01-03 event_6
6 2013-01-03 2013-01-03 event_7
7 2013-01-03 2013-01-03 event_8

8 2013-01-04 2013-01-04 event_10

谁能帮忙解决这些...可能在单个查询中

最佳答案

这个查询应该有效

SET @level = 0;
SET @group = '';
SELECT
*
FROM (
SELECT
id,
start_date,
end_date,
event_title,
@level := IF(@group = start_date, @level+1, 1) AS LEVEL,
@group := start_date AS StartDate
FROM test
/*WHERE start_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY)*/
ORDER BY start_date
) rs
WHERE LEVEL < 4

这将在每个日期获取 3 条记录。如果要申请where条件根据需要取消注释

Demo

输出

id  start_date  end_date    event_title level StartDate 
1 2013-01-01 2013-01-03 event_1 1 2013-01-01
2 2013-01-01 2013-01-01 event_2 2 2013-01-01
3 2013-01-01 2013-01-01 event_3 3 2013-01-01
7 2013-01-02 2013-01-02 event_5 1 2013-01-02
8 2013-01-03 2013-01-03 event_6 1 2013-01-03
9 2013-01-03 2013-01-03 event_7 2 2013-01-03
10 2013-01-03 2013-01-03 event_8 3 2013-01-03
12 2013-01-04 2013-01-04 event_10 1 2013-01-04

关于php - MYSQL 获取每周数据的有限数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14251806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com