我有两种类型的用户,我将它们保存在两个不同的表中,我需要根据类型选择此用户的数据,这是我的查询:
SELECT user_data_bis.name, user_data_bis.surname,
user_data_bis.avatarimage, user.externalid, user.type // User's Data
FROM user_wall_likes
INNER JOIN user
ON user.internalid = user_wall_likes.owner
INNER JOIN (CASE user.type
WHEN user.type=0
THEN
(
SELECT name, owner, surname, avatarimage
FROM user_data
) user_data_bis
WHEN user.type=1
THEN
(
SELECT name, "" AS surname, owner, icon AS avatarimage
FROM university_data
WHERE isdelete=0
) user_data_bis
END)
ON user_data_bis.owner = user.internalid
WHERE user_wall_likes.wallid="619fd58836c9a826b9eafb4b4e81da24"
AND user_wall_likes.isdeleted=0
LIMIT 5
注意:当它说user_wall_likes.wallid="619fd58836c9a826b9eafb4b4e81da24
时,此varchar是我的数据库中一列的示例
但是当我执行此查询时,它会显示我:
#1064 - 您的SQL语法出错;检查与您的MySQL服务器版本相对应的手册,以便在' CASE user.type WHEN user.type = 0'附近使用正确的语法。在第6行
是否有一些方法可以根据这种情况user.type
中的变量从表中提取数据?
答案 0 :(得分:0)
您可以使用两个left join
和coalesce()
:
SELECT coalesce(ud.name, unv.name) as name,
coalesce(ud.surname, unv.surname) as surname,
coalesce(ud.avatarimage, unv.avatarimage) as avatarimage,
u.externalid, u.type -- User's Data
FROM user_wall_likes uld INNER JOIN
user u
ON u.internalid = uwl.owner LEFT JOIN
user_data ud
ON u.type = 0 AND ud.owner = u.internalid LEFT JOIN
university_data unv
ON u.type = 1 AND unv.owner = u.internalid
WHERE uwl.wallid = '619fd58836c9a826b9eafb4b4e81da24' AND uwl.isdeleted = 0
LIMIT 5;
请注意,您通常会ORDER BY
LIMIT
。