2014-05-08 46 views
0

我有多個具有相同結構的表,用於存儲文本短語。對於實例:MySQL獲取表名作爲結果集的一部分

TABLE_1

id | text 
1. | Hello 

TABLE_2。

id | text 
1. | Goodbye 

table_3。

id | text 
1. | 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
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' 
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' 
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')