i'm displaying current week events to user.. fetching data from current date to +7 day of current date value.. it achived by using these query
SELECT * from events WHERE ( start_date BETWEEN '2013-01-01' AND '2013-01-07' ) order by start_date ASC
i have problem that if,
start_date 2013-01-01 have 10 records
start_date 2013-01-02 have 1 records
start_date 2013-01-03 have 12 records
....
...
then it take more time to fetching data from DB.. so, i need to display only 3 data form each day
My tabel,
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
expected output as ,
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
can any one help solve these... possible in single Query
This query should work
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
This will fetch 3 records per date. if you want to apply where condition uncomment it according to your needs
Output
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
Try this:
SELECT id, start_date, end_date, event_title
FROM (SELECT id, start_date, end_date, event_title,
IF(@lastDate=(@lastDate:=start_date), @auto:=@auto+1, @auto:=0) autoCol
FROM events e, (SELECT @lastDate:='', @auto:=0) A
WHERE start_date BETWEEN '2013-01-01' AND '2013-01-07'
ORDER BY start_date ASC) A
WHERE autoCol < 3;
Check this link SQL FIDDLE DEMO
OUTPUT
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
7 2013-01-02 2013-01-02 event_5
8 2013-01-03 2013-01-03 event_6
9 2013-01-03 2013-01-03 event_7
10 2013-01-03 2013-01-03 event_8
12 2013-01-04 2013-01-04 event_10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With