MySQL 按字段排序(column_name,子查询)
MySQL order by field(column_name, subquery)
我正在尝试获取数据以显示如下内容:
数据库模式:
category_id
parent_category
banana
fruit
apple
fruit
kiwi
fruit
cucumber
vegetable
celery
vegetable
pork
meat
beef
meat
chicken
meat
t-shirt
clothes
jeans
clothes
sweater
clothes
meat
food
fruit
food
vegetable
food
food
null
clothes
null
select * from category
order by
field(category_id, "banana") desc,
field(parent_category, (SELECT parent_category FROM category WHERE category_id = "banana")) desc
field(category_id, (select category_id from category where parent_category <> (SELECT parent_category FROM category WHERE category_id = "banana"))) desc
我的目标结果是按以下顺序显示:
香蕉第一,
其他种类的水果其次,
其他种类的食物第三,
最后穿衣服(所有其他不被视为食物的数据。)
第二级和第三级类别不必显示(肉类、水果、蔬菜、T 恤、牛仔裤、毛衣、食品、衣服)
也许是这样的:
SELECT * FROM category
WHERE
IF(parent_category='food',NULL,parent_category) IS NOT NULL
ORDER BY
CASE WHEN category_id='banana' THEN 1
WHEN parent_category='fruit' THEN 2
WHEN parent_category='clothes' THEN 99
ELSE 3 END;
在 ORDER BY
部分使用 CASE
表达式并过滤掉 parent_category
即 food
和 NULL
。结果将是这样的:
category_id
parent_category
banana
fruit
apple
fruit
kiwi
fruit
cucumber
vegetable
celery
vegetable
pork
meat
beef
meat
chicken
meat
t-shirt
clothes
jeans
clothes
sweater
clothes
我正在尝试获取数据以显示如下内容:
数据库模式:
category_id | parent_category |
---|---|
banana | fruit |
apple | fruit |
kiwi | fruit |
cucumber | vegetable |
celery | vegetable |
pork | meat |
beef | meat |
chicken | meat |
t-shirt | clothes |
jeans | clothes |
sweater | clothes |
meat | food |
fruit | food |
vegetable | food |
food | null |
clothes | null |
select * from category
order by
field(category_id, "banana") desc,
field(parent_category, (SELECT parent_category FROM category WHERE category_id = "banana")) desc
field(category_id, (select category_id from category where parent_category <> (SELECT parent_category FROM category WHERE category_id = "banana"))) desc
我的目标结果是按以下顺序显示:
香蕉第一,
其他种类的水果其次,
其他种类的食物第三,
最后穿衣服(所有其他不被视为食物的数据。)
第二级和第三级类别不必显示(肉类、水果、蔬菜、T 恤、牛仔裤、毛衣、食品、衣服)
也许是这样的:
SELECT * FROM category
WHERE
IF(parent_category='food',NULL,parent_category) IS NOT NULL
ORDER BY
CASE WHEN category_id='banana' THEN 1
WHEN parent_category='fruit' THEN 2
WHEN parent_category='clothes' THEN 99
ELSE 3 END;
在 ORDER BY
部分使用 CASE
表达式并过滤掉 parent_category
即 food
和 NULL
。结果将是这样的:
category_id | parent_category |
---|---|
banana | fruit |
apple | fruit |
kiwi | fruit |
cucumber | vegetable |
celery | vegetable |
pork | meat |
beef | meat |
chicken | meat |
t-shirt | clothes |
jeans | clothes |
sweater | clothes |