Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL更改列(如果存在)_Sql_If Statement_Exists - Fatal编程技术网

SQL更改列(如果存在)

SQL更改列(如果存在),sql,if-statement,exists,Sql,If Statement,Exists,我有两张桌子。我正试图找到一种方法,在我的select查询中添加一列,该列返回true或false,以判断B中是否存在记录 Table A ID Title 1 A 2 B 3 C 4 D 5 E Table B ID Detail 3 foo 4 foo 4 bar 4 barfood 我想基本上“选择ID,标题,(存在?)从”返回 ID Title Exists 1

我有两张桌子。我正试图找到一种方法,在我的select查询中添加一列,该列返回true或false,以判断B中是否存在记录

Table A
ID     Title
1      A
2      B
3      C
4      D
5      E

Table B
ID     Detail
3      foo
4      foo
4      bar
4      barfood
我想基本上“选择ID,标题,(存在?)从”返回

ID     Title     Exists
1      A         False
2      B         False
3      C         True
4      D         True
5      E         False
表A的ID列将始终是唯一的。表B的ID列可以有零个、一个或多个与表A的ID相关的项。我不关心表B中的细节,我只想知道表B中是否至少有一条记录与表A的ID相关


我是SQL新手,我一直在寻找使用“if exists”或任何其他方法来解析它的方法,但我并没有真正找到我想要的东西

如果您离开联接表B,那么您将获得该信息

select a.id, a.title, 
case 
  when b.id is null then 'false'
  else 'true'
end
from a
left outer join b on a.id = b.id
group by a.id, a.title

如果要添加名为“Exists”temporary的列,请尝试以下操作

select a.id, a.title,case when a.id=b.id then 'True' else 'False' end as Exists       
from A a left outer join B b
on a.id = b.id
若您已经将Exists列添加到表中,那个么

select a.id, a.title,Exists=(case when a.id=b.id then 'True' else 'False')      
from A a left outer join B b
on a.id = b.id

可能有更有效的方法来实现这一点,但是将count和case语句结合起来就可以了:

select ID, Title, 
case when 
    (select count(1) from B where ID = A.ID) = 0 then 'False'
else 'True'
end as 'Exists'
from A

这无疑让我走上了正确的方向。我只需要添加一些独特的格式,这很完美。非常感谢。加上一个最早的答案和最酷的用户名的组合。