I am trying to write a query for my database.
Basically, I have an array of strings containing room numbers that I need to match up with another database containing events in the rooms. I want to find the next event happening in that room.
Ex:
I have an array room containing [ZACH102, ZACH103]. I want to find the database to return the next event happening in ZACH102 and ZACH103. I know how to find events for 1 room using the query below. But how do I do this using an array?
select name,
eventtime,
(eventtime - currenttime) > 0 as time_from_test
from the_table
where the_table.room = ZACH102
order by time_from_test
limit 1
Thanks in advance!
EDIT: Sorry if my explanation wasnt clear enough, but I only want the earliest event in each room in the array. Note the limit 1 at the end.
EDIT: Yes, I put the limit 1 there to mean that I only want 1 event from ZACH 102 and then i want 1 event from ZACH 103. I explained that the code above only finds events for 1 room.
In Sql Server I’d use a common table expression. But since it looks like you’re using mysql, I’d do something like this:
Eventually you’re gonna need to set this up dynamically, where you don’t know the contents of your
IN (...)clause in advance. When that time comes, the best thing to do is plan ahead so that your array is already stored in a table somewhere. That will give you two options. The first is to nest a sub query in yourIN (...)condition:The other is to use a join: