MySQL查询 - 强制区分大小写与ORDER BY rand()

3

有没有办法强制查询区分大小写?

我的查询语句类似于这样:

"SELECT g_path FROM glyphs WHERE g_glyph = :g_glyph ORDER BY rand()"

如果g_glyph = r,结果可以是R或r,这不是我期望的。

我想要一个区分大小写的返回值。

我谷歌搜索了我的问题,并找到了这个解决方案:

/*Case-sensitive sort in descending order.
In this query, ProductName is sorted in 
case-sensitive descending order.
*/
SELECT ProductID, ProductName, UnitsInStock
FROM products
ORDER BY BINARY ProductName DESC;

但是下面这一行根本不起作用:
"SELECT g_path FROM glyphs WHERE g_glyph = :g_glyph ORDER BY BINARY rand()"

有什么建议吗?

非常感谢您的帮助。


你是否将g_glyph声明为二进制? - riso
你的列使用了哪种排序规则? - Mark Byers
感谢您对我的问题的关注。 Gumbo的解决方案完美地解决了问题。 - Zorkzyd
2个回答

5
字符的顺序和相等性由排序规则定义。在大多数情况下,使用不区分大小写的排序规则。
如果您需要对特定数据使用严格的区分大小写比较,请使用BINARY 运算符
mysql> SELECT 'a' = 'A';
        -> 1
mysql> SELECT BINARY 'a' = 'A';
        -> 0
mysql> SELECT 'a' = 'a ';
        -> 1
mysql> SELECT BINARY 'a' = 'a ';
        -> 0

所以在你的情况下:
SELECT g_path FROM glyphs WHERE BINARY g_glyph = :g_glyph ORDER BY rand()

非常感谢您,Gumbo!这正是我所需要的! - Zorkzyd

2
这在手册页面字符串搜索中的大小写敏感性中有详细介绍。
您需要指定大小写敏感或二进制排序规则。

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

col_name COLLATE latin1_general_cs LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_general_cs
col_name COLLATE latin1_bin LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_bin

If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation. See Section 13.1.14, “CREATE TABLE Syntax”.

在排序名称中的_cs代表“区分大小写”。

谢谢你的回答。 我的数据库规格如下:
  • 类型:InnoDB
  • 排序规则:utf8_general_ci
如果我只是将排序规则从 utf8_general_ci 更改为 utf8_bin,是否可以获得预期结果(区分大小写的结果),还是必须转换所有数据库数据?
- Zorkzyd
"_ci" 表示不区分大小写。你应该使用区分大小写的 "_cs"。Bin 表示二进制比较,比区分大小写更严格。 - Mark Byers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接