我可以在SQL查询的select部分中使用exists函数吗?

时间:2012-03-29 14:41:32

标签: sql sybase

如果另一个表中的某行与第一个表中的某个键字段匹配,我需要运行一个查询,其中返回的字段之一为yes或no。 听起来像是一个加入的工作,除了第二个表是一对多,我只需要知道辅助表中是否有零行数或非零行数。

我可以这样做:

select t1.name, t1.id, (select count(1) from t2 where t1.id=t2.id) from t1 

但是如果可能的话,我想避免使用聚合子查询。 有人提到我可以使用exists()函数,但我没有看到如何在select字段中这样做。

顺便说一下,这是sybase 15。

4 个答案:

答案 0 :(得分:1)

您仍然可以执行JOIN,如下所示:

SELECT t1.name, t1.id, CASE WHEN t2.id IS NULL THEN 0 ELSE 1 END Existst2
FROM t1 
LEFT JOIN (SELECT id FROM t2 GROUP BY id) t2
ON t1.id = t2.id

答案 1 :(得分:0)

啊,我是从另一个堆栈溢出问题中得到的......

case when exists (select * from t2  where t1.id = t2.id) then 1 else 0  end 

答案 2 :(得分:0)

我只是在这里写下语法:

if exists (select * from table1 t1 inner join table1 t2 on t1.id = t2.id )
  select * from table2 

答案 3 :(得分:0)

此查询(使用所有数据库)

select t1.name, t1.id, 'Y' as HasChild
from t1 
where exists ( select 1 from t2 where t2.id = t1.id)
UNION
select t1.name, t1.id, 'N' as HasChild
from t1 
where NOT exists ( select 1 from t2 where t2.id = t1.id)
相关问题