Skip to content

Instantly share code, notes, and snippets.

@t-oginogin
Last active April 17, 2016 14:23
Show Gist options
  • Save t-oginogin/6913607 to your computer and use it in GitHub Desktop.
Save t-oginogin/6913607 to your computer and use it in GitHub Desktop.

MySQLのデータベースバックアップ

1.バックアップ用スクリプトを作成します。

backup4mysql.sh

# バックアップファイルを何日分残しておくか
period=10

# バックアップファイルを保存するディレクトリ
dirpath='/data/backup/mysql'

# ファイル名を定義(※ファイル名で日付がわかるようにしておきます)
filename=`date +%Y%m%d`

echo `date`

# mysqldump実行(ファイルサイズ圧縮の為gzで圧縮しておきます。)
mysqldump --opt sample_db --user your_account --password=your_password | gzip > $dirpath/$filename.sql.gz

# パーミッション変更
chmod 700 $dirpath/$filename.sql.gz

# 古いバックアップファイルを削除
oldfile=`date --date "$period days ago" +%Y%m%d`
rm -f $dirpath/$oldfile.sql.gz

echo `date`

2.バックアップスクリプトの日時実行を設定します。

$ crontab -e

00 03 * * * /data/backup4mysql.sh

MySQLでの積集合

SELECT t1.* FROM 
(
  SELECT * FROM table_A
  WHERE (column_A = 'Foo')
  AND (column_B = 'Bar') 
) AS t1
inner join
(
  SELECT table_A.* FROM table_A
  INNER JOIN table_B
  ON table_A.table_B_id = table_B.id 
  AND (table_B.column_C = 'Baz') 
) AS t2
on
  t1.id = t2.id

MySQLのアクセス権設定

全てのホストからのsample_dbに対する全ての操作を許可

grant all privileges on sample_db.* to 'your_account'@'%' identified by 'your_password';
flush privileges;

特定のホストからのsample_dbに対する全ての操作を許可

grant all privileges on sample_db.* to 'your_account'@'xxx.xxx.xxx.xxx' identified by 'your_password';
flush privileges;

特定のホストからの全ての権限を削除

revoke all privileges, grant option from 'your_account'@'xxx.xxx.xxx.xxx';
flush privileges;

MySQLの文字コードを再設定

ALTER TABLE sample_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

collateの主な違い

utf8_general_ci

  • 英字の大文字小文字は区別しない(ci:case insensitive)
  • 全角半角は区別する

utf8_unicode_ci

  • 英字の大文字小文字は区別しない
  • 全角半角は区別しない
  • 濁音、半濁音、ひらがな、カタカナも区別しない

utf8_bin

  • 全てを区別する

MySQL起動時のエラー対応

MySQL起動時に次のようなエラーが出たときの対応です。

$ sudo /sbin/service mysql start
Starting MySQL...The server quit without updating PID file (/var/lib/mysql/localhost.localdomain.pid).                                     [FAILED]

ログを確認します。

$ sudo vi /var/lib/mysql/localhost.localdomain.err

すると、起動しなかった原因がわかります。

[ERROR] /usr/sbin/mysqld: unknown variable 'collation_connection=utf8_general_ci'

PID fileという文言に惑わされないようにしましょう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment