sql多条件order By并且加入置顶查询

需求分析

对于文章的管理中有一个置顶的需求,有一个按照时间排序的需求

设计

有一个置顶字段,专门去区分是否置顶的字段

难点

主要是怎么在sql中去将置顶的查出来,避免在业务代码中不必要的操作

主要的代码如下

  order by
        sa.sort Desc,
        // 重点
        CASE when sa.is_top = 1 THEN 0 ELSE 1 END

例子

<select id="getArticleInfos" resultMap="SitecontentArticleVO">
        SELECT st.article_id,
        st.article_title,
        st.publish_status,
        st.article_auther,
        st.update_date,
        st.create_date,
        /*适用站点json*/
        st.site_ids,
        /*审核状态*/
        st.check_status,
        st.article_source_type,
        st.is_top,
        st.sort,
        sac.article_category_name,
        sac.article_category_id,
        sacj.article_category_join_id
        FROM sitecontent_article st
        LEFT JOIN sitecontent_article_category_join sacj ON st.article_id = sacj.article_id
        LEFT JOIN sitecontent_article_category sac ON sacj.article_category_id = sac.article_category_id
        AND sac.is_del = 0
        <where>
            st.is_del = 0
            <if test="articleTitle != null and articleTitle != ''">
                AND st.article_title LIKE CONCAT( '%', #{articleTitle}, '%' )
            </if>
            <if test="articleCategoryIds != null">
                <foreach collection="articleCategoryIds" item="articleCategoryId"
                         open="AND sac.article_category_id IN (" separator="," close=")">
                    #{articleCategoryId}
                </foreach>
            </if>
            AND st.sys_inner_id = #{sysInnerId}
        </where>
        ORDER BY
        // 多条件order by
        CASE when st.is_top = 1 THEN 0 ELSE 1 END,
        st.create_date Desc,
        st.sort Desc
	 // 上面是错的注意顺序(先正常的一些排序在置顶)
  order by
        sa.sort Desc,
        CASE when sa.is_top = 1 THEN 0 ELSE 1 END
    </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值