[英]Oracle Query - Filter and Limit in two tables using JOIN
I am facing an issue in Oracle Query to achieve the following use case,我在 Oracle 查询中遇到问题以实现以下用例,
Consider I have two tables:考虑我有两张桌子:
Table 1 : product
productId - Integer - primaryKey
productName - Varchar
Table 2 : product_sequence
productId - Integer - primaryKey
sequenceId - Integer - primaryKey
orderId - Integer
orderName - Varchar
product table has 1000 entries and product_sequence table has 10K entries product 表有 1000 个条目,product_sequence 表有 10K 个条目
Requirement :要求:
Query (tried) :查询(已尝试) :
SELECT
p.productId, p.productName, ps.orderId, ps.orderName,
COUNT(distinct p.productId) OVER () AS TOTAL
FROM (
select *
from product
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY
) p
JOIN product_sequence ps on p.productId=ps.productId
WHERE ps.orderId IN ('12','13','14');
NOTE: the above query will work in Oracle, But the issue is注意:上述查询将在 Oracle 中工作,但问题是
Expected : Return 100 entries from 'product' table with mapped entries in the 'product_sequence' table预期:从 'product' 表返回 100 个条目,并在 'product_sequence' 表中映射条目
Actual : It first LIMITS 100 entries in product and then filter the orderId so the number of entries returned is reduced from 100 to lesser number I agree my query is not correct : It first LIMIT by 100 in 'product' table in subquery and then goes for filter in second table which reduces the count实际:它首先在产品中限制 100 个条目,然后过滤 orderId,因此返回的条目数从 100 减少到更少我同意我的查询不正确:它首先在子查询中的“产品”表中限制 100,然后继续用于第二个表中的过滤器,以减少计数
Could some one help me with the query for this please?有人可以帮我查询这个吗? Anyhelp is appreciated.
任何帮助表示赞赏。
If my question is not clear, Let me know, I can explain with more info.如果我的问题不清楚,请告诉我,我可以解释更多信息。
Try to move the OFFSET
and FETCH
clauses to the outer query, something like this:尝试将
OFFSET
和FETCH
子句移至外部查询,如下所示:
SELECT q.productId, q.productName, q.orderId, q.orderName,
COUNT(distinct p.productId) OVER () AS TOTAL
FROM ( SELECT * FROM product p JOIN product_sequence ps ON p.productId = ps.productId
WHERE ps.orderId IN ('12','13','14') ) q
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY
To get 100 rows per page "after filtering" you'll need to find all the productid
values first, then process the main query.要在“过滤后”获得每页 100 行,您需要先找到所有
productid
值,然后处理主查询。
For example:例如:
select
p.productid, p.productname, ps.orderid, ps.orderName,
count(distinct p.productid) over() as total
from product p
join product_sequence ps on p.productid = ps.productid
where ps.orderid in ('12','13','14')
and p.productid in (
select *
from (
select distinct p.productid
from product p
join product_sequence ps on p.productid = ps.productid
where p.productname like '%theremin%' -- filter #1
and ps.orderid in ('12','13','14') -- filter #2
) x
order by productid
offset 300 rows -- get the 4th page
fetch first 100 rows only -- page size set to 100 rows
)
See example at db<>fiddle .请参阅db<>fiddle中的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.