简体   繁体   English

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

[英]SQL query for finding all records with Table Name from multiple table

I have three table Table1,Table2,Table3. 我有三个表Table1,Table2,Table3。 Each table contains Column "Comments". 每个表都包含“注释”列。 So i want to find the records with table name. 所以我想找到带有表名的记录。

For Example: 例如:

Table1 表格1

Id         Comments

98         test

99         test

100        attach

Table2 表2

Id    Comments 

101   test

102   test

103   module

Table3 表3

Id    Comments

111   test

112   test

113   exist

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

Result should be like this : 结果应该是这样的:

Id      Table    Comments

98      Table1   test

99      Table1   test

101     Table2   test

102     Table2   test

111     Table3   test

112     Table3   test

You could use a UNION query: 您可以使用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%`

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

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