MySQL case sensitive query [duplicate]

有些话、适合烂在心里 提交于 2019-11-26 01:56:50

问题


This question already has an answer here:

  • How can I make SQL case sensitive string comparison on MySQL? 11 answers

This has been asked on this site before but I couldn\'t find a sufficient answer. If I\'m doing a query like:

Select Seller from Table where Location = \'San Jose\'

How can I make it return only Sellers with Location \'San Jose\' instead of \'san jose\' or something else?


回答1:


MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'



回答2:


To improve James' excellent answer:

It's better to put BINARY in front of the constant instead:

SELECT * FROM `table` WHERE `column` = BINARY 'value'

Putting BINARY in front of column will prevent the use of any index on that column.




回答3:


Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.



来源:https://stackoverflow.com/questions/7857669/mysql-case-sensitive-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!