posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

好久没有写过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:排序后往 上 数第二个

.....

欢迎讨论,增加知识

posted on   邢帅杰  阅读(296)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示