我们有一张表 - 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
这个查询没问题,但我们这里有一个问题。
- 如果
must_show 的值为 1
,那么我们需要显示 Must_show=1 且 status=1 的公司的 max_product ID。 - 如果
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/