MySql Query,选择大于

时间:2008-12-11 21:14:19

标签: sql mysql

我有一个名为faq_questions的表,其结构如下:

id int not_null auto_increment,
question varchar(255),
sort_order int

我正在尝试构建一个给定排序顺序的查询,选择具有下一个最高排序顺序的行。

示例:

id  question                sort_order
1   'This is question 1'    10
2   'This is question 2'    9
3   'This is another'       8
4   'This is another one'   5
5   'This is yet another'   4

好的,所以想象一下我传入5表示已知的排序顺序(id 4),我需要它返回id为3的行。由于无法保证sort_order是连续的,所以我不能只选择known_sort_order + 1 。

谢谢!

4 个答案:

答案 0 :(得分:24)

看起来太简单了,但它看起来像你需要的东西:

SELECT id,question FROM `questions` 
WHERE `sort_order` > sort_order_variable
ORDER BY sort_order ASC 
LIMIT 1

答案 1 :(得分:3)

SELECT * FROM table_name WHERE sort_order > 5 ORDER BY sort_order ASC LIMIT 1

答案 2 :(得分:2)

您可以使用TOPLIMIT

执行此操作
SELECT TOP 1 * FROM faq_questions
WHERE sort_order > 5
ORDER BY sort_order ASC

但这并不像

那样优雅或便携
SELECT *  
FROM faq_questions AS f1  
LEFT JOIN faq_questions AS f2  
    ON f1.sort_order > f2.sort_order  
    AND f2.sort_order = 5  
LEFT JOIN faq_questions AS f3  
    ON f3.sort_order BETWEEN f1.sort_order AND f2.sort_order  
WHERE f3.id IS NULL

答案 3 :(得分:0)

SELECT 
    id, question, sort_order
FROM faq_questions 
WHERE sort_order in 
(SELECT 
        MIN(sort_order) 
    FROM faq_questions 
    WHERE sort_order > ?);

这似乎有效

豫ICP备18024241号-1