【问题标题】:SQL query for finding all records with Table Name from multiple table用于从多个表中查找具有表名的所有记录的 SQL 查询
【发布时间】:2016-11-12 22:48:04
【问题描述】:

我有三个表 Table1、Table2、Table3。每个表都包含“评论”列。所以我想找到带有表名的记录。

例如:

表 1

Id         Comments

98         test

99         test

100        attach

表2

Id    Comments 

101   test

102   test

103   module

Table3

Id    Comments

111   test

112   test

113   exist

如果我说select * from Table1,Table2,Table3 where comments like '%test%'

结果应该是这样的:

Id      Table    Comments

98      Table1   test

99      Table1   test

101     Table2   test

102     Table2   test

111     Table3   test

112     Table3   test

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用UNION 查询:

    SELECT Id, 'Table1' AS Table, Comments
    FROM Table1
    WHERE Comments LIKE '%test%'
    UNION ALL
    SELECT Id, 'Table2' AS Table, Comments
    FROM Table2
    WHERE Comments LIKE '%test%'
    UNION ALL
    SELECT Id, 'Table3' AS Table, Comments
    FROM Table3
    WHERE Comments LIKE '%test%`
    

    【讨论】:

    • 会影响性能吗?实际上我有数千条记录,将近 10 万
    • 你的问题只写了一半。与什么相比,它会影响性能吗?如果您有替代方案,我们可以讨论性能。我看不到查询这三个表的方法。
    • 非常感谢蒂姆·比格莱森
    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多