我正在尝试使用以下sql查询
SELECT task.id,task.Task,task.TaskCategory,task.IsComplete,
task.AssignedDate,task.CompletionDate, task.AssignedTo,task.templateID,task.ListingID,task.ClosingID,
task.ContactID,task.LeadID,task.statusid, taskcategory.taskCategoryID,taskcategory.Category FROM
task INNER JOIN taskcategory ON task.TaskCategory = taskcategory.taskCategoryID WHERE 1=1
and (CompletionDate = CURDATE() OR CompletionDate IS NULL AND task.IsComplete = 0)
and assignedto = 2345 and id = 2421 and
CASE(WHEN status_for_design = 0 THEN (leadid is not null or ContactID is not null)
THEN NULL
END AS status_for_design)
group by
assignedto ORDER BY task.AssignedDate ASC
主要目的是,如果status_for_design = 0 [使用leadid或contactid不为null,但如果status_for_design = 1
但我面临一个错误
[Err] 1064 - 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 'WHEN status_for_design = 0 THEN (leadid is not null or ContactID is not null)
T' at line 7
答案 0 :(得分:0)
不,你不能在CASE
条款中包含WHERE
条件。这就是它所抱怨的。如果您打算在SELECT
子句中使用它,则将case表达式移动到SELECT
子句。否则,您可以在CASE
子句
WHERE
转换为低于复合条件
AND ((status_for_design = 0 AND leadid is not null)
AND (status_for_design = 0 AND ContactID is not null))
答案 1 :(得分:0)
实际上,格式化您的查询以便人们可以阅读它将有助于您了解正在发生的事情。
您的WHERE
子句中包含AS
。这不合适。我怀疑你想要的查询看起来更像是这样:
SELECT t.*, tc.taskCategoryID, tc.Category
FROM task t INNER JOIN
taskcategory tc
ON t.TaskCategory = tc.taskCategoryID
WHERE 1 = 1 AND
(CompletionDate = CURDATE() OR CompletionDate IS NULL AND t.IsComplete = 0) AND
assignedto = 2345 AND
id = 2421 AND
(status_for_design <> 0 or leadid is not null or ContactID is not null)
GROUP BY assignedto
ORDER BY t.AssignedDate ASC ;
请注意CASE
中不需要WHERE
。我也非常怀疑SELECT
中未列入GROUP BY
的未聚合列的查询。