[英]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.