0

桌子

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。

如何判断这 2 行是从哪些查询中提取的?

也就是说,num_row = 11st SELECTnum_row = 24th SELECT

4

4 回答 4

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) 
于 2012-11-05T14:59:07.117 回答
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)   
于 2012-11-05T14:59:13.927 回答
0

使用第二列来指示数据的来源

(SELECT string, '1st query' as from_where FROM table WHERE ...)
UNION
(SELECT string, '2nd query' as from_whereFROM table WHERE ...)
于 2012-11-05T14:59:52.607 回答
0

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

(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', string FROM table WHERE id > 4 ORDER BY id ASC LIMIT 1) / null / UNION (SELECT '4', string FROM table WHERE id < 4 ORDER BY id DESC LIMIT 1) / num_row = 2

于 2012-11-05T15:00:21.397 回答