MYSQL UNION - 使用mysql字符串函数?

时间:2012-03-23 14:31:12

标签: php mysql database

(SELECT field1 FROM Table1) UNION
(SELECT field1 FROM Table2);

这将从两个表中获取所有行。 有没有办法将表名添加到结果中,以便更容易查看记录的来源?例如,使用IF表1然后预先添加一个字符串来记录?

我目前获得的一个示例记录是

banana

我想

t1-banana or t2-banana

4 个答案:

答案 0 :(得分:4)

您可以将表名添加为第二列的值:

(SELECT field1, 'Table1' AS table_name FROM Table1) 
UNION
(SELECT field1, 'Table2' AS table_name FROM Table2);

答案 1 :(得分:2)

(SELECT field1, 't1' as table_name FROM Table1)
UNION    
(SELECT field1, 't2' as table_name FROM Table2);

答案 2 :(得分:2)

(SELECT CONCAT("t1-", field1) FROM Table1)
UNION
(SELECT CONCAT("t2-", field1) FROM Table2);

答案 3 :(得分:1)

(SELECT Concat(field1 , '-Table1') FROM Table1) UNION
(SELECT Concat(field1 , '-Table2') FROM Table2);