0

我正在尝试next/previous从作为内部选择查询输出的结果集中获取记录。

这是我的查询:

select qs.*
from
(
    select
       tsk.id,
       tsk.request_id,
       tsk.category_group,
       tsk.category,
       tsk.hash_id 
    from
       user_tasks as usr 
       inner join
          unassigned_tasks as tsk 
          on usr.task_id = tsk.id 
    where
       usr.assigned_to = 12        
    AND 
        BINARY hash_id NOT IN ( SELECT hash_id FROM product_match_unmatches WHERE request_id = tsk.request_id AND auto_unmatched_by IS NOT NULL )
) as qs

WHERE qs.id = ( SELECT min(qs.id) FROM qs WHERE qs.id > 5181 )

如果内部查询返回结果集,其值为:

id
------
4179
4280
5181
6182
6283

然后我需要选择行id 6182

但看起来我必须在外部查询中再次提及内部查询。

还有其他方法吗?

4

1 回答 1

0

如果要选择内部查询的第二个到最后一个值,可以使用会话变量使用行编号:(编号取决于给定内部查询的行顺序)

set @rank = 0;
select
    tsk.id,
    tsk.request_id,
    tsk.category_group,
    tsk.category,
    tsk.hash_id
from (
        select
               tsk.id,
               tsk.request_id,
               tsk.category_group,
               tsk.category,
               tsk.hash_id,
               @rank := @rank + 1 as rank
            from
               user_tasks as usr 
               inner join
                  unassigned_tasks as tsk 
                  on usr.task_id = tsk.id 
            where
               usr.assigned_to = 12        
            AND 
                BINARY hash_id NOT IN ( SELECT hash_id FROM product_match_unmatches WHERE request_id = tsk.request_id AND auto_unmatched_by IS NOT NULL )
    )tbl
    where rank = @rank - 1;

您可以使用这样的查询获得所需的输出。:) 谢谢

于 2019-11-07T06:47:01.417 回答