如何知道UNION mysql查询中数据的来源

时间:2013-03-26 14:31:56

标签: php mysql sql union

我有这个mysql结果查询:

SELECT 
    * 
FROM 
   ( SELECT 
         * 
     FROM userA 
     UNION 
     SELECT 
         * 
     FROM userB 
     UNION 
     SELECT 
         * 
     FROM userC ) AS friendresult 
ORDER BY create_date DESC 
LIMIT 0 , 15

为了检索数据,我使用mysql_fetch_array,但我想知道我获取的每一行的来源。

提前致谢!

1 个答案:

答案 0 :(得分:3)

您可以选择一个新列,以指示数据来自哪个表。类似的东西:

SELECT * 
FROM 
( 
    SELECT *, 'userA' AS ComesFrom FROM userA 
    UNION ALL
    SELECT *, 'userB'              FROM userB 
    UNION ALL
    SELECT *, 'userC'              FROM userC
) AS friendresult 
ORDER BY create_date DESC 
LIMIT 0 , 15