【问题标题】:Finding if a value exists in either table查找任一表中是否存在值
【发布时间】:2020-06-20 17:47:09
【问题描述】:

我有两个表,tblONE 和 tblTWO。我希望找出存储在Object.Name 中的值是否存在于其中任何一个中。我尝试了以下命令:

            SQLCmd.CommandText = "SELECT Count(ID) FROM tblONE WHERE ID = '" & Object.Name & "' UNION ALL SELECT Count(ID) FROM tblTWO WHERE ID = '" & Object.Name & "'"

但是,似乎只执行了第一个 SELECT。

【问题讨论】:

  • 请添加输入和预期输出
  • 是什么让你说只执行第一个?
  • 您确定两个表中都存在该值吗?
  • @zip 该值一次只存在一个表中

标签: sql vb.net ms-access


【解决方案1】:

另一种选择是,

'Any of them contains the record?

SELECT
    count(*)
FROM
    tblONE left join tblTwo on tblOne.Id = tblTwo.Id ' or just tblOne, tblTwo
Where
    tblOne.Id = @id OR tblTwo.Id =@id;



'Which tale contains the Id?

Select
   T.fromTable
From
(
    SELECT Id, "Table1" as fromTable FROM tblONE Where tblOne.Id = @id;
    UNION ALL
    SELECT Id, "Table2" as fromTable FROM tblTwo Where tblTwo.Id = @id;
) T ' if both tables has the row, you get multiple rows.

【讨论】:

  • 应该改为 FULL JOIN
【解决方案2】:

这是一种方法。它首先检查tblONE,然后检查tblTWO

SELECT IIF(Count(*) > 0, 1,
           (SELECT COUNT(*) FROM tblTWO WHERE ID = @ID) 
          )   
FROM tblONE
WHERE ID = @ID;

或者另一种选择:

select iif(t1.cnt1 + t2.cnt2 > 0, 1, 0) as is present
from (select count(*) as cnt1
      from tblONE
      where id = @id
     ) as t1,  -- have to use , because MS Access does not support CROSS JOIN
     (select count(*) as cnt2
      from tblTWO
      where id = @id
     ) as t2

【讨论】:

  • IIF 表达式可能无法直接用于聚合和/或子查询。访问可能会抱怨表达式应该在GROUP BY
  • @Parfait 。 . .我知道 MS Access 很挑剔。多少总是让我感到惊讶。我提供了另一个 Access 应该可以接受的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-26
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
相关资源
最近更新 更多