列出仅用于运载水果的卡车
List the trucks that have only been used to carry fruit
假设数据库具有架构
TRUCK (license-plate, maker, model, year, mileage, max-load)
DRIVER (driver-id, name, age, address, license)
TRIP (license-plate, driver-id, date, origin, destination, miles, cargo, cost)
写关系代数和SQL列出只用来运水果的卡车的车牌。
我想出了一个解决方案
关系代数:
SQL:
不是正确答案。这是为什么?
一种解决方案是使用 EXISTS
运算符检查卡车是否运送水果而不是其他类型的货物:
SELECT license-plate
FROM truck
WHERE EXISTS (
SELECT 1
FROM trip
WHERE trip.license-plate = truck.license-plate
AND trip.cargo = 'fruit'
)
AND NOT EXISTS (
SELECT 1
FROM trip
WHERE trip.license-plate = truck.license-plate
AND trip.cargo <> 'fruit'
)
我会使用聚合。您的查询只需要一个 table:
select license_plate
from trip
group by license_plate
having min(cargo) = max(cargo) and
min(cargo) = 'fruit';
您的回答不正确,因为它returns 旅行的货物是水果。但是,它不考虑货物可能不是水果的同一卡车的 其他 次行程。
假设数据库具有架构
TRUCK (license-plate, maker, model, year, mileage, max-load)
DRIVER (driver-id, name, age, address, license)
TRIP (license-plate, driver-id, date, origin, destination, miles, cargo, cost)
写关系代数和SQL列出只用来运水果的卡车的车牌。
我想出了一个解决方案
关系代数:
SQL:
不是正确答案。这是为什么?
一种解决方案是使用 EXISTS
运算符检查卡车是否运送水果而不是其他类型的货物:
SELECT license-plate
FROM truck
WHERE EXISTS (
SELECT 1
FROM trip
WHERE trip.license-plate = truck.license-plate
AND trip.cargo = 'fruit'
)
AND NOT EXISTS (
SELECT 1
FROM trip
WHERE trip.license-plate = truck.license-plate
AND trip.cargo <> 'fruit'
)
我会使用聚合。您的查询只需要一个 table:
select license_plate
from trip
group by license_plate
having min(cargo) = max(cargo) and
min(cargo) = 'fruit';
您的回答不正确,因为它returns 旅行的货物是水果。但是,它不考虑货物可能不是水果的同一卡车的 其他 次行程。