简体   繁体   English

SQL Server:交叉引用一个表中的多个列与另一个表中的多个列

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

I have 2 tables each containing 10 integer fields. 我有2个表,每个表包含10个整数字段。 I need to retrieve records from table2 where if one of the field values exists in any one of the columns in table1. 我需要从table2中检索记录,其中,如果table1的任一列中都存在字段值之一。 For example; 例如;

表示例

So if I have a variable containing 1 (the id of record in table1) I need sql which will retrieve records 2 & 3 from table 2 because either 3400 or 3500 exists in any of the cat fields in table 2. Hope that makes sense ;-) 因此,如果我有一个包含1(表1中记录的ID)的变量,则我需要sql,它将从表2中检索记录2和3,因为表2中的任何cat字段中都存在3400或3500。 -)

This might be the most efficient way, although a bit cumbersome to write: 这可能是最有效的方法,尽管编写起来有些麻烦:

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);

More importantly, though, your data structure is bad. 但是,更重要的是,您的数据结构不好。 Trying to use multiple columns as an array is usually a bad idea in SQL. 在SQL中,尝试将多个列用作数组通常不是一个好主意。 You want a junction table for each of these, where you have one row per id and category. 您需要每个表的联结表,其中每个ID和类别都有一行。 If you had such a data structure, the query would be much simpler to write and probably have much better performance. 如果您具有这样的数据结构,则查询将更容易编写并且可能具有更好的性能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM