MySQL命令字母数字列

时间:2013-09-19 08:04:22

标签: mysql sql-order-by

我在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

此查询在执行后给出以下结果(结果超出范围排列整齐)。

enter image description here

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

任何帮助将这个东西排序(字面意思)都是值得赞赏的!

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

1 个答案:

答案 0 :(得分: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)。样本数据将是:

+------+----------+
| id   | name     |
+------+----------+
| 1    | 1-1-1a   |
| 2    | 1-13-5j  |
| 4    | 7-1      |
| 5    | 9-1-2    |
| 3    | 12-13-2a |
+------+----------+