我有WHERE
子句条件涉及ALL
子查询。有时子查询结果为空,在这种情况下,表达式始终计算为true
,但我希望它评估为false
。
例如,假设我有一个驱动程序表,一个路由表和一个多对多交互表,显示每个驱动程序驱动的路由。我想找到驾驶路线超过50英里的司机。
SELECT * FROM driver
WHERE 50 < ALL(
SELECT miles FROM route, driver_route
WHERE driver_route.route_id = route.id AND
driver_route.driver_id = driver.id)
此查询将包括未在结果中驱动任何路由的驱动程序,这不是我想要的。
我尝试过使用coalesce,但遇到了ERROR: more than one row returned by a subquery used as an expression
。以下是我对该查询的措辞:
SELECT * FROM driver
WHERE 50 < COALESCE((
SELECT ALL(SELECT miles FROM route, driver_route
WHERE driver_route.route_id = route.id AND
driver_route.driver_id = driver.id)),
0);
我正在寻找一种足以应用于不同类型和查询的结构。
答案 0 :(得分:2)
我认为你需要这个:
select driver.* from driver inner join (
select driver.id from driver
inner join driver_route
on driver.id = driver_route.driver_id
inner join route
on route.id = driver_route.route_id
group by driver.id
having min(route.miles) > 50
)t
on driver.id = t.id
答案 1 :(得分:1)
这个怎么样?
SELECT * FROM driver
WHERE NOT EXISTS (
SELECT miles FROM route, driver_route
WHERE driver_route.route_id = route.id AND
driver_route.driver_id = driver.id AND
miles <= 50
)
AND EXISTS (
SELECT miles FROM route, driver_route
WHERE driver_route.route_id = route.id AND
driver_route.driver_id = driver.id AND
miles > 50
)
全部大于50等于没有小于或等于50。