创建MySQL视图时case语句中的语法错误

时间:2015-07-22 08:32:59

标签: mysql mysqli

我在尝试创建视图时遇到mysql#1064错误

CREATE VIEW trip_summary AS select `driver_details`.`DriverId`, CONCAT(driver_details.Firstname, ' ', driver_details.Lastname, ' ', driver_details.TaxiPlateNo) AS TaxiDriver, count(taxi_trip.AutoId) AS TotalTrip, GROUP_CONCAT(taxi_trip.AutoId) AS TripIds, sum(taxi_trip.TripDistance) AS TotalTripDistance, sum(taxi_trip.TotalFare) AS TotalTripFare from `driver_details` left join `taxi_trip` on (`taxi_trip`.`DriverId` = `driver_details`.`DriverId` and `taxi_trip`.`PickupLAT` != 0 and `taxi_trip`.`DropLAT` != 0 and `taxi_trip`.`TotalFare` != 0) where taxi_trip.AutoId!=0 and 
  CASE WHEN `DriverIdFun`()!='' THEN taxi_trip.DriverId = `DriverIdFun`()
  END AS field1,
  CASE WHEN `From_Date`()!='' THEN taxi_trip.RequestDate >= `From_Date`()
  END AS field2,
  CASE WHEN `To_Date`()!='' THEN taxi_trip.RequestDate <= `To_Date`()
  END AS field3 group by taxi_trip.DriverId

2 个答案:

答案 0 :(得分:0)

这不是一个完整的答案,但可能包含足够的信息以帮助您入门....

通常(但不是每次),对一组数据库表的VIEW没有WHERE子句,在您的情况下,WHERE子句看起来像狗的早餐。

我从这个更简单的观点开始,并从这里发展....

CREATE VIEW trip_summary AS 
SELECT 
  dd.`DriverId`, 
  CONCAT(dd.Firstname, ' ', dd.Lastname, ' ', dd.TaxiPlateNo) AS TaxiDriver, 
  count(tt.AutoId) AS TotalTrip, 
  GROUP_CONCAT(tt.AutoId) AS TripIds, 
  sum(tt.TripDistance) AS TotalTripDistance,
  sum(tt.TotalFare) AS TotalTripFare
FROM `driver_details` AS dd
LEFT JOIN `taxi_trip` AS tt 
ON tt.`DriverId` = dd.`DriverId` 
  AND tt.`PickupLAT` != 0 
  AND tt.`DropLAT` != 0 
  AND tt.`TotalFare` != 0
GROUP BY tt.DriverId

然后,当您查询视图时,通过where子句

选择您所做的和不想要的视图。
SELECT * FROM trip_summary WHERE DriverID=1234;

答案 1 :(得分:0)

这是创建我需要的视图的正确查询

CREATE VIEW trip_summary AS
select
`driver_details`.`DriverId`,
CONCAT(driver_details.Firstname, ' ', driver_details.Lastname, ' ',
driver_details.TaxiPlateNo) AS TaxiDriver,
count(taxi_trip.AutoId) AS TotalTrip,
GROUP_CONCAT(taxi_trip.AutoId) AS TripIds,
sum(taxi_trip.TripDistance) AS TotalTripDistance,
sum(taxi_trip.TotalFare) AS TotalTripFare
from `driver_details`
left join `taxi_trip`
on (`taxi_trip`.`DriverId` = `driver_details`.`DriverId`
and `taxi_trip`.`PickupLAT` != 0
and `taxi_trip`.`DropLAT` != 0
and `taxi_trip`.`TotalFare` != 0)
where taxi_trip.AutoId!=0
and
CASE
    WHEN `DriverIdFun`()!=''
        THEN taxi_trip.DriverId = `DriverIdFun`()
    ELSE
        TRUE
END
AND
CASE
    WHEN `From_Date`()!=''
        THEN taxi_trip.RequestDate >= `From_Date`()
    ELSE
        TRUE
END
AND
CASE
    WHEN `To_Date`()!=''
        THEN taxi_trip.RequestDate <= `To_Date`()
    ELSE
        TRUE
END
group by taxi_trip.DriverId