【问题标题】:mysql query using order by clause使用 order by 子句的 mysql 查询
【发布时间】:2014-06-05 02:06:24
【问题描述】:

我有字段存储是/否值,名称为 SelectionFavorite

我想获取像

这样的记录

首先包含SelectionFavorite值yes的所有记录和其他剩余记录

我做了一些类似的查询

SELECT p.Id,
       p.NameLatin,
       p.NameEnglish,
       cm.DescriptionEnglish,
       p.SelectionFavorite,
       p.SelectionGarden,
       p.SelectionPerso1,
       SelectionPerso2,
       SelectionPerso3
FROM plant p
INNER JOIN CategoryMain cm ON p.CategoryMain = cm.id
ORDER BY (p.SelectionFavorite=yes)

但只返回那些具有 yes 值的记录。

我想要这种类型的结果

Id 名称拉丁名称英文描述English SelectionFavorite .....

1 name1 eng1 desc1 yes yes yes no no

2 name2 eng2 desc2 yes yes yes no no

3 name3 eng3 desc3 yes yes yes no no

4 name4 eng4 desc4 yes yes yes no no

5 name5 eng5 desc5 yes yes yes no no

6 name6 eng6 desc1 no yes yes no no

7 name7 eng7 desc2 no yes yes no no

8 name8 eng8 desc3 no yes yes no no

9 name9 eng9 desc4 no yes yes no no

如何解决这个问题?

【问题讨论】:

  • 你能提供一些样本数据和想要的结果吗?

标签: mysql sql


【解决方案1】:

order by 子句将“是”值放在首位,然后是其他值:

ORDER BY (p.SelectionFavorite = 'yes') desc

您的查询不应过滤掉任何内容,尽管它会将非是值放在首位。

【讨论】:

  • 这看起来应该对我有用。我在 sqlfiddle 上做了一个快速示例,演示了应该发生的事情,而不需要进一步复杂化。 sqlfiddle.com/#!2/18fbb/4/0
【解决方案2】:

您可以使用这样的解决方案:

SELECT p.Id,
   p.NameLatin,
   p.NameEnglish,
   cm.DescriptionEnglish,
   p.SelectionFavorite,
   p.SelectionGarden,
   p.SelectionPerso1,
   SelectionPerso2,
   SelectionPerso3
FROM plant p
INNER JOIN CategoryMain cm ON p.CategoryMain = cm.id
ORDER BY CASE p.SelectionFavorite WHEN 'yes' THEN 1 ELSE  2 END;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    相关资源
    最近更新 更多