[英]MySQL get first existing row with value OR get another ordered
我需要為表編寫mysql查詢,如下所示:
id | product_id | version | status
1 | 1 | 1 | 0
2 | 1 | 2 | 1
3 | 1 | 3 | 0
4 | 2 | 9 | 0
5 | 2 | 10 | 0
我需要獲取行(product_id是唯一的-每個product_id一個),但是:
-如果有product_id的狀態為1的行-抓住它
-它沒有描述的行獲取具有較高值或版本的行
所以對於描述的表結果應該是
id | product_id | version | status
2 | 1 | 2 | 1
5 | 2 | 10 | 0
我唯一的想法是獲取狀態為1的行,然后使用WHERE product_id NOT IN進行第二次查詢,然后按版本DESC和GROUP BY product_id進行排序
在這種情況下可以重新加入表格
SELECT p1.id, p1.product_id, p1.version, p1.status FROM products p1
LEFT OUTER JOIN (
SELECT MAX(version) AS version FROM products p2
) p2 ON p1.version = p2.version OR p1.status = 1
GROUP BY p1.product_id
您可以使用UNION
來實現
select myTable.id, product_id, version, status from myTable
where id in(select id from myTable where status > 0)
union
select myTable.id, product_id, version, status from myTable
join (select max(id) as id from myTable group by product_id)
as m on m.id = myTable.id
and product_id not in(select product_id from myTable where status > 0 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.