簡體   English   中英

如果id是順序的話,MySql獲取行

[英]MySql get row if id is in sequence

如果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

謝謝 !

我能想到的一種方法是用戶用戶定義的變量來獲取行的等級,然后計算產品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

演示

解釋 首先查詢product_id的最小值賦值給變量@row ,然后按照升序為product_id 排序的每一行分配一個排名 ,一旦為每一行分配排名,則計算product_id的原始值之間的差異最后使用結果差異檢查差異為0得到那些行,因為它們遵循序列。 希望這是有道理的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM