【问题标题】:Java sorting is not the same with MySQL sortingJava排序与MySQL排序不同
【发布时间】:2016-03-04 04:02:18
【问题描述】:

我需要检查表格中的排序,表格内容是由 MySQL 给出的。我正在尝试以下操作: Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);

并得到以下结果:
tes3@test.com
test4@test.com
test5@test.com
test@test.com
test_user@mail.com
user-og@driver.com

这是我通过查询从 MySQL 得到的:
SELECT 'email' FROM 'user' WHERE 1 ORDER BY 'user'.'email' ASC

tes3@test.com
test_user@mail.com
test@test.com
test4@test.com
test5@test.com
user-og@driver.com

似乎Java根据ASCII表排序: http://www.asciitable.com/ 4 (52) - @ (64) - _ (95)

但在 MySQL 结果中,顺序是 _ -> @ -> 4

email 字段排序规则为:utf8_unicode_ci
有什么问题,是否有任何比较器可以以相同的方式进行排序?

【问题讨论】:

  • AFAIK java 处理_ 不同,然后在您排序时它们在 sql 中得到处理。但造成这种情况的原因可能是您的本地语言设置。
  • 你是如何在你的代码中做到这一点的?

标签: java mysql sorting collections comparator


【解决方案1】:

使用[Collator][1]:

Collat​​or 类执行区域敏感的字符串比较。您可以使用此类为自然语言文本构建搜索和排序例程。

代码将是:

    Collator coll = Collator.getInstance(Locale.US);
    coll.setStrength(Collator.IDENTICAL); 
    Collections.sort(words, coll);

【讨论】:

  • 谢谢,这有助于处理数字和“@”等符号,但现在我在识别space 时遇到了问题。 MySQL输出:Existing_test_companyTest companyTest company 10test_test_1使用Collat​​or的Java排序结果:Existing_test_companytest_test_test_1Test companyTest company
  • 添加规则解决:String rules = ((RuleBasedCollator) Collator.getInstance(Locale.US)).getRules(); RuleBasedCollator correctedCollator = new RuleBasedCollator(rules.replaceAll("<'\u005f'", "<' '<'\u005f'"));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多