检查值是否在数据库中可用
check if value is available in DB or not
我有一个 table 具有架构:
id | name
1 | AD
2 | BC
我需要查询包含数据库中是否存在我提供的名称的报告。
name | isExists
AD | yes
BC | yes
CA | NO
名称 AD、BC、CA 应该是我给的,而不是在任何其他 table 中。
提前致谢
对值列表使用外部联接:
select v.name, t.name is not null as does_exist
from (
values ('AD'), ('BC'), ('CA')
) as v(name)
left join the_table t on t.name = v.name;
我建议 values()
生成包含搜索值的行,然后 exists
检查它们是否存在于 table:
select x.name,
exists (select 1 from mytable t where t.name = x.name) exists_in_table
from (values ('AD'), ('BC'), ('CA')) x(name)
与使用 join
s 的解决方案相反,这种方法的优点在于,当名称在源 table.[=14= 中出现一次时,它不会增加行数]
您可以使用左联接。例如:
with
params (name) as (
select 'AD' union all
select 'BD' union all
select 'CA'
),
select distinct params.name,
case when t.name is null then 'no' else 'yes' end as isExists
from params
left join t on t.name = params.name
我有一个 table 具有架构:
id | name
1 | AD
2 | BC
我需要查询包含数据库中是否存在我提供的名称的报告。
name | isExists
AD | yes
BC | yes
CA | NO
名称 AD、BC、CA 应该是我给的,而不是在任何其他 table 中。
提前致谢
对值列表使用外部联接:
select v.name, t.name is not null as does_exist
from (
values ('AD'), ('BC'), ('CA')
) as v(name)
left join the_table t on t.name = v.name;
我建议 values()
生成包含搜索值的行,然后 exists
检查它们是否存在于 table:
select x.name,
exists (select 1 from mytable t where t.name = x.name) exists_in_table
from (values ('AD'), ('BC'), ('CA')) x(name)
与使用 join
s 的解决方案相反,这种方法的优点在于,当名称在源 table.[=14= 中出现一次时,它不会增加行数]
您可以使用左联接。例如:
with
params (name) as (
select 'AD' union all
select 'BD' union all
select 'CA'
),
select distinct params.name,
case when t.name is null then 'no' else 'yes' end as isExists
from params
left join t on t.name = params.name