• select into tb_temp2 from tb_temp1 创建临时表实现上一个、下一个功能,使用完毕就删除临时表


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

    .....

    欢迎讨论,增加知识

  • 相关阅读:
    apache虚拟主机三种不同配置方式
    搭建http服务器及配置
    学校ftp服务器搭建
    vsftpd搭建使用
    nginx使用
    pxe+kickafkstart (二)转
    pxe批量网络装机
    bash中()使用特性
    ansible使用
    javascript 之 Object.defineProperty
  • 原文地址:https://www.cnblogs.com/xsj1989/p/4690293.html
Copyright © 2020-2023  润新知