簡體   English   中英

PL SQL查詢以查找與列表中的所有值匹配的標識符列表

[英]PL SQL query to find a list of identifiers that matches all values in a list

假設我有一個包含以下數據的表:

SHELF_ID    PRODUCT_ID

shelf1      product1
shelf1      product2
shelf1      product3
shelf2      product1
shelf2      product2
shelf3      product1

我做了一個查詢'queryA'從另一個表返回

PRODUCT_ID

product1
product2

現在,我想在另一個查詢中使用“ queryA”來確定哪些貨架上至少具有“ queryA”中返回的所有產品

通過查看第一個表,您可以輕松地實現其架子1和架子2,但是如何在PL SQL中實現呢?

謝謝

我認為此查詢可以幫助您找到所需的內容:

基本上,我該怎么做:首先,我對每個貨架的product_id執行COUNT(DISTINCT ) ,然后檢查此計數是否等於或大於queryA表示貨架產品匹配的產品列表。 然后,如果我使用EXISTS()將產品與queryA不匹配,則我將其排除在外。 如果您還想查看不匹配的產品,則無需使用該過濾器。

--DROP TABLE shelves;
CREATE TABLE shelves
(
    SHELF_ID    VARCHAR(100)
    ,PRODUCT_ID VARCHAR(100)
);

INSERT INTO shelves
VALUES 
 ('shelf1','product1')
,('shelf1','product2')
,('shelf1','product3')
,('shelf2','product1')
,('shelf2','product2')
,('shelf3','product1');

--DROP TABLE queryA;

CREATE TABLE queryA
(
    PRODUCT_ID  VARCHAR(100)
);

INSERT INTO queryA VALUES ('product1'),('product2');

SELECT  * 
FROM shelves S
WHERE S.SHELF_ID IN (           
                    SELECT S.SHELF_ID
                            --,COUNT(DISTINCT S.PRODUCT_ID) PRODUCTCOUNT
                    FROM shelves S
                    GROUP BY S.SHELF_ID
                    HAVING COUNT(DISTINCT S.PRODUCT_ID)>=(SELECT COUNT(DISTINCT PRODUCT_ID) 
                                                            FROM queryA Q  )        
                    )
AND EXISTS (SELECT 1 
            FROM queryA Q
            WHERE S.PRODUCT_ID = Q.PRODUCT_ID
            )

您可以這樣做:

with products as (
      <your query here)
     )
select s.shelf_id
from shelves s join
     products p
     on s.product_id = p.product_id
group by s.shelf_id
having count(distinct s.product_id) = (select count(*) from products);

基本上,這會計算每個貨架上的火柴數量,並確保火柴數量是產品總數。

如果shelves沒有重復項,則可以使用having count(*) = . . .) having count(*) = . . .) having count(*) = . . .)

您可以執行此操作-無需聚合。 (除了頂部查詢中的SELECT DISTINCT ;如果您有一個附加表SHELVES (以SHELF_ID作為主鍵,那會更好),那么查詢可能會效率更高。)

select distinct shelf_id
from   shelves s
where  not exists (select product_id
                   from   queryA   -- Your existing query goes here
                   where  (s.shelf_id, product_id) 
                              not in (select shelf_id, product_id
                                      from   shelves
                                     )
                  )
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM