如果product_id
按顺序排列,我们需要获取行。
表(产品)
product_id name
1 Parle
2 Coconut
3 Pizza
4 Colgate
5 Ice Cream
6 Nuts
8 Britania
9 Pepsi
需要输出
product_id name
1 Parle
2 Coconut
3 Pizza
4 Colgate
5 Ice Cream
6 Nuts
product_id - 8 and 9
没有得到,因为它没有顺序。
我的尝试
select distinct t1.*, t1.product_id, (select GROUP_CONCAT(t2.product_id) from product as t2) as p_id
from product t1
having FIND_IN_SET(t1.product_id+1, p_id)
输出
product_id name
1 Parle
2 Coconut
3 Pizza
4 Colgate
5 Ice Cream
在这次尝试中,我没有得到
product_id - 6
行。注意:我希望
MySql
中没有PHP
查询。
谢谢!
答案 0 :(得分:2)
我能想到的一种方法是用户定义的变量来获取行的等级,然后计算产品ID和等级的差异,并只选择差异= 0的行
select *
from(
select f.*,@row:= @row + 1 rank,
product_id - @row as diff
from product f,
(select @row:= 0) t
order by product_id
) t1
where diff = 0
或者如果你想选择最少的序列号。自动你可以把它写成
select *
from(
select f.*,@row:= @row + 1 rank,
product_id - @row as diff
from product f,
(select @row:= (select min(product_id) from product_sale_flag) a) t
order by product_id
) t1
where diff = -1
<强>解释强> First query将
product_id
的最小值分配给变量@row
,然后按product_id
按升序排序每行rank,为每一行分配排名,然后使用结果差异计算difference between the original value ofproduct_id
和lastly,它检查差异为0的位置,因为它们遵循序列。希望这是有道理的