简体   繁体   中英

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

I have 2 tables each containing 10 integer fields. I need to retrieve records from table2 where if one of the field values exists in any one of the columns in 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 ;-)

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. You want a junction table for each of these, where you have one row per id and category. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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