I've been trying to find a way to get a Yes/No answer to a query without using control flow functions(IIF,ELSE,CASE,COALESCE,ISNULL,IFNULL,etc). I want my query to give me a "Yes" answer if there has been a flight of a certain Airline on a given date between 2 given airports. This is what i have done so far
SELECT 'Yes' as Answer
FROM flights
WHERE flights.date = '2014-12-12' AND flights.routes_id IN (SELECT routes.id
FROM routes
INNER JOIN airlines
ON airlines.id = routes.airlines_id
WHERE airlines_id IN (SELECT airlines.id
FROM airlines
WHERE airlines.name='Olympic Airways')
AND routes.source_id = (SELECT airports.id
FROM airports
WHERE airports.name like '%Venizelos%')
AND routes.destination_id=(SELECT airports.id
FROM airports
WHERE airports.name like 'London Gatwick'))
UNION
SELECT 'No' AS Answer
FROM flights
WHERE flights.date = '2014-12-12' AND flights.routes_id NOT IN (SELECT routes.id
FROM routes
INNER JOIN airlines
ON airlines.id = routes.airlines_id
WHERE airlines_id IN (SELECT airlines.id
FROM airlines
WHERE airlines.name = 'Olympic Airways')
AND routes.source_id = (SELECT airports.id
FROM airports
WHERE airports.name like '%Venizelos%')
AND routes.destination_id=(SELECT airports.id
FROM airports
WHERE airports.name like 'London Gatwick'))
The problem is that when i run the queries it prints both Yes and No, when it should print only one of those two. How can it be fixed?
This happens because in that day there will be flight for that airline, but also for others, from/to that airports but also from others.
Put your query inside another query like:
SELECT Max(Answer)
from (
your query from the question
)
This will return Yes
if you have at leas a good flight (because the internal query will return Yes
and No
) and No
if you have only no matches (the results from the internal query will be only No
).
Hope this helps.
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.