the table
id string
------------
1 aaa
2 bbb
3 ccc
4 ddd
the query
(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 */
The query above will return 2 rows
since there are no id=5 and id=0.
How can I tell which queries are these 2 rows fetched from?
that is, num_row = 1
from 1st SELECT
, and num_row = 2
from 4th SELECT
You could try
(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)
You could add an extra constant column with a common alias:
(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)
use a second column to indicate from where the data comes from
(SELECT string, '1st query' as from_where FROM table WHERE ...)
UNION
(SELECT string, '2nd query' as from_whereFROM table WHERE ...)
You could try (inelegant as it is):
(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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.