如何编写MYSQL函数以基于列的连续值(int,日期或时间戳记)返回记录。
例如:
// id连续记录4次,id:5,6,7,8
InvoiceRecyclerViewAdapter adapter = new InvoiceRecyclerViewAdapter(
this ,cart_productslist, new InvoiceRecyclerViewAdapter.OnQuantityChangeListener(){
@Override
void onQuantityChange( float difference ){
total += difference;
total_textview.setText("Rs "+ total);
}
} );
//日期连续4个日期记录
select * from employee where consecutive(id,4);
///只要id是连续的,就全部返回。
select * from employee where consecutive(date,4);
答案 0 :(得分:1)
在ISO标准的SQL 2003或更高版本中,我将结合使用ROW_NUMBER() OVER ( ORDER BY id )
和OFFSET
。该查询可在SQL Server 2012或更高版本,Oracle 10g或更高版本,PostgreSQL或MySQL 8 or later中运行-但几乎没有人运行MySQL 8 ...
第一个示例:
SELECT
employee.*
FROM
(
SELECT
id,
ROW_NUMBER() OVER ( ORDER BY id ) AS rn
FROM
employee
) AS sq
INNER JOIN employee ON employee.id = sq.id
ORDER BY
id
OFFSET
0 ROWS FETCH 4
幸运的是,MySQL使您可以递增变量并在SELECT
中对其他不纯表达式进行评估,就好像它们是迭代求值的(这是在“ SQL思维方式”中做出的错误假设。 “)。
So here's a trick to get a row-rank in MySQL, using an inline initialization:
SELECT
*,
@rank := @rank + 1 AS rn
FROM
employee,
( SELECT @rank := 0 )
ORDER BY
employee.id
因此我们可以将其用作子查询:
SELECT
employee.*
FROM
(
SELECT
employee.id,
@rank := @rank + 1 AS rn
FROM
employee,
( SELECT @rank := 0 )
ORDER BY
employee.id
) AS sq
INNER JOIN employee ON employee.id = sq.id
ORDER BY
id
LIMIT
4 OFFSET 0