Question

I have an "events" table and a "events_dates" table. "events_dates" has a reference to event_id in "events" table. I would like to build a stored function that checks if NOW() is bigger of ALL the dates in "events_dates" referred to a specific event_id. I have written that function in order to get a tinyint(1) value (1 if true, 0 if false), but I get always false. Moreover, I think I get lost using loops. What would you do in my place?

I want to use that function in a bigger query and use it like:

SELECT e.*, ed.*
FROM events e INNER JOIN
     events_dates ed
     ON e.event_id = ed.fk_event_id
 WHERE IF (checkIfAllDatesArePassed(e.event_id),DATEDIFF(ed.event_date,NOW())<0,DATEDIFF(ed.event_date,NOW())>0)

Actually it is a little bit more complex, but I am sure you get what the point is :)

Thanks everybody.

Était-ce utile?

La solution

I would use the ALL keyword, e.g.

select *
from events
where now() > all (select event_date from events_dates where fk_event_id = event_id)

Supposing event_id is a parameter of your function.

I could not fathom what the checkIfAllDatesArePassed was supposed to be however.

Update from the comments:

drop function if exists checkIfAllDatesArePassed;
delimiter $$
create function checkIfAllDatesArePassed(event_id integer)
returns integer
language sql
begin
return select case
when now() > all (select event_date from events_dates where fk_event_id = event_id) then 1
else 0;
end;
$$
delimiter;

Would that do?

Autres conseils

If you just want the events that meet this criteria along with a flag:

SELECT ed.event_id,
       (max(event_date) < now()) as AllDatesPast
FROM events_dates ed
group by event_id;

If you want the event information, then join in events:

SELECT e.*
FROM events e join
     events_dates ed
     on e.event_id = ed.fk_event_id
group by e.event_id
having max(event_date) < now();

And if you want the dates:

SELECT e.*, ed.*
FROM events e join
     events_dates ed
     on e.event_id = ed.fk_event_id
WHERE not exists (select 1
                  from event_dates ed2
                  where e.event_id = ed2.event_id and
                        event_date > now()
                 ) ;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top