根据另一张表中的数据过滤一张表中的数据

时间:2019-02-14 12:50:55

标签: sql sql-server

下面有两个表格。第一个表包含有关索引的信息。每个索引可以应用于一个或多个列。第二个表包含成对的集合:表名-列名。

我需要以某种方式获取表1的索引列表,并将其应用于表2的列。结果应包括过滤索引的所有列(请参见下面的结果表)。

#1
+---------------------------------------+
| Index name | Table name | Column name |
+---------------------------------------+
| Index_1    | Table_A    | Column_A_1  |
| Index_1    | Table_A    | Column_A_2  |
| Index_2    | Table_A    | Column_A_1  |
| Index_2    | Table_A    | Column_A_3  |
| Index_3    | Table_B    | Column_B_1  |
| Index_3    | Table_B    | Column_B_2  |
| Index_4    | Table_C    | Column_C_1  |
+---------------------------------------+

#2
+--------------------------+
| Table name | Column name |
+--------------------------+
| Table_A    | Column_A_2  |
| Table_B    | Column_B_1  |
+--------------------------+

Result:
+---------------------------------------+
| Index name | Table name | Column name |
+---------------------------------------+
| Index_1    | Table_A    | Column_A_1  |
| Index_1    | Table_A    | Column_A_2  |
| Index_3    | Table_B    | Column_B_1  |
| Index_3    | Table_B    | Column_B_2  |
+---------------------------------------+

我可以在不使用其他表的情况下对每个“ SELECT”操作执行此操作吗?如果可以,怎么办?

3 个答案:

答案 0 :(得分:0)

使用加入

select t1.* from table1 t1
join table2 t2
on t1.table_name=t2.table_name 
where t1.index_name in ('Index_1','Index_3') --- provide filter values

答案 1 :(得分:0)

EXISTS(半联接)更合适:

SELECT t1.* FROM table1 t1
WHERE EXISTS(
    SELECT * FROM table2 t2
        WHERE 
          t1.table_name=t2.table_name and t1.col_name=t2.col_name 
    )

答案 2 :(得分:0)

直接的JOINEXISTS不会删除它,因为如果至少其中一个行满足条件,则要显示一个集合(完整的索引)。

您需要首先确定哪些索引与另一个表匹配,然后显示其所有行:

;WITH IndexMatches AS
(
    SELECT DISTINCT
        I.IndexName
    FROM
        IndexTable AS I
        INNER JOIN ColumnsTable AS C ON
            C.TableName = I.TableName AND 
            C.ColumnName = I.ColumnName
)
SELECT
    I.*
FROM
    IndexTable AS I
    INNER JOIN IndexMatches AS M ON I.IndexName = M.IndexName
ORDER BY
    I.IndexName,
    I.TableName,
    I.ColumnName

或使用EXISTS

SELECT
    I.*
FROM
    IndexTable AS I
WHERE
    EXISTS (
        SELECT
            'at least one column match'
        FROM
            IndexTable AS I2
            INNER JOIN ColumnsTable AS C ON
                C.TableName = I2.TableName AND 
                C.ColumnName = I2.ColumnName
        WHERE
            I.IndexName = I2.IndexName)
ORDER BY
    I.IndexName,
    I.TableName,
    I.ColumnName