You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对去重后的MySQL分类数据按多字段排序并忽略NULL值?

分类列表查询排序需求

需要获取按siteId去重后的分类列表,并按指定顺序排列。

数据表结构

categories
=============
categoryId,
siteId,
parentId,
title,
active

当前使用的SQL语句

SELECT
parentTitle,
childTitle,
subChildTitle
from (
    select      subChild.categoryId as parentCategoryId,
                child.categoryId as childCategoryId,
                parent.categoryId as subChildCategoryId,
                subChild.title as subChildTitle,
                child.title as childTitle,
                parent.title as parentTitle
    from        categories subChild
    left join   categories child on child.categoryId = subChild.parentId 
    left join   categories parent on parent.categoryId = child.parentId 
    where subChild.siteId in (1,2,3)
    and subChild.active = 'Y'
    ) as categories 
group by parentTitle, childTitle, subChildTitle
order by COALESCE(parentTitle, childTitle, subChildTitle);

当前查询结果

NULL       NULL         Appliance   
NULL       Appliance    Dishwasher  
NULL       Appliance    Dryer
Appliance  Dishwasher   Not Cleaning Correctly
Appliance  Dryer        Not Cleaning

目标排序结果(优先实现)

NULL       NULL         Appliance   
NULL       Appliance    Dishwasher  
Appliance  Dishwasher   Not Cleaning Correctly
NULL       Appliance    Dryer
Appliance  Dryer        Not Cleaning

更优目标结果(可选)

Appliance     NULL        NULL
Appliance     Dishwasher  NULL
Appliance     Dishwasher  Not Cleaning Correctly
Appliance     Dryer       NULL
Appliance     Dryer       Not Cleaning

内容的提问来源于stack exchange,提问作者danjfoley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:24:41