简体   繁体   中英

Which orders include both products 2 and 16? I tried several ways to solve this but it doesn't work.in psql

 SELECT  O.ORDER_ID,O.PRODUCT_ID,OD.ORDER_ID,OD.PRODUCT_ID
    FROM ORDER_DETAILS AS O , (SELECT PRODUCT_ID,ORDER_ID FROM ORDER_DETAILS) AS OD
                  WHERE O.PRODUCT_ID=2 AND OD.PRODUCT_ID=16;

Link to my db is: https://www.db-fiddle.com/f/xk4cpca66DHs3bsxyRjThV/0#&togetherjs=lAbjjIyuCh

You could filter the orders table with two exists conditions with correlated subqueries:

select o.*
from orders o
where 
    exists (
        select 1
        from order_details od
        where od.order_id = o.order_id and od.product_id = 2
    )
    and exists (
        select 1
        from order_details od
        where od.order_id = o.order_id and od.product_id = 16
    )

For performance, you want an index on order_details(order_id, product_id) .

In your DB fiddle , this returns 5 orders:

| order_id | customer_id | employee_id | order_date               | required_date            | shipped_date             | ship_via | freight | ship_name                  | ship_address        | ship_city      | ship_region | ship_postal_code | ship_country |
| -------- | ----------- | ----------- | ------------------------ | ------------------------ | ------------------------ | -------- | ------- | -------------------------- | ------------------- | -------------- | ----------- | ---------------- | ------------ |
| 10255    | RICSU       | 9           | 1996-07-12T00:00:00.000Z | 1996-08-09T00:00:00.000Z | 1996-07-15T00:00:00.000Z | 3        | 148.33  | Richter Supermarkt         | Starenweg 5         | Genève         |             | 1204             | Switzerland  |
| 10440    | SAVEA       | 4           | 1997-02-10T00:00:00.000Z | 1997-03-10T00:00:00.000Z | 1997-02-28T00:00:00.000Z | 2        | 86.53   | Save-a-lot Markets         | 187 Suffolk Ln.     | Boise          | ID          | 83720            | USA          |
| 10469    | WHITC       | 1           | 1997-03-10T00:00:00.000Z | 1997-04-07T00:00:00.000Z | 1997-03-14T00:00:00.000Z | 1        | 60.18   | White Clover Markets       | 1029 - 12th Ave. S. | Seattle        | WA          | 98124            | USA          |
| 11070    | LEHMS       | 2           | 1998-05-05T00:00:00.000Z | 1998-06-02T00:00:00.000Z |                          | 1        | 136     | Lehmanns Marktstand        | Magazinweg 7        | Frankfurt a.M. |             | 60528            | Germany      |
| 11077    | RATTC       | 1           | 1998-05-06T00:00:00.000Z | 1998-06-03T00:00:00.000Z |                          | 2        | 8.53    | Rattlesnake Canyon Grocery | 2817 Milton Dr.     | Albuquerque    | NM          | 87110            | USA          |

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM