gpt4 book ai didi

mysql - 我可以在 MySQL 中将条件放入 INNER JOIN 中吗?

转载 作者:行者123 更新时间:2023-11-29 19:12:05 25 4
gpt4 key购买 nike

我有两种类型的用户,我将它们保存在两个不同的表中,我需要根据类型选择该用户的数据,这是我的查询:

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 - 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 user.type WHEN user.type=0' at line 6

在这种情况下,是否有某种方法可以根据变量user.type从表中提取数据?

最佳答案

您可以使用两个left joincoalesce()来完成此操作:

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 BYLIMIT

关于mysql - 我可以在 MySQL 中将条件放入 INNER JOIN 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43004962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com