我有多个具有相同结构的表,用于存储文本短语。例如:
TABLE_1
id | text
1. | Hello
TABLE_2。
id | text
1. | Goodbye
TABLE_3。
id | text
1. | Hello
我希望看到包含文字的所有表格' Hello'所以我的查询很简单:
SELECT * FROM table_1, table_2, table_3 WHERE text ='Hello'
这告诉我是否'你好'存在但不存在。结果是:
id | text
1. | Hello
1. | Hello
有没有办法将表名放入结果集中,以便结果集看起来像这样?
id | text | table_name
1. | Hello | table_1
1. | Hello | table_3
提前致谢。
答案 0 :(得分:0)
SELECT *, 'table_1' as tablename FROM table_1 WHERE text ='Hello'
union all
SELECT *, 'table_2' as tablename FROM table_2 WHERE text ='Hello'
union all
SELECT *, 'table_3' as tablename FROM table_3 WHERE text ='Hello'
答案 1 :(得分:0)
试试这个
SELECT id, text, 'table_1' as tablename FROM table_1 WHERE text ='Hello'
union all
SELECT id, text, 'table_2' as tablename FROM table_2 WHERE text ='Hello'
union all
SELECT id, text, 'table_3' as tablename FROM table_3 WHERE text ='Hello'
答案 2 :(得分:0)
您想要的查询是union all
,而不是cross join
(您在from
子句中使用逗号得到的内容):
(select 'table_1' as which, t1.* from table_1 t1 where text ='Hello')
union all
(select 'table_2' as which, t2.* from table_2 t2 where text ='Hello')
union all
(select 'table_3' as which, t3.* from table_3 t3 where text ='Hello')