“分类”或“标记”SELECT查询

时间:2014-01-21 18:05:10

标签: mysql sql select

我有一个查询来自多个数据库的SELECT,其中'auth'= mad:

$result = mysql_query("SELECT * FROM test.1 WHERE auth = 'mad' LIMIT 1 
    UNION SELECT * FROM test.2 WHERE auth = 'mad' LIMIT 1 
    UNION SELECT * FROM test.3 WHERE auth = 'mad' LIMIT 1");

如何标记或分类从test.1获得的结果; test.2或test.3?

非常感谢。

3 个答案:

答案 0 :(得分:2)

将表名添加到结果中:

$result = mysql_query("SELECT *, 'test.1' FROM test.1 WHERE auth = 'mad' LIMIT 1 
                  UNION SELECT *, 'test.2' FROM test.2 WHERE auth = 'mad' LIMIT 1 
                  UNION SELECT *, 'test.3' FROM test.3 WHERE auth = 'mad' LIMIT 1");

答案 1 :(得分:0)

$result = mysql_query("SELECT *, 'test1' as Source FROM test.1 WHERE auth = 'mad' LIMIT 1 
UNION SELECT *, 'test2' FROM test.2 WHERE auth = 'mad' LIMIT 1 
UNION SELECT *, 'test3' FROM test.3 WHERE auth = 'mad' LIMIT 1");

答案 2 :(得分:0)

如果我理解正确,您只需添加一列。此外,最好使用union all而不是union,因为union也会花费额外的精力来消除重复项:

SELECT 1 as test, t1.* FROM test.1 t1 WHERE auth = 'mad' LIMIT 1 
    UNION ALL
SELECT 2 as test, t2.* FROM test.2 t2 WHERE auth = 'mad' LIMIT 1 
    UNION ALL
SELECT 3 as test, t3.* FROM test.3 t3 WHERE auth = 'mad' LIMIT 1;