如何判断哪个查询是使用UNION在MySQL语句中获取的数据

时间:2012-11-05 14:57:09

标签: mysql union

id    string
------------
1     aaa
2     bbb
3     ccc
4     ddd

查询

(SELECT string FROM table WHERE id > 1 ORDER BY id ASC LIMIT 1)    /* num_row = 1 */
UNION
(SELECT string FROM table WHERE id < 1 ORDER BY id DESC LIMIT 1)   /* null */
UNION
(SELECT string FROM table WHERE id > 4 ORDER BY id ASC LIMIT 1)    /* null */
UNION
(SELECT string FROM table WHERE id < 4 ORDER BY id DESC LIMIT 1)   /* num_row = 2 */

上面的查询将返回2 rows,因为没有id = 5且id = 0。

如何判断从这两行获取哪些查询?

即来自num_row = 1的{​​{1}}和来自1st SELECT的{​​{1}}

4 个答案:

答案 0 :(得分:2)

你可以尝试

(SELECT 1, string FROM table WHERE id > 1 ORDER BY id ASC LIMIT 1)   
UNION
(SELECT 2, string FROM table WHERE id < 1 ORDER BY id DESC LIMIT 1)  
UNION
(SELECT 3, string FROM table WHERE id > 4 ORDER BY id ASC LIMIT 1)   
UNION
(SELECT 4, string FROM table WHERE id < 4 ORDER BY id DESC LIMIT 1) 

答案 1 :(得分:0)

您可以使用常用别名添加额外的常量列:

(SELECT string, 'query_1' as query_num FROM table WHERE id > 1 ORDER BY id ASC LIMIT 1)    
UNION
(SELECT string, 'query_2' as query_num FROM table WHERE id < 1 ORDER BY id DESC LIMIT 1)
UNION
(SELECT string, 'query_3' as query_num FROM table WHERE id > 4 ORDER BY id ASC LIMIT 1)    
UNION
(SELECT string, 'query_4' as query_num FROM table WHERE id < 4 ORDER BY id DESC LIMIT 1)   

答案 2 :(得分:0)

使用第二列来指示数据来自何处

(SELECT string, '1st query' as from_where FROM table WHERE ...)
UNION
(SELECT string, '2nd query' as from_whereFROM table WHERE ...)

答案 3 :(得分:0)

你可以尝试(虽然不优雅):

(SELECT'1',string FROM table WHERE id&gt; 1 ORDER BY id ASC LIMIT 1)/ * num_row = 1 / 联盟 (SELECT'2',string FROM table WHERE id&lt; 1 ORDER BY id DESC LIMIT 1)/ null / 联盟 (SELECT'3',string FROM table WHERE id&gt; 4 ORDER BY id ASC LIMIT 1)/ null / 联盟 (SELECT'4',string FROM table WHERE id&lt; 4 ORDER BY id DESC LIMIT 1)/ num_row = 2