在select语句中使用if exists()

时间:2016-04-10 07:45:55

标签: sql-server if-statement

我需要从table2中获取一个列,如果row存在,如果不将其返回为null。

如果我使用 的情况,它只获取table1和table2之间匹配的行。

如果我使用左外连接,它会从table1中获取所有行 条件table1.code =' A'

所以我需要,像这样的东西。

select table1.id,
if(row exist in table2 for query(table2.relation_type_id=55  and table1.id=table2.related_id)
then
return table2.parent_id
else
null
as parent_id,
table1.description,
from table1,table2 where table1.code='A'

2 个答案:

答案 0 :(得分:1)

SELECT table1.id, table2.parent_id as parent_id 
FROM table1 
LEFT OUTER JOIN table2 ON (table1.id = table2.related_id) 
WHERE table1.code = 'A';

根据评论编辑:

  SELECT table1.id, sub.parent_id as parent_id 
    FROM table1 
    LEFT OUTER JOIN (select parent_id,related_id from table2 where relation_type_id =55) sub ON (table1.id = sub.related_id) 
    WHERE table1.code = 'A';

答案 1 :(得分:0)

您是否尝试过子查询?

select table1.id,
(select table2.parent_id from table2 where table2.relation_type_id=55 and table2.related_id=table1.id) parent_id,
table1.description,
from table1 where table1.code='A'