I have to write this query and I think I need some help. I'm using CodeIgniter (last version) with Mysql.
I have this small table "events" with the folowing structure:
And what I want to do is to for each venue_id
select 2 events.
The outcome of the query would be something like:
Venue_id number 1 : event1, event 2
venue_id number 2 : event 5, event 6
In other words, and just to be clear. I need to select 2 events per club.
I'm trying something like:
SELECT * FROM (`events`) GROUP BY `venue_id` LIMIT 2
But I need to group by and limit by venue_id
Is there a way to do this only by sql query, or should I count on php to work around it ?
Example, I'm a bit confused since there is no attribute active in your table, but it exists in your query.
If it's any 2 events
SELECT e1.venue_id, MIN(e2.name), MAX(e2.name)
FROM events e1
JOIN events e2
ON e1.venue_id = e2.venue_id
GROUP BY e1.venue_id
If you just want the event id, then use group_concat()
and substring_index()
:
select e.venue_id, substring_index(group_concat(e.id), ',', 2)
from events e
group by e.venue_id;
If you want the full records for two venues, I'd take this approach:
select e.*
from events e join
(select venue_id, min(id) as minid, max(id) as maxid
from events
group by venue_id
) v
on e.venue_id = v.venue_id and
(e.id = minid or e.id = maxid);
EDIT:
The following is one way to get up to "n" events for a given venue:
select e.*
from events e
where n >= (select count(*)
from events e2
where e2.venue_id = e.venue_id and
e2.id <= e.id
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.