gpt4 book ai didi

mysql - 在 mySQL 的 WHERE 子句中使用 if/else 结果别名

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

我有一个包含两列的表格:

user_id, parent_id

我想运行以下查询:

SELECT 
(CASE WHEN parent_id IS NOT NULL
THEN parent_id
ELSE user_id
END) as id
FROM users
WHERE id in (43, 23, 11, 277);

但它不起作用 - 它说找不到 id 列。我怎样才能让它在 where 子句中使用那个 alias

最佳答案

coalesce 就是为此而生的。它返回第一个非 NULL 值。

SELECT coalesce(parent_id, user_id) as id
FROM users
WHERE coalesce(parent_id, user_id) in (43, 23, 11, 277);

并且由于您不能在 where 子句中使用别名 - 您必须使用它两次。

It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed.

关于mysql - 在 mySQL 的 WHERE 子句中使用 if/else 结果别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36177263/

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