简体   繁体   中英

MySQL need sub select or temporary table

I have 2 tables.

First table - products
products_id | quantity

1001,1
1002,2
1003,5
1004,4


Second table - products_catalog
products_catalog_id | products_id | partner_channel |active_status

1,1001,amazon,0
2,1001,ebay,0
3,1001,zalando,1
4,1002,amazon,1
5,1002,ebay,0
6,1003,amazon,1
7,1003,ebay,1
8,1003,zalando,1
9,1004,amazon,0
10,1004,ebay,0
11,1004,zalando,0

I want to have result of the products id with the condition if this product is not active in any partner channel (active_status = 0) I was using WHERE filter like this:

 SELECT p.products_id, pc.partner_channel, pc.active_status
    FROM products p
      LEFT  JOIN products_catalog pc ON  pc.products_id=p.products_id     
    WHERE pc.active_status='0' 
GROUP BY p.products_id ORDER BY  p.products_id;

WHERE active_status = 0, but the result was like this:

products_id | partner_channel | active_status
1001,amazon,0
1002,ebay,0
1004,amazon,0

I want to have result table products like this:

products_id | partner_channel | active_status
1004,amazon,0

Because in all partner_channel only this product id (1004) that have active_status = 0.

I think i missed something in the WHERE filter, but didn't have any clue about that. Maybe i should use sub query in when LEFT JOIN to products_catalog?

Any help will be appreciated.

Thanks.

use Having function.

SELECT p.products_id, ANY_VALUE(pc.partner_channel), ANY_VALUE(pc.active_status)
    FROM products p
      LEFT  JOIN products_catalog pc ON  pc.products_id=p.products_id   
 GROUP BY p.products_id
 having sum(pc.active_status)=0
  ORDER BY  p.products_id;

You have to place a condition in the HAVING clause like this:

SELECT products_id
FROM products_catalog
GROUP BY products_id 
HAVING SUM(active_status <> 0) = 0;

This query returns all products_id values having active_status = 0 for all partner_channel they are related to.

You can then use the above query as a derived table to join back to the original tables in order to get the rest of the fields:

SELECT p.*, pc.*
FROM products p
JOIN products_catalog pc ON pc.products_id=p.products_id  
JOIN (
    SELECT products_id
    FROM products_catalog
    GROUP BY products_id 
    HAVING SUM(active_status <> 0) = 0
) AS g ON g.products_id = p.products_id
ORDER BY p.products_id

Demo here

Try this Code

SELECT p.products_id, pc.partner_channel, pc.active_status
    FROM products p
      LEFT  JOIN products_catalog pc ON  pc.products_id=p.products_id     
    WHERE pc.active_status='0' 
GROUP BY p.products_id ORDER BY  p.products_id DESC;

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