我有这张桌子
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是第一个提供有效解决方案的人,我会选择接受他的答案。
你们真棒,谢谢!
答案 0 :(得分: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'
答案 1 :(得分: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
)
答案 2 :(得分:2)
@Devart's answer是完美的,但它是我们可以使用的另一种选择:
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
);
答案 3 :(得分: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
)
答案 4 :(得分:0)
如果'banana'
行少于2行,则会返回表格的所有行:
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 ;