好久沒有寫過Sql了,今天遇到一個問題,業務邏輯是:
一個商品可以屬于多個分類,在顯示商品詳情的時候,要求可以點擊“上一個”,“下一個” 查看和該商品在同一個分類下的其他商品,商品具有排序號。
這樣我就開始寫了第一個sql:
select top 1 ROW_NUMBER() over(order by p_order asc) as sno,* from dbo.App_Product
where p_id in
(
select p_id from App_ProductTypeRelation
where pt_id in
(
select pt_id from dbo.App_ProductTypeRelation where p_id=827
)
)
and p_order>(select p_order from App_Product where p_id=827)
但是當我再點擊“下一個”的時候,下一個商品所屬的分類和上一個的商品所屬的分類不同了(商品A:分類1,分類2,商品B:分類2,分類3)
這樣就會出現一個新的查詢結果,如果我再點擊“上一個”,就回不到剛才的商品了,暈了。
后來我就又寫了一個sql:
select * from
(
select top 1 ROW_NUMBER() over(order by p_order asc) as sno,* from dbo.App_Product
where p_id in
(
select p_id from App_ProductTypeRelation
where pt_id in
(
select pt_id from dbo.App_ProductTypeRelation where p_id=827
)
)
) as tb1
where sno>(select sno from tb1 where p_id=827)
這樣邏輯是對的,但是最后的where語句是不對的,就是where sno>(select sno from tb1 where p_id=827)中的tb1錯誤,我沒查到怎么解決問題,有高手請指教下。
后來我想到,可以把結果放到實際表中,用完刪了(過河拆橋)就好了,但是這樣的效率肯定不會好,
但是我也想不到怎么解決了,先這么著吧,日后再研究,呵呵,于是就有了下面的Sql:
if exists(select * from sys.objects where name='proc_GetAdjacentWithSameProType')
drop proc proc_GetAdjacentWithSameProType
go
create procedure proc_GetAdjacentWithSameProType
@p_id int=0,
@add_no int=0
as
declare @sql varchar(max)
if exists(select * from sys.objects where name='tb_temp')
drop table tb_temp
select ROW_NUMBER() over(order by p_order asc) as sno,* into tb_temp from dbo.App_Product
where p_id in
(
select p_id from App_ProductTypeRelation
where pt_id in
(
select pt_id from dbo.App_ProductTypeRelation where p_id=@p_id
)
)
select top 1 * from tb_temp where sno=((select sno from tb_temp where p_id=@p_id)+@add_no) order by sno asc
drop table tb_temp
go
exec proc_GetAdjacentWithSameProType 827,-5
用法是傳入當前商品的id,這個是固定不變的,點擊“下一個”或者“上一個”,永遠都是傳當前商品的id,
只是第二個參數:當前商品的上下第n個,
1:排序后往下數第一個,
2:排序后往下數第二個
....
-1:排序后往 上 數第一個
-2:排序后往 上 數第二個
.....
歡迎討論,增加知識
浙公網安備 33010602011771號