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
我在jargons表中有两行:
"id" "jargon" "description" "example" "rootJargonName" "rootJargon"
"2" "Child" "jd" "1" NULL 1
"1" Root" "sad" "1" NULL 0
为什么rootJargonName
会在null
行返回Root
而不是Child
?
我试图做的是,如果rootJargon
列不等于零,则选择列中指定的id不等于零的行。
答案 0 :(得分:3)
这可能是您看到的表别名问题,但您可以使用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
答案 1 :(得分:0)
为什么不试一个案例
像:
SELECT jargons.jargon as jargon,
jargons.description as description,
jargons.example as example,
CASE
WHEN (jargons.rootJargon == 0) THEN NULL
WHEN (jargons.rootJargon != 0) THEN
(SELECT jargon FROM jargons WHERE id = jargons.rootJargon)
END) AS 'rootJargonName'
FROM jargons
LEFT JOIN users ON users.id = jargons.addedBy
ORDER BY jargons.id DESC
我在语法的某处可能有错,但我认为这就是想法......