MySQL : How to get latest row on optional where clause using group by?

标签 mysql group-by subquery max

我们有一张表 - Product_table:

product_id | company_id | Status | must_show
1          | 23         | 1      | 1
2          | 23         | 1      | 1
3          | 23         | 1      | 0
4          | 23         | 1      | 0
5          | 23         | 0      | 0
6          | 24         | 1      | 0
7          | 24         | 1      | 0
8          | 24         | 1      | 0
9          | 24         | 1      | 0
10         | 24         | 0      | 0

我们需要找到状态为1的公司的最大product_id。为此,我们使用以下查询:

select * from Product_table as pt
JOIN (select MAX(product_id) as extid from Product_table) t1 ON t1.extid = 
pt.product_id where company_id in (23,24) and status = 1 group by company_id;

结果:

product_id| company_id| Status | must_show
4         | 23        | 1      | 0
9         | 24        | 0      | 0

这个查询没问题,但我们这里有一个问题。

  1. 如果 must_show 的值为 1,那么我们需要显示 Must_show=1 且 status=1 的公司的 max_product ID。
  2. 如果 must_show 的值为 0,那么我们需要显示 status=1 的公司的 max_product ID。

预期结果:

product_id| company_id| Status | must_show
    2     | 23        | 1      | 1
    9     | 24        | 1      | 0

请给我找到解决方案的路径。谢谢!

最佳答案

请尝试以下查询:

select max(t.product_id) product_id, t.company_id, t.status, t.must_show from
( select p1.product_id, p1.company_id, p1.status, p1.must_show
   from product_table p1
    where status = 1
     and must_show = (
      select max(must_show) from product_table p2 where p2.company_id = p1.company_id)
) as t group by t.company_id;

输出:

+------------+------------+--------+-----------+
| product_id | company_id | status | must_show |
+------------+------------+--------+-----------+
|          2 |         23 |      1 |         1 |
|          9 |         24 |      1 |         0 |
+------------+------------+--------+-----------+

company_id in (23,24)-我认为您不需要这个条件,因为根据您的问题数据,您的表中只存在这两个company_id。

关于MySQL : How to get latest row on optional where clause using group by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45058417/

相关文章:

mysql - 处理选择查询mysql上的空值

MySQL 如何使用通配符进行分组

python - 如何使用 Pandas 查找重复名称?

sql - PostgreSQL Where 计数条件

mysql - 多列子查询不适用于笛卡尔积

mysql - 如何在查询中设置MySQL变量

mysql - 使用Sqoop从mysql导入数据到Hadoop但是失败

mysql - sql 合并行成列(多对多的情况)

mysql - 如何在减法中使用子查询结果?

mysql - 从一个表中获取不在另一特定表中的所有 mysql 条目