简体   繁体   English

MySQL Group By 并根据条件从分组结果中返回不同的行

[英]MySQL Group By and return distinct rows from grouped result based on conditions

Background背景

  1. The table below shows the list of products across the three branches of a particular Phone Shop下表显示了特定电话店三个分店的产品列表
  2. "branch_id" with value "0" means the product is available in all branches值为“0”的“branch_id”表示该产品在所有分店都有售
  3. I would like to query for distinct products whose "branch_id = 2" - including those in a comma-separated string AND "branch_id = 0";我想查询“branch_id = 2”的不同产品 - 包括逗号分隔字符串和“branch_id = 0”中的产品;
  4. However, if the result returns more than one row with the same "product_name", in this case "Iphone X", the row with the "branch_id" not equal to "0" should be returned.但是,如果结果返回具有相同“product_name”的多行,在本例中为“Iphone X”,则应返回“branch_id”不等于“0”的行。

Products产品

id ID product_name产品名称 branch_id分支编号 price价格
1 1 Iphone X苹果手机 2,3 2,3 700 700
2 2 Iphone X苹果手机 0 0 500 500
3 3 Samsung S8三星S8 2 2 600 600
4 4 Ipad Pro掌上电脑 1 1 750 750
5 5 Apple watch苹果手表 0 0 550 550
6 6 Samsung S9三星S9 1,2 1,2 600 600

Expected Result预期结果

id ID product_name产品名称 branch_id分支编号 price价格
1 1 Iphone X苹果手机 2 2 700 700
3 3 Samsung S8三星S8 2 2 600 600
5 5 Apple watch苹果手表 0 0 550 550
6 6 Samsung S9三星S9 2 2 600 600

My Query - it doesn't return rows with branch_id = 0我的查询- 它不返回 branch_id = 0 的行

    select  id, product_name, branch_id, price FROM products 
    group by product_name,branch_id 
    having CASE 
       WHEN FIND_IN_SET(2, branch_id) > 0 THEN FIND_IN_SET(2, branch_id) > 0
       WHEN branch_id = 0 THEN branch_id = 0
       ELSE  branch_id = NULL 
    END

Use NOT EXISTS :使用NOT EXISTS

SELECT id, product_name, 
       CASE WHEN branch_id = '0' THEN branch_id ELSE '2' END branch_id, 
       price
FROM Products p1
WHERE FIND_IN_SET(2, p1.branch_id)
   OR (
     p1.branch_id = 0 
     AND NOT EXISTS (
       SELECT 1
       FROM Products p2
       WHERE p2.product_name = p1.product_name
         AND FIND_IN_SET(2, p2.branch_id)
     )
   );

Or, if your version of MySql is 8.0+ use ROW_NUMBER() window function:或者,如果您的 MySql 版本是 8.0+,请使用ROW_NUMBER()窗口函数:

SELECT id, product_name, 
       CASE WHEN branch_id = '0' THEN branch_id ELSE '2' END branch_id, 
       price
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY product_name ORDER BY FIND_IN_SET(2, branch_id) > 0 DESC) rn
  FROM Products
  WHERE FIND_IN_SET(2, branch_id) OR branch_id = '0'
) t
WHERE rn = 1

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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