2017-07-12 6 views
0

我々は1卓上Product_tableを持っている:MySQL:オプションのwhere節で最新の行を取得するにはどうすればいいですか?

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 

我々はstatus is 1会社のmax 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 is 1の場合、must_show = 1およびstatus = 1の会社にはmax_product idを表示する必要があります。
  2. must_show is 0の値の場合、status = 1の会社の場合、show max_product idが必要です。

期待される結果:

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

は私に解決策を見つけるためのパスを教えてください。ありがとう!

+0

'product_id = 10、status is 0'の場合、なぜそれを表示したいのですか?あなたは、「状態が1である会社の最大product_idを見つける必要がある」と言いました。そして、なぜ期待される結果にproduct_id = 10のレコードがあるのですか? –

+0

はい、must_showに1が入っている場合は、そのレコードを表示する必要があります。実際に優先順位を変更します。 –

+0

私は 'product_id = 10'について話しています。そのレコードの 'status'と' must_show'は両方とも0です。 –

答えて

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)を - 私はあなたのテーブルでのみこれらの2つのcompany_idが存在しているとして、あなたはこの条件を必要としないと思いますあなたの質問データごとに。

+0

ありがとう!わかった。これは、ページの速度を低下させる可能性がありますが動作します。 –

関連する問題