MySQL SELECT CASE WHEN 某事然后返回 null
表 who
wid--name-------father---mother
1----Daisy------David----Liza
2----Jenny------Joe------Judy
3----Meggy------Mike-----Manuela
4----Sarah------Joe------Judy
5----Chelsea----Bill-----Hillary
6----Cindy------David----Liza
7----Kelly------Joe------Judy
表 ages
aid---whoid---age
1-----1--------0
2-----2--------0
3-----3-------14
4-----4-------30
5-----5-------22
6-----6-------17
7-----1-------18
我想要该列表作为结果:
id---name------age
1----Meggy-----14
2----Cindy-----17
3----Daisy-----18 (Selected data that bigger than 0)
4----Chelsea---22
5----Sarah-----30
6----Jenny-----30 (Her age is 0 on ages table and Sarah's age with same father and mother)
7----Kelly-----30 (No data on ages table and Sarah's age with same father and mother)
我尝试了该查询:
SELECT
*,
(CASE age
WHEN '0' THEN (
SELECT age
FROM ages a
LEFT JOIN who w
ON w.wid = a.whoid
WHERE
w.father = father
AND
w.mother = mother
ORDER BY a.age DESC LIMIT 1
)
ELSE age
END
) AS newage
FROM who
LEFT JOIN ages
ON wid = whoid
ORDER BY newage
有什么问题吗?
Table who
wid--name-------father---mother
1----Daisy------David----Liza
2----Jenny------Joe------Judy
3----Meggy------Mike-----Manuela
4----Sarah------Joe------Judy
5----Chelsea----Bill-----Hillary
6----Cindy------David----Liza
7----Kelly------Joe------Judy
Table ages
aid---whoid---age
1-----1--------0
2-----2--------0
3-----3-------14
4-----4-------30
5-----5-------22
6-----6-------17
7-----1-------18
I want that list as a result:
id---name------age
1----Meggy-----14
2----Cindy-----17
3----Daisy-----18 (Selected data that bigger than 0)
4----Chelsea---22
5----Sarah-----30
6----Jenny-----30 (Her age is 0 on ages table and Sarah's age with same father and mother)
7----Kelly-----30 (No data on ages table and Sarah's age with same father and mother)
I tried that query:
SELECT
*,
(CASE age
WHEN '0' THEN (
SELECT age
FROM ages a
LEFT JOIN who w
ON w.wid = a.whoid
WHERE
w.father = father
AND
w.mother = mother
ORDER BY a.age DESC LIMIT 1
)
ELSE age
END
) AS newage
FROM who
LEFT JOIN ages
ON wid = whoid
ORDER BY newage
What's wrong with that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CASE … WHEN NULL
永远不会匹配任何内容,并且CASE NULL
将始终匹配ELSE
子句(在您的情况下返回age< /code>,即
NULL
)。使用此:
更新:
您还需要为表添加别名并在字段描述中使用别名:
CASE … WHEN NULL
will never match anything, andCASE NULL
will always match theELSE
clause (which in your case returnsage
, i. e.NULL
).Use this:
Update:
You also need to alias your tables and use the aliases in the field descriptions: