假设我有下表:
Table Files
id
size
在伪SQL中我需要这个处理之王:
select id
where
size < S1 and (limit this clause to N1 results)
or
size > S2 and (limit this clause to N2 results)
我知道Oracle定义rownum关键字来限制结果。
但就我而言,这不起作用。
这需要子选择吗?怎么样 ?可以使用多个子选择吗?
(这个SQL将由一个带有其他where子句的java程序生成,这使得使用subselects很困难。)
编辑: 我需要过滤的不仅仅是不同的尺寸。
解决
SELECT *
FROM Files
WHERE
someField = 'stuff'
AND
someOtherField = 'other stuff'
AND
(
SELECT id FROM Files WHERE size <= S1 AND ROWNUM <= N1
UNION
SELECT id FROM Files WHERE size > S2 AND ROWNUM <= N2
)
答案 0 :(得分:2)
使用UNION
:
SELECT *
FROM (
SELECT 'low' AS "which", "id"
FROM Files
WHERE "size" < S1)
WHERE ROWNUM <= N1
UNION
SELECT *
FROM (
SELECT 'high' AS "which", "id"
FROM Files
WHERE "size" >= S1)
WHERE ROWNUM <= N2
答案 1 :(得分:2)
假设条款独立(它们是您的例子),您可以使用union all
执行此操作:
select id
. . .
where size < S1 and rownum <= N1
union all
select id
. . .
where size > S1 and rownum <= N2
如果您不想重复from
子句(因为它很复杂),您可以使用CTE:
with t as (<blah blah blah>)
select *
from ((select id from t where size < S1 and rownum <= N1) union all
(select id from t where size > S1 and rownum <= N2)
) x
答案 2 :(得分:0)
使用此查询解决
SELECT *
FROM Files
WHERE
someField = 'stuff'
AND
someOtherField = 'other stuff'
AND
(
SELECT id FROM Files WHERE size <= N1 AND ROWNUM <= N1
UNION
SELECT id FROM Files WHERE size > N2 AND ROWNUM <= N2
)