答案 0 :(得分:1)
如果main_product_id
为NULL
:
SELECT *
FROM products
ORDER BY COALESCE(main_product_id, product_id) ASC,
(CASE WHEN main_product_id IS NULL THEN 0 ELSE 1 END) ASC,
product_id ASC
如果是''
:
SELECT *
FROM products
ORDER BY (CASE WHEN main_product_id = '' THEN product_id ELSE main_product_id END) ASC,
(CASE WHEN main_product_id = '' THEN 0 ELSE 1 END) ASC,
product_id ASC
订单Bys:
main_product_id
到"组"它们。product_id
排序(或任何您想要分类的子产品)答案 1 :(得分:0)
如果main_product_id
列值为空,那么我们可以将其视为main_product
,并且必须首先为该组提供。
<强>查询强>
select t.`product_id`, t.`main_product_id` from(
select `product_id`, `main_product_id`,
case when coalesce(trim(`mp_id`), '') = '' then `product_id`
else `main_product_id` end as `main_product_id_2`
from `your_table_name`
) t
order by `main_product_id_2`,
case when coalesce(trim(t.`main_product_id`), '') = '' then 1 else 2 end,
t.`product_id`;
<强> Find a demo here 强>