2

我在使用 MySQL 查询时遇到了一些意想不到的结果。我想按我的帖子标题自然地排序(我正在运行 WordPress,但我认为这不相关)。

这是一些出现的标题的示例,以提供一个想法:

1-1-1a
1-13-5j
7-1
9-1-2 
12-13-2a

我做了很多研究,最接近我想要使用的结果

ORDER BY (posts.post_title+0) ASC

我仍然在一页结果中得到一个奇怪的结果。完整的查询如下。

SELECT rlt13_posts.post_title
FROM rlt13_posts
INNER JOIN rlt13_term_relationships ON (rlt13_posts.ID = rlt13_term_relationships.object_id)
INNER JOIN rlt13_postmeta ON (rlt13_posts.ID = rlt13_postmeta.post_id)
JOIN rlt13_icl_translations t ON rlt13_posts.ID = t.element_id
AND t.element_type IN ('post_rlt_rule')
JOIN rlt13_icl_languages l ON t.language_code=l.code
AND l.active=1
WHERE 1=1
  AND (rlt13_term_relationships.term_taxonomy_id IN (92,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,501))
  AND rlt13_posts.post_type = 'rlt_rule'
  AND (rlt13_posts.post_status = 'publish')
  AND ((rlt13_postmeta.meta_key = 'new_rule'
        AND CAST(rlt13_postmeta.meta_value AS CHAR) = ''))
  AND t.language_code='en'
GROUP BY rlt13_posts.ID
ORDER BY (rlt13_posts.post_title+0) ASC

并且这个查询在执行后给出了以下结果(超出范围的结果排列整齐)。

在此处输入图像描述

最后两个结果对我来说有点莫名其妙。该查询会在任何其他页面上给出预期结果。我确实注意到,当我从查询中删除以下语句时,前一个查询底部的 2 个意外结果会以自然顺序正确显示。

感谢您对(字面上)进行排序的任何帮助!

AND (rlt13_term_relationships.term_taxonomy_id IN (92, ****))
4

1 回答 1

0

在 MySQL 中这并不容易,因为在处理分隔符分隔的字符串时会遇到困难。作为一个选项,您可以像这样使用SUBSTRING_INDEX()函数(简化查询)

SELECT
  *
FROM
  t
ORDER BY
-- left:
  CAST(SUBSTRING_INDEX(name, '-', 1) AS UNSIGNED),
-- middle:
  CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(name, '-', 2), '-', -1) AS UNSIGNED)
-- right:
  CAST(SUBSTRING_INDEX(name, '-', -1) AS UNSIGNED)

- 你也不应该忘记将类型转换为整数(CAST()UNSIGNED上面的情况)。样本数据将是:

+--------+----------+
| 编号 | 姓名 |
+--------+----------+
| 1 | 1-1-1a |
| 2 | 1-13-5j |
| 4 | 7-1 |
| 5 | 9-1-2 |
| 3 | 12-13-2a |
+--------+----------+
于 2013-09-19T08:27:44.337 回答