用于从多个表中查找具有表名的所有记录的SQL查询

时间:2016-07-11 04:44:45

标签: sql sql-server

我有三个表Table1,Table2,Table3。每个表都包含Column" Comments"。所以我想找到带有表名的记录。

例如:

表1

Id         Comments

98         test

99         test

100        attach

表2

Id    Comments 

101   test

102   test

103   module

表3

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

1 个答案:

答案 0 :(得分:2)

您可以使用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%`