执行UNION选择获取数据来自哪个表

时间:2013-03-24 10:44:57

标签: mysql sql

我有3个表,它们具有完全相同的结构,例如:

id       name_col

我有这个问题:

$query = mysql_query("SELECT * FROM tbl_1 UNION SELECT * FROM tbl_2 UNION SELECT * FROM tbl_3");

现在:

while($row = mysql_fetch_array($query)){
    names .= $row['name_col'];
    // HERE HOW I COULD KNOW WHICH TABLE THIS DATA IS COMING FROM?
    // THIS NAME IS FROM tbl_1 OR tbl_2 OR tbl_3
}

2 个答案:

答案 0 :(得分:3)

您还可以添加一个自定义列,指定它所属的表的名称,例如

SELECT id, name_col, 'table1' tableName FROM table1
UNION
SELECT id, name_col, 'table2' tableName FROM table2
UNION
SELECT id, name_col, 'table3' tableName FROM table3

答案 1 :(得分:2)

您可以向子查询添加常量字段以对其进行索引,如下所示:

SQL:

SELECT *, 1 AS tbl ROM tbl_1 
UNION
SELECT *, 2 AS tbl FROM tbl_2 
UNION
SELECT *, 3 AS tbl FROM tbl_3

该额外字段的列名必须与子查询保持一致。

PHP:

while($row = mysql_fetch_array($query)){
    names .= $row['name_col'];
    switch ($row['tbl']){
         case 1: // tbl_1
         break;
         // etc.
    }
}