我需要为这样的表编写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进行排序
答案 0 :(得分:2)
在这种情况下可以加入表格
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
答案 1 :(得分:0)
您可以使用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 )