SQL 服务器:交叉引用 1 table 中的多个列与另一个中的多个列

SQL Server: Cross Referencing multiple columns in 1 table with multiple columns in another

我有 2 个 table,每个包含 10 个整数字段。我需要从 table2 中检索记录,如果其中一个字段值存在于 table1 中的任何一列中。例如;

因此,如果我有一个包含 1 的变量(table1 中记录的 ID),我需要 sql,它将从 table2 中检索记录 2 和 3,因为 3400或 3500 存在于 table 中的任何 cat 字段中 2. 希望有意义 ;-)

WITH Table1Ids AS (
    SELECT ID, cat
    FROM Table1
         CROSS APPLY (
             VALUES (cat0), (cat1), (cat2), (cat3), (cat4)
         ) AS CA1(cat)
)
,Table2Ids AS (
    SELECT ID, cat
    FROM Table2
         CROSS APPLY (
             VALUES (cat0), (cat1), (cat2), (cat3), (cat4)
         ) AS CA1(cat)
)
,MatchingRecords AS (
    SELECT DISTINCT Table1Ids.ID AS Table1ID
                   ,Table2Ids.ID AS Table2ID
    FROM Table1Ids
         INNER JOIN Table2Ids
             ON Table2Ids.cat = Table1Ids.cat
)
SELECT Table2.*
FROM MatchingRecords
     INNER JOIN Table2
         ON Table2.ID = MatchingRecords.Table2ID
WHERE MatchingRecords.Table1ID = @TheIDYouAreLookingFor

这可能是最有效的方式,虽然写起来有点麻烦:

select t2.*
from table2 t2 
where exists (select 1 from table1 t1 where t2.cat1 in (t1.cat1, t1.cat2, t1.cat3, t1.cat4, t1.cat5) or
      exists (select 1 from table1 t1 where t2.cat2 in (t1.cat1, t1.cat2, t1.cat3, t1.cat4, t1.cat5) or
      exists (select 1 from table1 t1 where t2.cat3 in (t1.cat1, t1.cat2, t1.cat3, t1.cat4, t1.cat5) or
      exists (select 1 from table1 t1 where t2.cat5 in (t1.cat1, t1.cat2, t1.cat3, t1.cat4, t1.cat5) or
      exists (select 1 from table1 t1 where t2.cat6 in (t1.cat1, t1.cat2, t1.cat3, t1.cat4, t1.cat5);

但更重要的是,您的数据结构很糟糕。在 SQL 中尝试将多列用作数组通常不是一个好主意。您需要为其中的每一个创建一个联结 table,其中每个 ID 和类别各占一行。如果您有这样的数据结构,查询将更容易编写并且可能具有更好的性能。