繁体   English   中英

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

[英]How to tell which query is the data fetched from in a MySQL statement with 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 = 11st SELECT ,和num_row = 24th SELECT

你可以试试

(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) 

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

(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)   

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

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

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

(SELECT'1',string FROM table WHERE id> 1 ORDER BY id ASC LIMIT 1)/ * num_row = 1 / UNION( SELECT'2 ',string FROM table WHERE id <1 ORDER BY id DESC LIMIT 1)/ null / UNION(SELECT'3',字符串FROM表WHERE id> 4 ORDER BY id ASC LIMIT 1)/ null / UNION( SELECT'4 ',字符串FROM表WHERE id <4 ORDER BY id DESC LIMIT 1)/ num_row = 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM