3

我有这张桌子

id  fruit
---------
1   apple
2   banana <--
3   apple
4   apple
5   apple
6   apple
7   banana <----

8   apple
9   banana
10  apple

我想选择行,直到找到 2 个香蕉,比如

SELECT id FROM table_fruit UNTIL number_of_bananas = 2

所以结果是1,2,3,4,5,6,7

我怎么能做到这一点?

谢谢

我希望我能给所有回答我问题的人点赞。我已经测试了所有这些,它们都工作得很好(得到了预期的结果)。

尽管 Devart 和 ypercube 的答案对我来说似乎有点复杂且难以理解。

由于 AnandPhadke 是第一个提供有效解决方案的人,我会选择他的答案作为接受。

你们太棒了,谢谢!

4

5 回答 5

3

试试这个查询 -

SELECT id, fruit FROM (
  SELECT
    b.*, @b:=IF(b.fruit = 'banana', 1, 0) + @b AS banana_number
  FROM
    bananas b,
  (SELECT @b := 0) t
  ORDER BY id) t2
WHERE
  banana_number < 2 OR banana_number = 2 AND fruit = 'banana'

SQLFiddle 演示

于 2012-11-01T07:13:07.480 回答
2
select * from tables where id <=

(
select id from (
select id from tables where fruit='banana'
order by id limit 2) a order by id desc limit 1
)

SQLFIDDLE 演示

于 2012-11-01T07:13:33.257 回答
2

@Devart 的答案是完美的,但它是我们可以使用的另一种选择:

SELECT * FROM table_fruit WHERE id <=
(
    SELECT id FROM 
    (SELECT id FROM table_fruit WHERE fruit='banana' ORDER BY id LIMIT 2) a
    ORDER BY ID DESC LIMIT 1
);

或使用MAX

SELECT * FROM table_fruit WHERE id <=
(
    SELECT MAX(id) FROM 
    (SELECT id FROM table_fruit WHERE fruit='banana' ORDER BY id LIMIT 2) a
);

看到这个 SQLFiddle

于 2012-11-01T07:35:12.587 回答
1
select * from table_fruit where id <=
(
   select max(id) from
   (select id from table_fruit where fruit='banana' order by id limit 2) t
)
于 2012-11-01T07:24:32.830 回答
0

如果带有 的行少于 2 行'banana',这将返回表的所有行:

SELECT t.*
FROM table_fruit AS t
  JOIN
    ( SELECT MAX(id) AS id
      FROM
        ( SELECT id
          FROM table_fruit
          WHERE fruit = 'banana'
          ORDER BY id
            LIMIT 1 OFFSET 1
        ) AS lim2
    ) AS lim
    ON t.id <= lim.id
    OR lim.id IS NULL  ;
于 2012-11-01T07:38:01.513 回答