0

We have one table- 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

We need to find the max product_id of company where status is 1. For that we are using below query:

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;

Result:

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

This query is fine but we have an issue here.

  1. If value for must_show is 1 then we need show max_product id for company with must_show=1 and status=1.
  2. If value for must_show is 0 then we need show max_product id for company with status=1.

Expected Result:

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

Please give me the path to find a solution. Thanks!

Keyur Panchal
  • 1,382
  • 1
  • 10
  • 15

1 Answers1

0

Please try below query:

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;

Output:

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

company_id in (23,24)- I think you don't need this condition as there are only these two company_id present in your table as per your question data.

Keyur Panchal
  • 1,382
  • 1
  • 10
  • 15