0

我有 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
}
4

2 回答 2

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
于 2013-03-24T10:46:40.793 回答
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.
    }
}
于 2013-03-24T10:49:17.573 回答