gpt4 book ai didi

SQL:带有 "exists"的 case-when 语句

转载 作者:行者123 更新时间:2023-12-04 21:09:10 24 4
gpt4 key购买 nike

我希望能够设置添加一个字段来回答问题“对于此记录中的值,该值是否满足另一个表中的某些条件?”。我想我会尝试一个 case-whenexists ,但 Teradata(我的 dbms)不喜欢它。有什么建议吗?

select foo,
(case when exists (select x.foo
from somedb x
where x.bar > 0)
then '1' else '0' end) as MyFlag

from mydb

最佳答案

对此可能有不止一种解决方案。有时两个表之间存在关系。然后我做一个 JOIN 并在 WHERE 子句中处理它。我不知道 Teradata,但在 Oracle 中我也可以做这样的事情。

SELECT foo 
FROM mydb
WHERE (select count(*) from somedb where x.bar > 0) > 0

或者更喜欢你的代码
select foo,  
(case when (select count(*)
from somedb x
where x.bar > 0) > 0
then '1' else '0') as MyFlag
from mydb

我知道只在 WHERE 子句中使用 EXISTS“我只想要下面的 SELECT 给我一些东西的那些行”。这仅在一张表和另一张表之间存在某种联系时才有意义。
select id,foo from mydb y
where exists (select x.id from somedb x where x.id = y.id)

关于SQL:带有 "exists"的 case-when 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3353987/

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