I am looking for an SQL query that will return a 1 or a zero depending on a joined row’s content.
Two Tables:
Events:
- event_id
- descriptors
Qualifiers:
- qualifier_id
- event_id
- qualifier_type
- value
Each event can have multiple qualifiers.
The query that I currently have is:
select event_id, if(qualifier_type = 15, 1, 0)
from events
join qualifiers q using (event_id)
where q.qualifier_type = 15;
In a perfect world, I would nicely normalize these tables and put the different qualifiers in with the events, but this isn’t possible at the moment.
Edit: Currently, this query only returns rows that have the association. Instead, I need to return all rows and an extra column specifying if this association exists.
This gives you a list of all events with an indication of whether the qualifier type 15 is associated with the event.
Another way of writing the same thing is:
Both formulations rely on
COUNT(expr)only counting non-null values. For the events with a matching qualifier, the COUNT is 1; for the events without, it is 0. The first version compresses the query by including the condition on qualifier type into the ON join condition. The second version is clearer, but more verbose. The chances are that a good optimizer will execute both queries the same way.