检查 id 是否存在于多个表中 [英] check if id exists in multiple tables

查看:44
本文介绍了检查 id 是否存在于多个表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 SQL Server 2012.

I am using SQL Server 2012.

我有 5 张桌子(我们称它们为 A、B、C、D 和 E).每个表都包含一个名为 m_id 的列,其中包含 nvarchar(10) 的 id.

I have 5 tables (lets call them A, B, C, D & E). Each table contains a column called m_id, which contains id's that are nvarchar(10).

我目前运行以下查询 5 次(更改表名).查看表中是否包含id.

I currently run the query below 5 times (changing the table name). To see if the table contains the id.

select m_id from A where m_id = 'some_id'

基本上我想知道 id 是否是 5 个表中的任何一个,如果是,则返回 1 否则,如果 5 个表中的任何一个中都不存在,则返回 0.

Basically I want to know if the id is any of the 5 tables, if so return 1 else if does not exist in any of the 5 tables return 0.

我觉得我目前的做法非常低效.有一个更好的方法吗?

I feel the current way I'm doing this is very inefficient. Is there a better way to do this?

推荐答案

您可以使用 UNION(预先删除重复项)或 UNION ALL:

You could use UNION(removes duplicates beforehand) or UNION ALL:

SELECT CASE WHEN EXISTS 
  ( SELECT 1 FROM ( SELECT m_id FROM  A 
                    UNION 
                    SELECT m_id FROM  B 
                    UNION 
                    SELECT m_id FROM  C 
                    UNION 
                    SELECT m_id FROM  D 
                    UNION 
                    SELECT m_id FROM  E ) All 
    WHERE  All.m_id = 'some_id') 
THEN 1 ELSE 0 END AS ContainsID 

这篇关于检查 id 是否存在于多个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆