如何在sql中使用select ... union ...时检测结果来自哪个表

时间:2015-04-13 18:48:42

标签: php mysql sql

    $result = mysql_query( "SELECT id FROM table1 UNION ALL SELECT id FROM table2;" , $link);

    while($end = mysql_fetch_assoc($result))
    {
    echo $end['id']; // how separate and specify output is frow which table ?   
    }

我有两个表(phpmyadmin),我想用1qeury搜索它们,然后我使用UNION来组合,现在我想分离输出并指定从哪个表是evry结果(行)? tnx

2 个答案:

答案 0 :(得分:2)

添加一个额外的列,指示它是哪个表:

SELECT "table1" which, id FROM table1
UNION ALL
SELECT "table2" which, id FROM table2

现在,您可以使用$end['which']来了解每行的哪个表格。

which不是表格中的列。它是查询中文字字符串的别名。

要在表格之间交替排序,您可以执行以下操作:

SELECT *
FROM (
    SELECT "table1" which, id FROM table1
    UNION ALL
    SELECT "table2" which, id FROM table2
) x
ORDER BY id, which

答案 1 :(得分:0)

使用别名:

$result = mysql_query( "SELECT id as table1_id FROM table1 
                        UNION ALL SELECT id FROM table2;" , $link);

然后:

echo $end['table1_id'];
echo $end['id'];