MySQL SELECT DISTINCT应该区分大小写?

时间:2013-10-19 05:59:07

标签: mysql sql distinct case-sensitive

如何使MySQL的SELECT DISTINCT区分大小写?

create temporary table X (name varchar(50) NULL);
insert into X values ('this'), ('This');

现在这个查询:

select distinct(name) from X;

结果:

  

这里发生了什么?我想SELECT DISTINCT区分大小写。这不应该是默认的吗?

3 个答案:

答案 0 :(得分:25)

使用BINARY operator

SELECT DISTINCT(BINARY name) AS Name FROM X;

您还可以在选择时CAST进行选择:

SELECT DISTINCT 
(CAST(name AS CHAR CHARACTER SET utf8) COLLATE utf8_bin) AS Name FROM X;

请参阅此SQLFiddle

答案 1 :(得分:7)

我宁愿将列定义更新为区分大小写的碰撞。

像这样:

create table X (name VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin NULL);
insert into X values ('this'), ('This'); 

SQLFiddle:http://sqlfiddle.com/#!2/add276/2/0

答案 2 :(得分:2)

您可以使用散列函数(MD5),然后对其进行分组。

SELECT Distinct(MD5(Cat)), Cat FROM (
  SELECT 'Cat'
    UNION ALL
  SELECT 'cat'
) AS BOW

SQL输出:

enter image description here