带有否定的MYSQL中的多个案例陈述

时间:2013-10-28 10:22:51

标签: php mysql sql

考虑以下mysql语句:

SELECT costs.cost AS package, payments.cost AS labs, patients.fname, patients.lname, patients.sname, visit.id AS visitid, patients.id, pharm_payments.cost AS pharm_costs ,costs.cost+payments.cost+pharm_payments.cost AS total_cost ,
CASE pharm_payments.cost WHEN pharm_payments.visitid=visit.id THEN pharm_payments.cost
WHEN pharm_payments.visitid != visit.id THEN 0
CASE costs.cost WHEN cost.visitid=visit.id THEN costs.cost
WHEN costs.visitid != visit.id THEN 0
FROM costs
LEFT JOIN visit ON costs.visitid = visit.id
LEFT JOIN patients ON visit.patientid = patients.id
LEFT JOIN pharm_payments ON pharm_payments.visitid = visit.id
LEFT JOIN payments ON payments.visitid = visit.id
WHERE costs.paid =  'not paid'
AND visit.VisitDate >= CURDATE( ) 
LIMIT 0 , 30

查询的预期结果应该是访问ID不相同的位置,它应该返回零值。我一直收到以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE costs.cost WHEN cost.visitid=visit.id THEN costs.cost WHEN costs.visitid !=' at line 4

如何解决此错误?

3 个答案:

答案 0 :(得分:0)

我不熟悉在SQL语句中使用caseshouldn't you put an END after?

答案 1 :(得分:0)

我认为你的案例陈述应该是这样的:

.......
CASE 
    WHEN pharm_payments.visitid=visit.id 
    THEN pharm_payments.cost
    ELSE 0
END AS Column1,
CASE 
    WHEN cost.visitid=visit.id 
    THEN costs.cost
    ELSE 0
END AS Column2

<强>更新

总结一下,你可以这样做:

.......
(
   CASE 
       WHEN pharm_payments.visitid=visit.id 
       THEN pharm_payments.cost
       ELSE 0
   END
) 
+
(
   CASE 
       WHEN cost.visitid=visit.id 
       THEN costs.cost
       ELSE 0
   END 
)AS total

答案 2 :(得分:0)

SELECT 
  costs.cost AS package,
  payments.cost AS labs,
  patients.fname,
  patients.lname,
  patients.sname,
  visit.id AS visitid,
  patients.id,
  pharm_payments.cost AS pharm_costs,
  costs.cost + payments.cost + pharm_payments.cost AS total_cost,
  CASE
    pharm_payments.cost 
    WHEN pharm_payments.visitid = visit.id 
    THEN pharm_payments.cost 
    WHEN pharm_payments.visitid != visit.id 
    THEN 0 END AS  pharm_payments_cost,
    CASE
      costs.cost 
      WHEN cost.visitid = visit.id 
      THEN costs.cost 
      WHEN costs.visitid != visit.id 
      THEN 0 END AS costs_cost 
FROM
  costs 
  LEFT JOIN visit 
    ON costs.visitid = visit.id 
  LEFT JOIN patients 
    ON visit.patientid = patients.id 
  LEFT JOIN pharm_payments 
    ON pharm_payments.visitid = visit.id 
  LEFT JOIN payments 
    ON payments.visitid = visit.id 
WHERE costs.paid = 'not paid' 
  AND visit.VisitDate >= CURDATE() 
LIMIT 0, 30