MYSQL中的COALESCE函数与select给出错误

时间:2014-04-28 01:57:32

标签: mysql coalesce

我想知道我的查询有什么问题对我来说很简单,请看看,如果我错过了什么请告诉我

SELECT users.*, p.*, 
COALESCE(SELECT picture_location FROM pictures 
WHERE user_id = 'patient' AND default_pic = 1, 
SELECT picture_location FROM pictures 
WHERE user_id = 'patient' ORDER BY id ASC LIMIT 1) AS default_pic, 
pic.picture_location, MONTHNAME(users.registered_on) AS month_reg,
YEAR(users.registered_on) AS year_reg FROM users 
LEFT JOIN profile p ON p.profile_id = users.profile_id 
LEFT JOIN pictures pic ON pic.user_id = p.profile_id 
WHERE users.pseudo = 'patient' GROUP BY users.pseudo 
ORDER BY pic.default_pic DESC LIMIT 1
你看到了什么吗?它让我回答:

1064 - 您的SQL语法出错;查看与您的MySQL服务器版本相对应的手册,以便使用正确的语法,以便在附近使用' SELECT picture_location FROM pictures WHERE user_id =' patient' AND default_pic'在第1行

1 个答案:

答案 0 :(得分:2)

嵌套select需要额外的括号层:

SELECT users.*, p.*,
       COALESCE((SELECT picture_location FROM pictures WHERE user_id = 'patient' AND default_pic = 1),
                (SELECT picture_location FROM pictures WHERE user_id = 'patient' ORDER BY id ASC LIMIT 1)) AS default_pic,
       pic.picture_location,
       MONTHNAME(users.registered_on) AS month_reg, YEAR(users.registered_on) AS year_reg
FROM users LEFT JOIN
     profile p
     ON p.profile_id = users.profile_id LEFT JOIN
     pictures pic
     ON pic.user_id = p.profile_id
WHERE users.pseudo = 'patient'
GROUP BY users.pseudo
ORDER BY pic.default_pic DESC
LIMIT 1;