如果id是顺序的话,MySql获取行

时间:2017-11-30 08:30:07

标签: php mysql

如果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查询。

谢谢!

1 个答案:

答案 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

Demo

或者如果你想选择最少的序列号。自动你可以把它写成

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

Demo

  

<强>解释   First queryproduct_id的最小值分配给变量@row,然后按product_id按升序排序每行rank,为每一行分配排名,然后使用结果差异计算difference between the original value of product_idlastly,它检查差异为0的位置,因为它们遵循序列。希望这是有道理的