简体   繁体   English

Mysql 根据列值查询到select行

[英]Mysql query to select row based on column value

id ID date日期 is_available可用 product_id产品编号 product_recalled产品_召回
200 200 2019-10-10 2019-10-10 1 1个 123 123 yes是的
201 201 2020-07-10 2020-07-10 1 1个 123 123 no
202 202 2020-08-11 2020-08-11 0 0 123 123 yes是的
203 203 2021-07-10 2021-07-10 0 0 123 123 yes是的
204 204 2021-01-10 2021-01-10 0 0 123 123 no
205 205 2021-07-10 2021-07-10 0 0 124 124 yes是的
206 206 2021-01-10 2021-01-10 0 0 124 124 no

I need a query to select the max row based on the is_available column value sorted by latest date.我需要查询 select 基于按最新日期排序的 is_available 列值的最大行。 If is_available = 1 for the product, I should get the max row for with is_available = 0. Similarly, if a product only has is_available set to 0, I should get the max row for is_available = 0.如果产品的 is_available = 1,我应该获得 is_available = 0 的最大行。同样,如果产品仅将 is_available 设置为 0,我应该获得 is_available = 0 的最大行。

If a product id has both is_available =1 and is_available = 0, then I need to get the latest record with is_available = 1 which is the case for product id 123. For product id 124, there is no is_available = 1 so I need to get the latest record with is_available = 0.如果产品 ID 同时具有 is_available = 1 和 is_available = 0,那么我需要使用 is_available = 1 获取最新记录,产品 ID 123 就是这种情况。对于产品 ID 124,没有 is_available = 1 所以我需要获取 is_available = 0 的最新记录。

Eg: Scenario 1: If I specify the product_id = 123, then the expected output should be例如:场景 1:如果我指定 product_id = 123,那么预期的 output 应该是

id ID date日期 is_available可用 product_id产品编号 product_recalled产品_召回
201 201 2020-07-10 2020-07-10 1 1个 123 123 no

Scenario 2: If I specify the product_id = 124, then the expected output should be场景 2:如果我指定 product_id = 124,那么预期的 output 应该是

id ID date日期 is_available可用 product_id产品编号 product_recalled产品_召回
205 205 2021-07-10 2021-07-10 0 0 124 124 yes是的

I am not sure how to write a single query that would do this.我不确定如何编写可以执行此操作的单个查询。 Any help would be appreciated.任何帮助,将不胜感激。

WITH cte AS (
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY is_available DESC, date DESC) rn
  FROM test
)
SELECT *
FROM cte
WHERE rn = 1;

For to select the row for definite product use为至select行为定品用

SELECT *
FROM test
WHERE product_id = @product_id
ORDER BY is_available DESC, date DESC
LIMIT 1;

fiddle小提琴

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

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