How to select the first N numbers from the Fibonacci series, or the Nth number from the series. This is done by using the SEQUENCE
storage engine and user variables.
Installing SEQUENCE
First, make sure that the SEQUENCE
storage engine is installed:
INSTALL SONAME 'ha_sequence';
Now you should see it installed by running:
SHOW PLUGINS LIKE 'sequence';
Select part of the Fibonacci series
To select the first 20 Fibonacci numbers:
SELECT
seq,
IF(seq = 0, 0, IF(seq = 1,
(@a := 0) + (@b := 1) + (@s := 0),
(@b := LAST_VALUE(LAST_VALUE(@s := (@a + @b), @a := @b), @s))
)) AS fibonacci
FROM seq_0_to_20;
Select one Fibonacci number
To select the 20th Fibonacci number:
SELECT * FROM (
SELECT
seq,
IF(seq = 0, 0, IF(seq = 1,
(@a := 0) + (@b := 1) + (@s := 0),
(@b := LAST_VALUE(LAST_VALUE(@s := (@a + @b), @a := @b), @s))
)) AS fibo
FROM seq_0_to_20
) s
LIMIT 1
OFFSET 20;
Reference
MariaDB KnowledgeBase: