我在mySQL查询中有一个IF语句,它运行良好:
GROUP_CONCAT(DISTINCT CONCAT("animal:",if(animal.name="monkey","fred",""),",color: ",animal.color) SEPARATOR " <br>") AS animals
我现在要添加一个ELSEIF:
GROUP_CONCAT(DISTINCT CONCAT("animal:",if(animal.name="monkey","fred","")elseif(animal.name="cat","jane",""),",color: ",animal.color) SEPARATOR " <br>") AS animals
但是我收到了一条错误消息:
语法错误或访问冲突:1064 SQL中有错误 语法
答案 0 :(得分:1)
&#34; if elseif endif&#34;是一个控制语句,而if()是MySQL中的一个函数。虽然它们具有相同的名称,但它们是不同的东西。
如果您有多个选项,则可以使用CASE而不是IF。
SELECT
GROUP_CONCAT(DISTINCT CONCAT("animal:",
CASE animal.name
WHEN "monkey" THEN "fred"
WHEN "cat" THEN "jane"
ELSE "other"
END,
",color: ",animal.color) SEPARATOR " <br>"
) AS animals
FROM (
SELECT 'monkey' AS 'name', 'brown' AS 'color'
UNION
SELECT 'cat', 'white'
UNION
SELECT 'dog', 'black'
) AS animal
答案 1 :(得分:1)
您必须在if
else
部分添加if
group_concat(distinct concat("animal:",if(animal.name="monkey","fred",if(animal.name="cat","jane","")),",color: ",animal.color) separator " <br>") as animals
case
语法几乎相同
group_concat(distinct concat("animal:",case animal.name when "monkey" then "fred" when "cat" then "jane" case "dog" then "donald" else "",",color: ",animal.color) separator " <br>") as animals