所以我想根据一个字段是否为空来运行不同的查询。这就是我所拥有的
m
我得到的错误是SELECT
CASE
WHEN vehicle_uid IS NULL THEN (SELECT lic_num, vehicle_make, vehicle_model, zone.name
FROM notice
INNER JOIN zone on notice.zone_uid = zone.uid
WHERE lic_num IN (
SELECT lic_num
FROM notice
GROUP BY lic_num
HAVING count(*) > 1
))
ELSE (SELECT lic_num, vehicle_uid, model.model, make.make, zone.name
FROM notice
INNER JOIN vehicle_model AS model ON notice.vehicle_uid = model.uid
INNER JOIN vehicle_make AS make ON model.vehicle_make_uid = make.uid
INNER JOIN zone on notice.zone_uid = zone.uid
WHERE lic_num IN (
SELECT lic_num
FROM notice
GROUP BY lic_num
HAVING count(*) > 1
))
END
当我将#1054 - Unknown column 'vehicle_uid' in 'field list'
更改为WHEN vehicle_uid IS NULL
时,错误显示为:WHEN notice.vehicle_uid IS NULL
我也试过了
#1109 - Unknown table 'notice' in field list
出现以下错误:SELECT
CASE vehicle_uid
WHEN IS NULL THEN ...
我只是从更复杂的查询开始,并且不知道为什么这是错误的。
答案 0 :(得分:0)
您在外部查询中缺少FROM
子句。
答案 1 :(得分:0)
您不能在select
语句中执行子查询,该语句返回多个字段,也不会返回多行。您看到的错误是因为您从无处选择了一个字段vehicle_uid
,您不会在数据库中找到from
子句,知道它来自哪里。
解决问题的最佳方法是使用特定条件执行UNION
,但仅当两个查询具有相同的列集时才会起作用:
SELECT lic_num,
vehicle_make,
'' SUBSTITUTE_FORVEHICLEUID,
vehicle_model,
'' SUBSTITUTE_FOR_MAKE,
zone.name
FROM notice
INNER JOIN zone ON notice.zone_uid = zone.uid
WHERE lic_num IN (
SELECT lic_num
FROM notice
GROUP BY lic_num
HAVING count(*) > 1
)
AND vehicle_uid is null
UNION
SELECT lic_num,
'' SUBSTITUTE_FOR_VEHICLEMAKE,
vehicle_uid,
model.model,
make.make,
zone.name
FROM notice
INNER JOIN vehicle_model AS model ON notice.vehicle_uid = model.uid
INNER JOIN vehicle_make AS make ON model.vehicle_make_uid = make.uid
INNER JOIN zone on notice.zone_uid = zone.uid
WHERE lic_num IN (
SELECT lic_num
FROM notice
GROUP BY lic_num
HAVING count(*) > 1
)
AND vehicle_uid IS NOT NULL
即使这是您问题的最佳选择,您也必须调整两个查询。因为我不知道你的结构是我能帮到的最好的结构。
答案 2 :(得分:-1)
您应该将UNION与两个返回相同列的SELECT语句一起使用。
(SELECT lic_num, vehicle_make uid_or_make, vehicle_model, '', zone.name
FROM notice
INNER JOIN zone on notice.zone_uid = zone.uid
WHERE lic_num IN (SELECT lic_num FROM notice GROUP BY lic_num HAVING count(*) > 1) AND vehicle_uid IS NULL
)
UNION ALL
(SELECT lic_num, vehicle_uid uid_or_make, model.model vehicle_model, make.make, zone.name
FROM notice
INNER JOIN vehicle_model AS model ON notice.vehicle_uid = model.uid
INNER JOIN vehicle_make AS make ON model.vehicle_make_uid = make.uid
INNER JOIN zone on notice.zone_uid = zone.uid
WHERE lic_num IN (SELECT lic_num FROM notice GROUP BY lic_num HAVING count(*) > 1) AND vehicle_uid IS NOT NULL
)