嘿,我对 sql 很陌生,我似乎找不到解决问题的好方法。我有以下实体
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)).
我想制作一个脚本,查找至少已登机的所有乘客的姓名,如果登机超过一个,则这些航类必须是使用同一架飞机进行的。我尝试返回一个包含的元组每位乘客使用过的飞机,使用嵌套查询。然后我尝试使用 all 语句,检查类型中的每个条目是否相同。不过我没有运气。任何建议都会受到重视。
编辑:我想到了以下解决方案,但我不知道它是否正确:
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;
最佳答案
更新:根据OP对答案的评论,这是使用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)
也许使用如下所示的 JOIN
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
关于mysql - 如何检查嵌套查询返回的元组中的每个条目是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71973583/