MySQL按两列顺序再次订购结果

时间:2022-09-18 13:17:51

My table has two columns which I need to sort by:

我的表有两列我需要排序:

content title

Only some rows have data in the content column but all have some in the title column. I need to sort these rows so that those with data in the content column are first. I can do this by:

只有一些行在内容列中有数据,但在title列中都有一些。我需要对这些行进行排序,以便那些内容列中包含数据的行是第一个。我可以这样做:

ORDER BY content DESC, title ASC

However, those top rows returned because of their content column also need to be sorted alphabetically by their title (not by their content which I assume is happening).

但是,由于其内容列而返回的那些顶行也需要按其标题按字母顺序排序(而不是我假设发生的内容)。

Ideas? Thanks.

想法?谢谢。

Update:

更新:

Should have noted that title is a VARCHAR and content is TEXT. So arbitary text. content column is empty if no content, not NULL.

应该注意到标题是VARCHAR,内容是TEXT。所以仲裁文本。如果没有内容,则content列为空,而不是NULL。

So for example:

例如:

`title`     `content`
title a
title b      this has content
title c      so does this
title d

The order would be:

订单将是:

title c
title b
title a
title d

3 个解决方案

#1


6  

If I understand what you need, try this:

如果我了解您的需求,请尝试以下方法:

SELECT * FROM your_table
ORDER BY
  CASE
    WHEN content IS NULL THEN 1
    ELSE 0
  END
  ,content,title

#2


1  

ORDER BY (content='') DESC, title ASC

or maybe

或者可能

ORDER BY title ASC,(content='') DESC

so always in title order, but ones with content are first (when title is the same)

总是在标题顺序中,但内容是第一个(当标题相同时)

#3


0  

How about checking if the content field is empty first?

如何检查内容字段是否为空?

ORDER BY if(content = '', 0, 1), content, title

This will put non-empty content rows first. It all depends on what you want to achieve.

这将首先放入非空内容行。这一切都取决于你想要达到的目标。

Edit: replace content = '' with content IS null if appropriate.

编辑:替换content ='',如果合适,内容为空。

#1


6  

If I understand what you need, try this:

如果我了解您的需求,请尝试以下方法:

SELECT * FROM your_table
ORDER BY
  CASE
    WHEN content IS NULL THEN 1
    ELSE 0
  END
  ,content,title

#2


1  

ORDER BY (content='') DESC, title ASC

or maybe

或者可能

ORDER BY title ASC,(content='') DESC

so always in title order, but ones with content are first (when title is the same)

总是在标题顺序中,但内容是第一个(当标题相同时)

#3


0  

How about checking if the content field is empty first?

如何检查内容字段是否为空?

ORDER BY if(content = '', 0, 1), content, title

This will put non-empty content rows first. It all depends on what you want to achieve.

这将首先放入非空内容行。这一切都取决于你想要达到的目标。

Edit: replace content = '' with content IS null if appropriate.

编辑:替换content ='',如果合适,内容为空。