gpt4 book ai didi

mysql - IF 语句中的 SELECT

转载 作者:太空宇宙 更新时间:2023-11-03 11:55:29 25 4
gpt4 key购买 nike

SELECT jargons.jargon as jargon, 
jargons.description as description,
jargons.example as example,
IF(jargons.rootJargon != 0, (SELECT jargon FROM jargons WHERE id = jargons.rootJargon), NULL) as rootJargonName
FROM jargons
LEFT JOIN users ON users.id = jargons.addedBy
ORDER BY jargons.id DESC

我在行话表中有两行:

"id"  "jargon"  "description"   "example"   "rootJargonName"    "rootJargon"
"2" "Child" "jd" "1" NULL 1
"1" Root" "sad" "1" NULL 0

为什么 rootJargonNameChild 行上返回 null 而不是 Root

我试图做的是,如果 rootJargon 列不等于零,则选择列中指定的 ID 不等于零的行。

最佳答案

这可能是您看到的表别名问题,但您可以使用 LEFT JOIN 重写它:

SELECT      J.jargon as jargon, 
J.description as description,
J.example as example,
R.jargon As rootJargonName
FROM jargons as J
LEFT JOIN users as U ON U.id = J.addedBy
LEFT JOIN jargons as R ON J.rootJargon = R.ID
ORDER BY J.id DESC

如果您想保留 IF() 函数,可以使用以下方法,但我建议使用 LEFT JOIN

SELECT      J.jargon as jargon, 
J.description as description,
J.example as example,
IF(J.rootJargon != 0, (SELECT jargon FROM jargons as R WHERE R.id = J.rootJargon), NULL) as rootJargonName
FROM jargons as J
LEFT JOIN users as U ON U.id = J.addedBy
ORDER BY J.id DESC

关于mysql - IF 语句中的 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129902/

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