满足其他条件后,MySQL SELECT具有条件的最小行ID

时间:2018-09-19 10:16:47

标签: mysql

我有一个MySQL版本表。 在最后一次更改(更改为1)之后,我想获得最小的发布版本(已发布= 1)。 版本ID越高,就越新。

以下是我希望返回的一些示例:

+----+-----------+---------+
| id | published | changed |
+----+-----------+---------+
|  4 |         1 |       0 |
|  3 |         1 |       0 |
|  2 |         1 |       0 |
|  1 |         1 |       1 |    <- I want this row
+----+-----------+---------+

+----+-----------+---------+
| id | published | changed |
+----+-----------+---------+
|  5 |         0 |       0 |
|  4 |         0 |       1 |
|  3 |         1 |       0 |
|  2 |         1 |       0 |    <- I want this row
|  1 |         0 |       1 |    
+----+-----------+---------+

+----+-----------+---------+
| id | published | changed |
+----+-----------+---------+
|  4 |         1 |       0 |
|  3 |         1 |       0 |
|  2 |         1 |       0 |
|  1 |         1 |       0 |     No rows should be returned
+----+-----------+---------+


+----+-----------+---------+
| id | published | changed |
+----+-----------+---------+
|  4 |         0 |       0 |
|  3 |         0 |       0 |
|  2 |         0 |       1 |
|  1 |         0 |       0 |      No rows should be returned
+----+-----------+---------+

在MySQL中(没有任何外部php逻辑)处理此问题的更优雅的方法是什么?

预先感谢

1 个答案:

答案 0 :(得分:1)

  • 利用Correlated subquery,我们可以尝试确定至少一个ID(检查LIMIT 1的使用情况),该ID具有changed = 1,并且小于或等于行ID 。
  • 我们仅考虑具有published = 1的行。
  • 使用EXISTS过滤掉之前更改了ID的那些行。
  • 使用ORDER BY ASC LIMIT 1,我们将最终结果集限制为最小ID。

尝试以下查询:

SELECT t1.id, 
       t1.published, 
       t1.changed 
FROM your_table AS t1 
WHERE t1.published = 1 
  AND EXISTS ( 
               SELECT t2.id 
               FROM your_table AS t2 
               WHERE t2.id <= t1.id 
                 AND t2.changed = 1 
               LIMIT 1
             )
ORDER BY t1.id ASC 
LIMIT 1