SQL Select only rows with Minimum Value on a Column with Where Condition

佐手、 提交于 2019-12-01 04:22:48

You can start by selecting the minimum orderIndex of products that are not rejected like this:

SELECT productId, MIN(orderIndex)
FROM myTable
WHERE rejected = 0
GROUP BY productId;

Once you have that, you can join it with your original table on the condition that productId and minOrderIndex match:

SELECT m.id, m.productId, m.orderIndex
FROM myTable m
JOIN(
  SELECT productId, MIN(orderIndex) AS minOrderIndex
  FROM myTable
  WHERE rejected = 0
  GROUP BY productId) tmp ON tmp.productId = m.productId AND tmp.minOrderIndex = m.orderIndex;

My query makes the assumption that there are no duplicate (productId, orderIndex) pairs. As long as those don't exist, this will work just fine. Here is an SQL Fiddle example.

http://sqlfiddle.com/#!9/0196f/2

SELECT DISTINCT t.*
FROM table1 t
INNER JOIN (
SELECT productId, min(orderIndex) minIdx
FROM table1
WHERE rejected = 0
GROUP BY productId
  ) t1
ON t.productId = t1.productId
  AND t.orderIndex = t1.minIdx;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!