0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MySQL group対象値の大文字小文字を区別する

Posted at

前提データ

blacklistsというテーブルにkeywordというカラムがあるだけのシンプルなテーブルを想定します。
この中に大文字小文字3バリエーションのテストがそれぞれ登録されているとしますます。

  • test->2行
  • Test->2行
  • TEST->1行

テーブル名: blacklists

id keyword
1 test
2 test
3 Test
4 TEST
5 Test

やりたいこと

以下のようなデータが欲しい!

id keyword count
1 test 2
3 Test 2
4 TEST 1

もちろんgroupする

上のようなデータが欲しい場合はもちろんgroupしますよね。
easy:v:

select id, keyword, count(id) keyword_count
from blacklists
group by keyword
having keyword_count> 1

【結果】

id keyword count
1 test 5

ん?

...ああ大文字と小文字って区別されないんだ。

対策

「binary」をつける
https://dev.mysql.com/doc/refman/5.6/ja/charset-binary-op.html

select id, keyword, count(id) keyword_count
from blacklists
group by binary keyword
having keyword_count> 1

【結果】

id keyword count
1 test 2
3 Test 2
4 TEST 1

easy:v:

余談

whereするときももちろん有効です。

select *
from blacklists
where keyword = binary 'test';

select *
from blacklists
where keyword = 'test';

ではもちろん結果が変わってきます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?