Is there a way to force case sensitivity in MySQL / Rails for a single find?

早过忘川 提交于 2019-12-04 10:58:43

问题


I'm doing some searching of tags, and some users like "cat" while others like "Cat" Go figure...

Anyways, is there a way to force a particular find to be case sensitive? Such as:

Tag.find(:some-special-option-here)

Any ideas?


回答1:


You can also do a case-sensitive search without changing your column properties.

SELECT * FROM mytable WHERE myfield='Value' 

This query matches:

  • Value
  • value
  • VALUE
  • vAlUe
  • and so on

While...

SELECT * FROM mytable WHERE BINARY myfield='Value'

Matches only:

  • Value



回答2:


You can make all strings case sensitive when you create the table by adding "COLLATE utf8_bin" to the :options string when creating the table. For example:

create_table( "page_infos", :force => true, :options => "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin") do |t|
      t.string   "title",       :limit => 120
end



回答3:


In the mysql database, set your text's data type to utf_collate_bin. For example:

ALTER TABLE `sets` CHANGE `set_name` `set_name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL

Where 'sets' is the table, 'set_name' is the column of type VARCHAR(64). You can also do this in PhpMyAdmin..

Any binary collate will do the job; but utf8 is preferable.

If you were wondering what the _ci at the end of your current collate is, it means "Case Insensitive" :p



来源:https://stackoverflow.com/questions/264381/is-there-a-way-to-force-case-sensitivity-in-mysql-rails-for-a-single-find

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