How to check if each entry in a returned tuple from a nested query is the same?

Viewed 56

Hey i'm quite new to sql and i can't seem to find a good of a way to solve a problem.I have the following entities

passengers (`id` INT, `name` VARCHAR(45), `surname` VARCHAR(45),
`year_of_birth` INT) 

flights (`id` INT, `routes_id` INT, `date` DATE, `airplanes_id` INT) 

flights_has_passengers (`flights_id` INT, `passengers_id` INT)

airplanes (`id` INT, `number` VARCHAR(45), `manufacturer`
VARCHAR(45), `model` VARCHAR(45)).

I want to make a script that finds the names of all the passengers , that have boarded in atleast on flight and if boarded more than one,those flights must have been made using the same airplane.I tried to return a tuple containing the planes, that each one of the passengers had used,using a nested query.Then i tried to use an all statement, to check if every entry in the typle is the same.I got no luck though .Any advice would be appriciated.

EDIT : I thought the following solution but i don't know if it is correct:

     select p1.name, p1.surname
    from passengers p1, airplanes a1, flights_has_passengers, flights
    where
        p1.id = flights_has_passengers.passengers_id and
        flights_has_passengers.flights_id = flights.id and
        flights.airplanes_id = a1.id
        group by p1.id
        having count(a1.id) = 1;
1 Answers

UPDATE: Based on OP's comment on the answer, here's another way using NOT EXISTS

Hey thanks for your answer.Is there another way to implement this without a join statement ?For example something like not exists or all ?

select p.id
from passengers p 
join flights_has_passengers  fp 
  on p.id= fp.passengers_id
join flights f
  on f.id=fp.flights_id
 where not exists 
 (select 1 from join flights f1 
 where f1.id=f.id
 and f1.airplanes_id<>f.airplanes_id)

Maybe use a JOIN like below

select p.id
from passengers p 
join flights_has_passengers  fp 
  on p.id= fp.passengers_id
join flights f
  on f.id=fp.flights_id
group by p.id
having count(f.airplanes_id)=1
Related