MySQL Reference Manual for version .


概要

MySQL (TM) ソフトウェアはとても高速で、マルチスレッド、マルチユーザの、頑丈な SQL (Structured Query Language)データベースサーバです。 MySQL Server は、mass-deployed ソフトウェアへの組み込みのように、ミッションクリティ カルで高負荷生産システム用に意図されています。 MySQLMySQL AB の商標です。

MySQL ソフトウェア は Dual Licensed です。 あなたは、MySQLGNU GENERAL PUBLIC LICENSE (http://www.gnu.org/licenses/) に従って、 Open Source/Free Software として利用できます。 あるいは、GPL の条件が合わない場合には、 コマーシャルライセンスを MySQL AB から購入することも可能です。 See section MySQL ライセンスとサポート.

MySQL ウェブサイト (http://www.mysql.com/) は MySQL ソフトウェア についての最新情報を提供しています。

次のリストはマニュアルのいくつかの有用なセクションを説明しています:

Important:

エラー(バグ)レポート、質問、コメントは メーリングリスト mysql@lists.mysql.com に送ってください。See section バグや問題を報告する方法。 バグレポートを生成するためには mysqlbug スクリプトを使用すべきです。

ソースディストリビューションでは、mysqlbug スクリプトは `scripts' ディレクトリ に見つけることができます。バイナリディストリビューションでは、mysqlbug`bin' ディレクトリ(MySQL-server RPM パッケージでは `/usr/bin') に見つけることができます。

MySQL Server のセキュリティバグを発見した場合は、 security@mysql.com に email を送ってください。

このマニュアルについて

これは MySQL のリファレンスマニュアルです; これは MySQL バージョン について記述しています。 Functional changes are always indicated with reference to the version, so this manual is also suitable if you are using an older version of the MySQL software. 一般的な SQL やリレーショナルデータベース概念の説明書ではありません。

MySQL Database Software は発展中なので、マニュアルは頻繁に更新されます。そのため、 オンラインで参照しない限り、このバージョンが期限切れである可能性があります。 このマニュアルの最新バージョンは http://www.mysql.com/documentation/ に多 様な形式で置いてあります。 このマニュアルは現在 HTML, PDF, Windows HLP バージョンがあります。

プライマリドキュメントは Texinfo ファイルです。HTML バージョンは texi2html の変更されたバージョンで自動的に提供されます。プレーン テキストと Info バージョンは makeinfo で提供されます。PostScript バージョンは texi2dvidivps を使用して提供されます。PDF バージョンは pdftex で提供されます。

マニュアル内の情報を見つけるのがつらいなら、 検索可能 バージョン http://www.mysql.com/doc/ を 試すことが可能です。

このマニュアルへの追加または修正に関連する提案がある場合は、それらを マニュアルチーム docs@mysql.com に 送ってください。

このマニュアルは当初、David Axmark, Michael (Monty) Widenius によって書かれました。 現在は Michael (Monty) Widenius, Arjen Lentz, Paul DuBois によって維持されています。他の貢献者については section Credits を参照してください。

日本語訳は、以下の方々により行なわれました。 (ハンドル名だけ書きます。敬称略。翻訳サーバーに登録した順 :) ):

The copyright (2003) to this manual is owned by the Swedish company MySQL AB. See section Copyrights and Licenses Used by MySQL.

このマニュアル中で使用されている表記

このマニュアルは特定の印刷上の表記を使用しています:

constant
固定幅フォントは次のものに使用されます。コマンド名, オプション; SQL ステー トメント; データベース名, テーブル名, フィールド名; C と Perl コード; 環境変数。 例: ``mysqladmin がどのように動作するかを見るためには、 --help オプションをつけて起動してください。''
`filename'
引用符で括られた固定幅フォントはファイル名とパス名に使用されます。例: `` ディストリビューションは `/usr/local' ディレクトリ配下にインストールされます。''
`c'
引用符で括られた固定幅フォントは文字シーケンスを示すためにも使用されます。 例: ``ワイルドカードを指定するためには、`%' 文字を使用してください。''
italic
イタリックフォントは強調のために使用されます, このように
boldface
ボールドフォントは table headings と、 特に強い強調を伝えるために使用されます。

コマンドが特定のプログラムによって実行されることを意味することを表す時、 コマンドと共に表示されるプロンプトによって、そのプログラムを表します。例えば、 shell> は、あなたのログインシェルから実行するコマンドを表し、 mysql>mysql クライアントプログラムから実行するコマンドを表します:

シェルコマンドは Bourne シェル構文で示されます。csh 形式のシェ ルを使用している場合は、わずかに変更してコマンドを発行する必要があるでしょ う。例えば、環境変数を設定してコマンドを実行するシーケンスは、Bourne シェ ル構文では次のようになります:

shell> VARNAME=value some_command

csh では、次のようなシーケンスを実行してください:

shell> setenv VARNAME value
shell> some_command

データベース名, テーブル名, フィールド名はコマンドの中で置換しなければいけない ことがよくあります。このような置換が必要なことを示すために、このマニュア ルは db_name, tbl_name, col_name を使用します。 例えば、次のようなステートメントを見た場合:

mysql> SELECT col_name FROM db_name.tbl_name;

これは、同様のステートメントを入力するためには、おそらく次のように、あな た自身のデータベース名, テーブル名, フィールド名を供給することを意味します:

mysql> SELECT author_name FROM biblio_db.author_list;

SQL ステートメントは大文字でも小文字でも記述できます。このマニュアルで は大文字で記述します。

構文の説明中では、角括弧(`['`]')はオプションの単語や節であ ることを示すために使用されます。in the following statement, IF EXISTS is optional:

DROP TABLE [IF EXISTS] tbl_name

構文要素がいくつかのものからなる場合、垂直バー(`|')で区切られます。 選択セットから一つのメンバを選ぶことができるときは、角括弧中にリストされ ます。(`[' and `]'):

TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str)

選択セットから一つのメンバを選ぶ必要があるときは、波括弧(`{'`}')中にリストされます:

{DESCRIBE | DESC} tbl_name {col_name | wild}

MySQL とは何か

MySQLは、もっとも有名な オープンソース SQLデータベースで、 MySQL AB によって開発、供給されています。MySQL ABMySQL データベースに関わるサービスを提供するビジネスを構築する 営利会社です。See section MySQL AB とは何か.

MySQL ウェブサイト(http://www.mysql.com/)は、MySQLMySQL AB に ついての最新情報を提供しています。

MySQL はデータベース管理システムです。
データベースはデータの集まりで構成されています。絵画のギャラリーの単純な ショッピングリストや共通ネットワーク内での膨大な量の情報からもなり得ます。 コンピュータデータベースに格納されたデータの追加、アクセス、処理のために は、MySQL サーバーのようなデータベース管理システムが必要です。コンピュー タは大量のデータの処理にとても向いているので、データベース管理システムは スタンドアロンユーティリティや他のアプリケーションの一部として、コンピュー タの中で中心的な役割を演じています。
MySQL は関係データベース管理システムです。
関係データベースはデータを大きな格納場所に全てのデータを置くのではなく、 別々のテーブル内に格納します。これは速度と柔軟性を追加します。要求された いくつかのテーブルからデータを結合することを可能とする関係を定義すること により、テーブルがリンクされます。MySQLSQL 部分は "構造化ク エリ言語 (Structured Query Language)" を表しています。これは、データベー スのアクセスに使用される最も有名な標準言語です。
MySQL ソフトウェアは オープンソース です。
オープンソースの意味は誰でも使用し変更することができるということです。誰 でも MySQL ソフトウェアをインターネットからダウンロードし、無償で使 用することができます。その気があれば誰でも必要に応じてソースコードを調べ、 変更することができます。MySQL ソフトウェア は GPL (GNU General Public License) http://www.gnu.org/licenses/ に従います。これは、様々な状況でそ のソフトウェアで行なえることと行なえないことを定義しています。もし GPL を嫌だと感じていたり、MySQL を商用アプリケーションに組み込む必 要があるなら、商用ライセンス版を我々から購入することができます。 See section MySQL Licenses.
何故 MySQL データベースサーバーを使用するのか?
MySQL Database Server はとても速く、信頼でき、簡単に使用できます。それがあなた が探しているものなら、試してみるべきです。MySQL Server は、我々のユー ザと協力して開発されたとても実用的な機能のセットを持っています。我々のベ ンチマークページ上で、MySQL Server と他のいくつかのデータベース管理シ ステムの性能比較を見つけることができます。See section The MySQL Benchmark Suite. MySQL Server は、既存のソリューションよりも速くとても大きなデータベー スを処理するために、そして、高い需要がある製品環境で何年間かの使用に耐え るために、独創的に開発されました。一定の開発下で、MySQL Server は今日、 豊富でとても有用な機能セットを提供します。MySQL は、結合性、速 度、セキュリティでインターネット上でのデータベースアクセスに高く適合しま す。
MySQL の技術機能。
詳しい技術情報については、section MySQL Language ReferenceMySQL Database Software は、様々なバッ クエンドをサポートするマルチスレッド SQL サーバ、いくつかのクライアント プログラム、ライブラリ、管理ツール、プログラミングインタフェース(APIs)から成る クライアント/サーバシステムです。 We also provide MySQL Server as a multi-threaded library which you can link into your application to get a smaller, faster, easier-to-manage product.
MySQL は多くの貢献ソフトを持っています。
おそらく、すでに MySQL Database Server をサポートする、あなたの好きなアプリケー ション/言語を見つけることができるでしょう。

MySQL の公式な発音は ``My Ess Que Ell'' です(MY-SEQUEL ではあり ません)。 しかし MY-SEQUEL と発音する人を正すことは避けています。

MySQL の歴史

最初は、我々固有の速くて低レベルな (ISAM) ルーチンを使用したテーブルへ 接続するために、 mSQL を使用するつもりでした。 しかし、いくつかのテストの後、我々は mSQL は我々が必要とするほど高速ではなく、柔軟度を持っていないとの 結論に至りました。この結果、mSQL とほとんど同じ API インタフェー スを持つ、我々のデータベースへの新しい SQL インタフェースに帰結しました。 この API はサードパーティコードの移植を簡単にするために選択されました。

MySQL の名前の由来は完全には明らかではありません。我々のベース ディレクトリと多くのライブラリとツールは接頭辞 ``my'' を 10 年以上も使っ ています。しかし、Monty の娘(何年か若い)も My という名前です。そのため、 この2つのどちらが MySQL に名前を与えたかは、我々にとっても未だ 謎です。

MySQL の主な機能

MySQL Database Software の重要な特徴のいくつかを以下の項目に挙げます。 See section MySQL 4.x In A Nutshell.

Internals and Portability
Column Types
Commands and Functions
Security
Scalability and Limits
Connectivity
Localisation
Clients and Tools

MySQL はどれくらい安定か?

この節では、``MySQL Server はどれくらい安定か?'' と ``私はこのプロジェ クトの MySQL Server に依存できるか?'' という質問について回答します。

我々はここで、いくつかの問題を明らかにし、多くの人に関係すると思われるさ らに重要な質問のいくつかを回答することを試みます。この節は、メーリングリ スト(そこではとても活発にバグが報告されています)から取り込まれた情報が一 緒に置かれています。

Original code stems back from the early '80s, providing a stable code base, and the ISAM table format remains backward-compatible. TcX (MySQL AB の前身)では、MySQL は 1996 中頃から我々のプロジェクトで何の問題も なく動いていました。MySQL Database Software が広く公にリリースされた時、我々は、MySQL 内 に ``テストされていないコード'' の部分があることに注意しました。これは、 我々とは異なる方法でクエリを作成する新しいユーザによってすぐに見つけられました。 新しい各リリースは、(多くの新しい機能を持っているのに)前のものよりも問題 は少なくなります。そして次のリリースの一つを ``安定'' と呼ぶことができるよ うに我々は望んでいます。

MySQL Server の各リリースは実用的で、ユーザが ``グレイゾーン'' からの コードの使用を開始する時にだけ問題があります。当然、外部のユーザは、何が グレイゾーンかを知ることができません; この節で現在知られているこれらを示 してみます。 説明は MySQL Server の 3.23.x バージョンで扱われます。知られていて報告 されているバグは全て最新のバージョンで修正されています。bugs 節に 書かれているバグは除きます。それらは ``設計'' 関連のものです。See section Known Errors and Design Deficiencies in MySQL.

MySQL Server は複数の階層と様々な独立モジュールで書かれています。これ らのモジュールは、それぞれがどのようにテストされているかとともに次にリス トされています:

Replication -- Gamma
レプリケーションを使用した大規模なサーバクラスターは製品として使用され良い結果をもたらしています。 拡張されたレプリケーション機能に対する取り組みは MySQL 4.x でも引き続き行われます。
InnoDB tables -- Stable (in 3.23 from 3.23.49)
InnoDB storage engines は MySQL 3.23 ツリーでは version 3.23.49 から安定です。 InnoDB は大規模で負荷の大きい製品システムで使用されています。
BDB tables -- Gamma
Berkeley DBはとても安定したコードですが未だに BDB トランザクション storage engines インターフェースが MySQL Server では改良を加えている途中であり、 他のテーブルタイプと同等に扱われるまでにはもう少し時間がかかりそうです。
FULLTEXT -- Beta
テキストの検索は動作しているように見えますが、まだ広く使用されていません。 Important enhancements are being implemented for MySQL 4.0.
MyODBC 2.50 (uses ODBC SDK 2.5) -- Gamma
Increasingly in wide use. Some issues brought up appear to be application-related and independent of the ODBC driver or underlying database server.
Automatic recovery of MyISAM tables -- Gamma
This status only regards the new code in the MyISAM storage engine that checks if the table was closed properly on open and executes an automatic check/repair of the table if it wasn't.
Bulk-insert -- Alpha
New feature in MyISAM tables in MySQL 4.0 for faster insert of many rows.
ロック -- ガンマ
これはとてもシステムに依存しています。いくつかのシステムでは、これは、標 準 OS ロック (fcntl()) を使用するため大きな問題があります。これらの場合では、 MySQL デーモンを --skip-external-locking フラグつきで動かすべ きです。知られている問題は、いくつかの Linux システムと NFS マウントされ たファイルシステム使用時の SunOS です。

MySQL AB は代金を支払った顧客のために 高サポートを提供しています。しかし MySQL メーリングリストは通常、全ての一般的な質問に回答を提供し ています。バグは通常すぐにパッチで修正され、深刻なバグには、ほとんどいつ も新しいリリースがあります。

MySQLではどれだけテーブルを大きくできるの?

MySQL Version 3.22では、最大テーブルサイズに 4Gbyte という制限がありました。 MySQL Version 3.23から採用された新しい MyISAM では、 最大テーブルサイズは800万テラバイト( 2 ^ 63 bytes )に拡張されました。

ただし、OSの側にも、ファイルサイズの制限が存在していることには注意して下さい。 いくつか例を示します:

Operating System File Size Limit
Linux-Intel 32 bit 2G, 4G あるいはそれ以上, Linux のバージョンによる。
Linux-Alpha 8T (?)
Solaris 2.5.1 2G (パッチにより 4G に対応)
Solaris 2.6 4G (can be changed with flag)
Solaris 2.7 Intel 4G
Solaris 2.7 UltraSPARC 512G

Linux 2.2 では、ext2ファイルシステム用のLFSパッチを適用することで、 2G 以上のテーブルを使用することができます。 Linux 2.4ではReiserFS用の同様のパッチが存在し、大きなファイルを扱うことができるようになります。 (訳注: Linux 2.4.1 以上では、最初から ReiserFS がカーネルのソースに組み込まれていますし、 2.4.16 以上では、ext3 もカーネルのソースに組み込まれました)

以上からわかるように、MySQL の最大テーブルサイズはOSの制限によって決まることがほとんどです。

デフォルトでは、MySQL の最大テーブルサイズは4Gに設定されています。 あるテーブルの最大テーブルサイズは、SHOW TABLE STATUS コマンドか、 myisamchk -dv table_name によって確認することができます。 See section SHOW 構文.

もしも4G 以上のテーブルが必要な場合には(加えて、OSがそれをサポートしている場合には)、 テーブルを作る際に、AVG_ROW_LENGTHMAX_ROWS パラメータを設定することができます。 See section CREATE TABLE 構文. テーブル作成後に、ALTER TABLE で変更することもできます。 See section ALTER TABLE 構文

読み込み専用の大きなテーブルが必要な時は、 myisampackを使って複数のテーブルを一つにまとめた上で圧縮することができます。 myisampackは、テーブルの大きさをだいたい50%程度まで圧縮できます。 結果として、より大きなテーブルを作ることが可能となるでしょう。See section myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ.

MyISAMデータファイルに対する、OSのファイル制限を回避するのに、 RAID オプションを使うこともできます。See section CREATE TABLE 構文.

MERGE ライブラリ -- 同じ構造のテーブルをひとまとめに扱う機能を提供します -- を 使用するという解決法も考えられるでしょう。See section MERGE Tables (3.23.25以上).

2000 年対応

MySQL Server 自身は 2000 年問題(Y2K)に対して何の問題も持っていません:

2000年安全でない方法で MySQL Server を使用するアプリケーションでは問題 になります。例えば、多くの古いアプリケーションは4桁値ではなく2桁値(これ は曖昧です)を使用して年を格納し操作します。この問題は、00 または 99 のような値を ``欠けている'' 値の表われとして使用するアプリケー ションによって作られます。

あいにく、これらの問題を修正するのは困難です。様々なアプリケーションが様々 なプログラムによって書かれていて、その各々が慣習と日付操作関数の様々な組 み合わせを使用するからです。

これは、MySQL Server が 2030 年までの日付に何の問題もないことを示す簡単なテスト です:

mysql> DROP TABLE IF EXISTS y2k;
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE y2k (date DATE,
    ->                   date_time DATETIME,
    ->                   time_stamp TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO y2k VALUES
    -> ("1998-12-31","1998-12-31 23:59:59",19981231235959),
    -> ("1999-01-01","1999-01-01 00:00:00",19990101000000),
    -> ("1999-09-09","1999-09-09 23:59:59",19990909235959),
    -> ("2000-01-01","2000-01-01 00:00:00",20000101000000),
    -> ("2000-02-28","2000-02-28 00:00:00",20000228000000),
    -> ("2000-02-29","2000-02-29 00:00:00",20000229000000),
    -> ("2000-03-01","2000-03-01 00:00:00",20000301000000),
    -> ("2000-12-31","2000-12-31 23:59:59",20001231235959),
    -> ("2001-01-01","2001-01-01 00:00:00",20010101000000),
    -> ("2004-12-31","2004-12-31 23:59:59",20041231235959),
    -> ("2005-01-01","2005-01-01 00:00:00",20050101000000),
    -> ("2030-01-01","2030-01-01 00:00:00",20300101000000),
    -> ("2050-01-01","2050-01-01 00:00:00",20500101000000);
Query OK, 13 rows affected (0.01 sec)
Records: 13  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM y2k;
+------------+---------------------+----------------+
| date       | date_time           | time_stamp     |
+------------+---------------------+----------------+
| 1998-12-31 | 1998-12-31 23:59:59 | 19981231235959 |
| 1999-01-01 | 1999-01-01 00:00:00 | 19990101000000 |
| 1999-09-09 | 1999-09-09 23:59:59 | 19990909235959 |
| 2000-01-01 | 2000-01-01 00:00:00 | 20000101000000 |
| 2000-02-28 | 2000-02-28 00:00:00 | 20000228000000 |
| 2000-02-29 | 2000-02-29 00:00:00 | 20000229000000 |
| 2000-03-01 | 2000-03-01 00:00:00 | 20000301000000 |
| 2000-12-31 | 2000-12-31 23:59:59 | 20001231235959 |
| 2001-01-01 | 2001-01-01 00:00:00 | 20010101000000 |
| 2004-12-31 | 2004-12-31 23:59:59 | 20041231235959 |
| 2005-01-01 | 2005-01-01 00:00:00 | 20050101000000 |
| 2030-01-01 | 2030-01-01 00:00:00 | 20300101000000 |
| 2050-01-01 | 2050-01-01 00:00:00 | 00000000000000 |
+------------+---------------------+----------------+
13 rows in set (0.00 sec)

これは、DATEDATETIME 型は未来のいかなる日付において 問題のないことををしめします (これら日付は 9999 年まで扱えます)

TIMESTAMP 型は、時刻を保存しますが、2030-01-01 までです。 TIMESTAMP は 32-bit マシンで(signed value)は 1970 から 2030 の範囲です。 64-bit マシンでは、 2106 年(unsigned value)まで扱えれます。

MySQL Server は 2000年対応ですが、曖昧でない入力を提供するのはあなたの 責任です。曖昧な日付の入力データ(2桁の年の値)の扱いについての MySQL Server の規則については section 西暦2000年問題とデータ型 を参照してください。

MySQL AB とは何か

MySQL AB は、MySQL の創始者と主な開発者の会社です。 MySQL AB was originally established in Sweden by David Axmark, Allan Larsson and Michael Monty Widenius.

All the developers of the MySQL server are employed by the company. We are a virtual organisation with people in a dozen countries around the world. We communicate extensively over the Net every day with each other and with our users, supporters and partners.

我々は、MySQL の開発と我々 のデータベースを新しいユーザに広げることに専念しています。MySQL ABMySQLサーバソースコードの著作権, MySQL logo の著作権, MySQL 商標権, このMySQL マニュアルの著作権を所有します。 See section MySQL とは何か.

The MySQL core values show our dedication to MySQL and Open Source.

我々は MySQL Database Software を次のようにしたいです。

MySQL ABMySQL AB の人々は次を行ないます。

MySQL ウェブサイト(http://www.mysql.com/)は、MySQL と MySQL AB に ついての最新情報を提供しています。

MySQL AB のビジネスモデル及びサポート

私たちが最もよく受ける質問は:「`どのようにして無料で配布して採算を取っているので しょうか?」 というものです。それは、このようにしています。

MySQL AB はサポート、サービス、商用ライセンス及びロイアリティで利益をあげます。 そして、私たちは製品開発とMySQLの事業を展開するため、これらの収益を利用します。

MySQL AB は創業以来、利益が増えています。 2001年10月、私たちは有数のスカンジナビアの投資家 および数少ないビジネスエンジェルからのベンチャー投資に応じました。 この投資は、私たちのビジネス・モデルを固め、 持続的成長の基盤を構築するために使用されます。

Support

MySQL AB は、MySQL データ・ベースの設立者及び主な開発者により管理・運営されます。 開発者は顧客及びその他のユーザの要望・課題を連絡をとり続けるためのサポートを提供することを約束します。 我々の全てのサポートは有能な開発者によって提供されます。実際に複雑な質問は、MySQLサーバーの主要な著者 である Michael Monty Widenius が答えます。 See section Support Offered by MySQL AB.

さらなる情報とサポートの依頼は、 http://www.mysql.com/support/ か、 我々の販売員 sales@mysql.com にご連絡ください。

トレーニングとCertification

MySQL ABMySQL と関連したトレーニングを世界的に提供します。 我々は、一般公募するコースと、あなたの会社のニーズに合せた特別な社内研修の 両方を提供します。 MySQL トレーニング はさらに、我々のパートナーである MySQL 認定 トレーニング・センター でも受講ができます。

我々のトレーニングの教材は、いくつかのデータベースの実例と資料・説明書、 そしてサンプル・アプリケーションを使用します。 また、教材は MySQL の最新バージョンを反映するために常時更新されます。 我々の講師は、トレーニングの質と教材の開発を保証するため、常に開発チームにサポートされます。 これは、さらにトレーニング中の質問には必ず回答できることを保証します。

私たちのトレーニング講座に参加することにより、 あなたの目標と MySQL アプリケーションを実現することができるでしょう。 さらに以下のことができるでしょう:

参加予定者あるいはトレーニング・パートナーとして我々のトレーニングに興味を持っている場合、 http://www.mysql.com/training/ のトレーニング課にアクセスするか、あるいは training@mysql.com にメールで連絡をください。

MySQL 認定プログラム についての詳細な情報は, http://www.mysql.com/certification/ を参照してください。

Consulting

MySQL AB and its Authorised Partners offer consulting services to users of MySQL Server and to those who embed MySQL Server in their own software, all over the world.

Our consultants can help you design and tune your databases, construct efficient queries, tune your platform for optimal performance, resolve migration issues, set up replication, build robust transactional applications, and more. We also help customers embed MySQL Server in their products and applications for large-scale deployment.

Our consultants work in close collaboration with our development team, which ensures the technical quality of our professional services. Consulting assignments range from 2-day power-start sessions to projects that span weeks and months. Our expertise not only covers MySQL Server, but also extends into programming and scripting languages such as PHP, Perl, and more.

If you are interested in our consulting services or want to become a consulting partner, please visit the consulting section of our web site at http://www.mysql.com/consulting/ or contact our consulting staff at consulting@mysql.com.

Commercial Licenses

The MySQL database is released under the GNU General Public License (GPL). This means that the MySQL software can be used free of charge under the GPL. If you do not want to be bound by the GPL terms (like the requirement that your own application becomes GPL as well), you may purchase a commercial license for the same product from MySQL AB. See http://www.mysql.com/products/pricing.html. Since MySQL AB owns the copyright to the MySQL source code, we are able to employ Dual Licensing which means that the same product is available under GPL and under a commercial license. This does not in any way affect the Open Source commitment of MySQL AB. For details about when a commercial license is required, please see section MySQL Licenses.

We also sell commercial licenses of third-party Open Source GPL software that adds value to MySQL Server. A good example is the InnoDB transactional storage engine that offers ACID support, row-level locking, crash recovery, multi-versioning, foreign key support, and more. See section InnoDB テーブル (3.23.6以上).

Partnering

MySQL AB has a worldwide partner programme that covers training courses, consulting & support, publications plus reselling and distributing MySQL and related products. MySQL AB Partners get visibility on the http://www.mysql.com/ web site and the right to use special versions of the MySQL trademarks to identify their products and promote their business.

If you are interested in becoming a MySQL AB Partner, please e-mail partner@mysql.com.

The word MySQL and the MySQL dolphin logo are trademarks of MySQL AB. See section MySQL AB Logos and Trademarks. These trademarks represent a significant value that the MySQL founders have built over the years.

Advertising

The MySQL web site (http://www.mysql.com/) is popular among developers and users. In October 2001, we served 10 million page views. Our visitors represent a group that makes purchase decisions and recommendations for both software and hardware. Twelve percent of our visitors authorise purchase decisions, and only nine percent are not involved in purchase decisions at all. More than 65% have made one or more online business purchase within the last half-year, and 70% plan to make one in the next months.

Contact Information

The MySQL web site (http://www.mysql.com/) provides the latest information about MySQL and MySQL AB.

For press service and inquiries not covered in our News releases (http://www.mysql.com/news/), please send e-mail to press@mysql.com.

If you have a valid support contract with MySQL AB, you will get timely, precise answers to your technical questions about the MySQL software. For more information, see section Support Offered by MySQL AB. On our website, see http://www.mysql.com/support/, or send an e-mail message to sales@mysql.com.

For information about MySQL training, please visit the training section at http://www.mysql.com/training/. If you have restricted access to the Internet, please contact the MySQL AB training staff at training@mysql.com. See section トレーニングとCertification.

For information on the MySQL Certification Program, please see http://www.mysql.com/certification/. See section トレーニングとCertification.

If you're interested in consulting, please visit the consulting section at http://www.mysql.com/consulting/. If you have restricted access to the Internet, please contact the MySQL AB consulting staff at consulting@mysql.com. See section Consulting.

Commercial licenses may be purchased online at https://order.mysql.com/. There you will also find information on how to fax your purchase order to MySQL AB. More information about licensing can be found at http://www.mysql.com/products/pricing.html. If you have questions regarding licensing or you want a quote for a high-volume license deal, please fill in the contact form on our web site (http://www.mysql.com/) or send an e-mail message to licensing@mysql.com (for licensing questions) or to sales@mysql.com (for sales inquiries). See section MySQL Licenses.

If you represent a business that is interested in partnering with MySQL AB, please send e-mail to partner@mysql.com. See section Partnering.

For more information on the MySQL trademark policy, refer to http://www.mysql.com/company/trademark.html or send e-mail to trademark@mysql.com. See section MySQL AB Logos and Trademarks.

If you are interested in any of the MySQL AB jobs listed in our jobs section (http://www.mysql.com/company/jobs/), please send an e-mail message to jobs@mysql.com. Please do not send your CV as an attachment, but rather as plain text at the end of your e-mail message.

For general discussion among our many users, please direct your attention to the appropriate mailing list. See section MySQL Mailing Lists.

Reports of errors (often called bugs), as well as questions and comments, should be sent to the mailing list at mysql@lists.mysql.com. If you have found a sensitive security bug in the MySQL Server, please send an e-mail to security@mysql.com. See section バグや問題を報告する方法.

If you have benchmark results that we can publish, please contact us at benchmarks@mysql.com.

If you have any suggestions concerning additions or corrections to this manual, please send them to the manual team at docs@mysql.com.

For questions or comments about the workings or content of the MySQL web site (http://www.mysql.com/), please send e-mail to webmaster@mysql.com.

MySQL AB has a privacy policy, which can be read at http://www.mysql.com/company/privacy.html. For any queries regarding this policy, please e-mail privacy@mysql.com.

For all other inquires, please send e-mail to info@mysql.com.

MySQL ライセンスとサポート

(訳注: ライセンスの章については、正確さをきすため原文を併記しています。 訳文だけでなく原文に目を通してください。 もし意味の取違いを見つけたなら、takeshi@SoftAgency.co.jp に連絡してください。)

このセクションでは、MySQLのサポートとライセンス規定について説明します。

Support Offered by MySQL AB

Technical support from MySQL AB means individualised answers to your unique problems direct from the software engineers who code the MySQL database engine.

We try to take a broad and inclusive view of technical support. Almost any problem involving MySQL software is important to us if it's important to you. Typically customers seek help on how to get different commands and utilities to work, remove performance bottlenecks, restore crashed systems, understand operating system or networking impacts on MySQL, set up best practices for backup and recovery, utilise APIs, etc. Our support covers only the MySQL server and our own utilities, not third-party products that access the MySQL server, though we try to help with these where we can.

Detailed information about our various support options is given at http://www.mysql.com/support/, where support contracts can also be ordered online. If you have restricted access to the Internet, contact our sales staff at sales@mysql.com.

Technical support is like life insurance. You can live happily without it for years, but when your hour arrives it becomes critically important, yet it's too late to buy it! If you use MySQL Server for important applications and encounter sudden troubles, it might take too long to figure out all the answers yourself. You may need immediate access to the most experienced MySQL troubleshooters available, those employed by MySQL AB.

Copyrights and Licenses Used by MySQL

MySQL AB owns the copyright to the MySQL source code, the MySQL logos and trademarks and this manual. See section MySQL AB とは何か. Several different licenses are relevant to the MySQL distribution:

  1. All the MySQL-specific source in the server, the mysqlclient library and the client, as well as the GNU readline library is covered by the GNU General Public License. See section GNU General Public License. The text of this license can also be found as the file `COPYING' in the distributions.
  2. The GNU getopt library is covered by the GNU Lesser General Public License. See section GNU Lesser General Public License.
  3. Some parts of the source (the regexp library) are covered by a Berkeley-style copyright.
  4. Older versions of MySQL (3.22 and earlier) are subject to a more strict license (http://www.mysql.com/products/mypl.html). See the documentation of the specific version for information.
  5. The manual is currently not distributed under a GPL-style license. Use of the manual is subject to the following terms: Please e-mail docs@mysql.com for more information or if you are interested in doing a translation.

For information about how the MySQL licenses work in practice, please refer to section MySQL Licenses. Also see section MySQL AB Logos and Trademarks.

MySQL Licenses

The MySQL software is released under the GNU General Public License (GPL), which probably is the best known Open Source license. The formal terms of the GPL license can be found at http://www.gnu.org/licenses/. See also http://www.gnu.org/licenses/gpl-faq.html and http://www.gnu.org/philosophy/enforcing-gpl.html.

Since the MySQL software is released under the GPL, it may often be used for free, but for certain uses you may want or need to buy commercial licenses from MySQL AB at https://order.mysql.com/. See http://www.mysql.com/products/licensing.html for more information.

Older versions of MySQL (3.22 and earlier) are subject to a more strict license (http://www.mysql.com/products/mypl.html). See the documentation of the specific version for information. 古いバージョンの MySQL (3.22 とそれ以前) は より制限されたライセンスを有していることに気をつけて下さい (http://www.mysql.com/support/arrangements/mypl.html)。 より詳しくは、それぞれのバージョンに添付のドキュメントを御覧下さい。

Please note that the use of the MySQL software under commercial license, GPL, or the old MySQL license does not automatically give you the right to use MySQL AB trademarks. See section MySQL AB Logos and Trademarks.

Using the MySQL Software Under a Commercial License

The GPL license is contagious in the sense that when a program is linked to a GPL program all the source code for all the parts of the resulting product must also be released under the GPL. Otherwise you break the license terms and forfeit your right to use the GPL program altogether and also risk damages.

You need a commercial license:

If you require a license, you will need one for each installation of the MySQL software. This covers any number of CPUs on a machine, and there is no artificial limit on the number of clients that connect to the server in any way.

For commercial licenses, please visit our website at http://www.mysql.com/products/licensing.html. For support contracts, see http://www.mysql.com/support/. If you have special needs or you have restricted access to the Internet, please contact our sales staff at sales@mysql.com.

Using the MySQL Software for Free Under GPL

You can use the MySQL software for free under the GPL if you adhere to the conditions of the GPL. For more complete coverage of the common questions about the GPL see the generic FAQ from the Free Software Foundation at http://www.gnu.org/licenses/gpl-faq.html. Some common cases:

If your use of MySQL database software does not require a commercial license, we encourage you to purchase support from MySQL AB anyway. This way you contribute toward MySQL development and also gain immediate advantages for yourself. See section Support Offered by MySQL AB.

If you use the MySQL database software in a commercial context such that you profit by its use, we ask that you further the development of the MySQL software by purchasing some level of support. We feel that if the MySQL database helps your business, it is reasonable to ask that you help MySQL AB. (Otherwise, if you ask us support questions, you are not only using for free something into which we've put a lot a work, you're asking us to provide free support, too.)

MySQL AB Logos and Trademarks

Many users of the MySQL database want to display the MySQL AB dolphin logo on their web sites, books, or boxed products. We welcome and encourage this, although it should be noted that the word MySQL and the MySQL dolphin logo are trademarks of MySQL AB and may only be used as stated in our trademark policy at http://www.mysql.com/company/trademark.html.

The Original MySQL Logo

The MySQL dolphin logo was designed by the Finnish advertising agency Priority in 2001. The dolphin was chosen as a suitable symbol for the MySQL database since it is a smart, fast, and lean animal, effortlessly navigating oceans of data. We also happen to like dolphins.

The original MySQL logo may only be used by representatives of MySQL AB and by those having a written agreement allowing them to do so.

MySQL Logos that may be Used Without Written Permission

We have designed a set of special Conditional Use logos that may be downloaded from our web site at http://www.mysql.com/press/logos.html and used on third-party web sites without written permission from MySQL AB. The use of these logos is not entirely unrestricted but, as the name implies, subject to our trademark policy that is also available on our web site. You should read through the trademark policy if you plan to use them. The requirements are basically:

Contact us at trademark@mysql.com to inquire about special arrangements to fit your needs.

When do you need a Written Permission to use MySQL Logos?

In the following cases you need a written permission from MySQL AB before using MySQL logos:

Out of legal and commercial reasons we have to monitor the use of MySQL trademarks on products, books, etc. We will usually require a fee for displaying MySQL AB logos on commercial products, since we think it is reasonable that some of the revenue is returned to fund further development of the MySQL database.

MySQL AB Partnership Logos

MySQL partnership logos may only be used by companies and persons having a written partnership agreement with MySQL AB. Partnerships include certification as a MySQL trainer or consultant. Please see section Partnering.

Using the word MySQL in Printed Text or Presentations

MySQL AB welcomes references to the MySQL database, but note that the word MySQL is a trademark of MySQL AB. Because of this, you should append the trademark symbol (TM) to the first or most prominent use of the word MySQL in a text and where appropriate, state that MySQL is a trademark of MySQL AB. Please refer to our trademark policy at http://www.mysql.com/company/trademark.html for details.

Using the word MySQL in Company and Product Names

Use of the word MySQL in product or company names or in Internet domain names is not allowed without written permission from MySQL AB.

MySQL 4.x In A Nutshell

Long promised by MySQL AB and long awaited by our users, MySQL Server 4.0 is now available in beta version for download from http://www.mysql.com/ and our mirrors.

Main new features of MySQL Server 4.0 are geared toward our existing business and community users, enhancing the MySQL database software as the solution for mission-critical, heavy-load database systems. Other new features target the users of embedded databases.

Stepwise Rollout

MySQL is starting from 4.0.6 been labelled gamma, which means that 4.0.x has been available more than 2 months (first in alpha and then in beta) without any found serious hard to fix bugs and should now be ready for production use.

We will drop the gamma prefix when MySQL 4.0 has been out for more than a month without any serious bugs.

Further new features are being added in MySQL 4.1, which is now available from our bk source tree, and is targeted for alpha release in first quarter of 2003. See section 開発ソースツリーからのインストール.

Ready for Immediate Use

All binary releases pass our extensive test suite without any errors on any of the platforms we test on. MySQL 4.0 has been tested on by a large number of users and is in production used by several big sites.

組み込み MySQL

libmysqld makes MySQL Server suitable for a vastly expanded realm of applications. 組み込み MySQL サーバーライブラリを使用することで、 MySQL を色々なアプリケーション、電子機器 (それらにデータベースが利用されている事などは エンドユーザーが気にすることはない) に埋め込むことが可能です。 組み込み MySQL は、 インターネットのアプリケーションや、キオスク、 ハードウェア、ソフトウェアを組み合わせた物、 高パフォーマンスのインターネットサーバー、 CD-ROMに全てが収まっているデータベース、 などの裏方での利用に最適です。

Many users of libmysqld will benefit from the MySQL Dual Licensing. For those not wishing to be bound by the GPL, the software is also made available under a commercial license. The embedded MySQL library uses the same interface as the normal client library, so it is convenient and easy to use. See section libmysqld, the Embedded MySQL Server Library.

Other Features Available From MySQL 4.0

Future MySQL 4.x Features

For the upcoming MySQL Server 4.x releases, expect the following features now still under development:

MySQL 4.1, The Following Development Release

MySQL Server 4.0 lays the foundation for the new features of MySQL Server 4.1 and onward, such as nested subqueries (4.1), stored procedures (5.0), and foreign key integrity rules for MyISAM tables (5.0), which form the top of the wish list for many of our customers.

After those additions, critics of the MySQL Database Server have to be more imaginative than ever in pointing out deficiencies in the MySQL Database Management System. For long already known for its stability, speed, and ease of use, MySQL Server will then match the requirement checklist of very demanding buyers.

MySQL についての情報源

MySQL Mailing Lists

This section introduces you to the MySQL mailing lists, and gives some guidelines as to how to use them. By subscribing to a mailing list, you will receive as e-mail messages all other postings on the list, and you will be able to send in your own questions and answers.

MySQL メーリングリスト

メイン MySQL メーリングリストを購読するには、メッセージを 電子メールアドレス mysql-subscribe@lists.mysql.com に送ってください。

メイン MySQL メーリングリストの購読の中止は、メッセージを 電子メールアドレス mysql-unsubscribe@lists.mysql.com に送ってください。

メッセージを送る先のアドレスだけが重要です。メッセージのサブジェクトと 本文は無視されます。

もし、あなたのリプライアドレスが妥当な物でない場合、アドレスを明確に指定することが出来ます。 subscribe あるいは unsubscribe のあとにハイフンを付け、そのあとにあなたの アドレスを記述します。ただし `@' 文字は `=' に置き変えて書きます。 例えば、 your_name@host.domain で購読したい場合、 mysql-subscribe-your_name=host.domain@lists.mysql.com 宛にメッセージを送ります。

mysql-subscribe@lists.mysql.commysql-unsubscribe@lists.mysql.com へのメールは ezmlm メーリングリストプロセッサによって自動的に処理されます。 ezmlm についての情報は ezml ウェブサイトを参考してください (http://www.ezmlm.org/)

本メーリングリストへの投稿を行うには、mysql@lists.mysql.com にメッセージを送ります。 しかし、subscribe あるいは unsubscribe のメールを mysql@lists.mysql.com送らないでください。 これらのアドレスへ送られたメールは、何千ものユーザーに配送されてしまいます。

あなたのローカルサイトが多くの mysql@lists.mysql.com 購読者を持つことも あります。この場合、ローカルメーリングリストを作り、lists.mysql.com からの 一つのメッセージがそのサイトに送られ、ローカルなリストで複写されるように してください。この場合、ローカルの MySQL リストへの追加と削除は、 あなたのシステム管理者に問い合わせて下さい。

あなたのメーラーでMySQL メーリングリストからのメールを 適切なメールボックスへ振り分けるには、 (振り分け用の)フィルタをメッセージヘッダを頼りに動作するよう設定して下さい。 その場合、List-ID: ヘッダか Delivered-To: ヘッダが 識別の役に立つことでしょう。

次の MySQL メーリングリストがあります:

announce-subscribe@lists.mysql.com announce
これは MySQL と関連プログラムの新しいバージョンのアナウンスのためのリストです。 このリストの流量は少なく、我々は全ての MySQL ユーザがこのMLに入るべきだと考えています。
mysql-subscribe@lists.mysql.com mysql
MySQL についての一般的な議論のためのリストです。さらに専門的なリストに 行くべきものもあることに注意してください。間違ったリストに投稿しても、答 を得られないでしょう!
mysql-digest-subscribe@lists.mysql.com mysql-digest
ダイジェスト形式の mysql リストです。 このリストからは、一日分の全てのメッセージががまとめられた(ダイジェスト)形式で送られてきます。
bugs-subscribe@lists.mysql.com bugs
このリストには、完全で再現可能なバグレポートだけを、mysqlbug を使 用して投稿すべきです(Windows 上で実行している場合は、OS と MySQL バージョンの記述を含めるべきです)。 できれば投稿前にMySQL の最新の安定バージョンか開発バージョンを使用して 問題をテストしてください! 含められたテストケース上で、mysql test < script を使 用することで、誰もがバグを再現できるべきです。このリストに投稿された全て のバグは、次の MySQL リリースで修正されるかドキュメント化されま す! 小さなコードの変更だけですめば、我々はこの問題を修正するパッチの投 稿も行ないます。
bugs-digest-subscribe@lists.mysql.com bugs-digest
ダイジェスト形式の bugs リストです。
internals-subscribe@lists.mysql.com internals
MySQL コード上で作業する人のためのリストです。 このリストでもMySQL 開発の議論とパッチの投稿が可能です。
internals-digest-subscribe@lists.mysql.com internals-digest
internals リストのダイジェスト版です。
java-subscribe@lists.mysql.com java
MySQL server と Java についての議論。 多くは JDBC ドライバ (MySQL Connector/J 含む) についてです。
java-digest-subscribe@lists.mysql.com java-digest
java リストのダイジェスト版です。
win32-subscribe@lists.mysql.com win32
Win95, Win98, NT, Win2000 のような Microsoft OS 上の MySQL software に関連するリストです。
win32-digest-subscribe@lists.mysql.com win32-digest
win32 リストのダイジェスト版です。
myodbc-subscribe@lists.mysql.com myodbc
ODBC で MySQL server への接続に関連する全て。
myodbc-digest-subscribe@lists.mysql.com myodbc-digest
myodbc リストのダイジェスト版です。
mysqlcc-subscribe@lists.mysql.com mysqlcc
MySQL MySQL Control Center graphical client 全般についてのリストです。
mysqlcc-digest-subscribe@lists.mysql.com mysqlcc-digest
mysqlcc リストのダイジェスト版です。 A digest version of the mysqlcc list.
plusplus-subscribe@lists.mysql.com plusplus
MySQL の C++ API でのプログラミングについての全て。
plusplus-digest-subscribe@lists.mysql.com plusplus-digest
plusplus リストのダイジェスト版です。
msql-mysql-modules-subscribe@lists.mysql.com msql-mysql-modules
MySQL でサポートする Perl についてのリスト。msql-mysql-modules.
msql-mysql-modules-digest-subscribe@lists.mysql.com msql-mysql-modules-digest
msql-mysql-modules リストのダイジェスト版です。

上述したのと同じ方法で全てのリストの購読または購読中止ができます。あなた の購読または購読中止のメッセージは、mysql ではなく適切なメーリングリス トに送ってください。例えば、 myodbc リストを購読または購読中止するには、 myodbc-subscribe@lists.mysql.com または myodbc-unsubscribe@lists.mysql.com にメールを送ります。

メーリングリストから有益な回答が得られない場合、MySQL ABに 有料のサポートを求めることもできます。有料サポートが必要な場合、 MySQL 開発チームに直接御連絡下さい(See section Support Offered by MySQL AB)。

次の表は英語以外の MySQL メーリングリストを示します。注意: これら は MySQL AB によって運用されていません。そのため、我々はそれらの 品質を保証できません。

mysql-france-subscribe@yahoogroups.com フランス語メーリングリスト
list@tinc.net 韓国語メーリングリスト
このリストに subscribe mysql your@e-mail.address をメールしてください。
mysql-de-request@lists.4t2.com ドイツ語メーリングリスト
このリストに subscribe mysql-de your@e-mail.address をメールしてください。 これについては http://www.4t2.com/mysql で情報を見つけられます。
mysql-br-request@listas.linkway.com.br ポルトガル語メーリングリスト
このリストに subscribe mysql-br your@e-mail.address をメールしてください。
mysql-alta@elistas.net スペイン語メーリングリスト
このリストに subscribe mysql your@e-mail.address をメールしてください。

質問またはバグ報告

メーリングリストへ質問を尋ねる前に、以下の手順を踏んでください:

ここで回答が見つけられない場合は、近くの MySQL 熟練者ととも に調べて下さい。まだあなたの質問の回答が見つけられなければ、先に進み、次 のセクションの mysql@lists.mysql.com へメールを送る方法についてを読んで ください。

バグや問題を報告する方法

良いバグレポートを書くのは忍耐が要りますが、それを最初に正しく行なうこと は我々とあなたから時間を節約します。 そのバグについての完全なテストケースを含む良いバグレポートは、次のリリー スでそれが修正される可能性がとても高くなります。 この節では、かなりの、または全く我々 の助けにならないことにあなたの時間を浪費しないように、あなたがレポートを 正しく書くことを手助けします。

我々は、バグレポートまた可能ならば全ての問題についてのレポートの作成に mysqlbug スクリプトを使用することを奨励します。mysqlbug は ソース配布内の `scripts' ディレクトリ、または、バイナリ配布では MySQL をインストールしたディレクトリ配下の `bin' ディレク トリから見つけられます。mysqlbug を使用できない場合は、この節に挙 げられている全ての必要な情報を含めるべきです。

mysqlbug スクリプトは、下記の多くの情報を自動的に見つけ出すことで、 レポートの作成を手助けします。しかし、重要な何かが足りない場合、あなたの メッセージにそれを含めてください! この節を慎重に読んで、ここで述べられ ている全ての情報がレポート中に含まれていることを確認してください。

バグや問題を報告する通常の場所は、mysql@lists.mysql.com です。 バグを明確に示すテストケースを作ることができれば、 bugs@list.mysql.com リストにそれを投稿してください。注意: この リストには、完全で再現可能なバグ情報を mysqlbug スクリプトを使用 して投稿すべきです。 Windows 上で実行している場合は、OS と MySQL バージョンの記述を含めるべきです。できれば、投稿前に MySQL Server の最新の安定バージョンか開発バージョンを使用して問題をテ ストすべきです! 含められたテストケース上で、``mysql test < script'' を使 用することで、または、バグレポートに含められたシェル/Perlスクリプトを実 行することで、誰もがバグを再現できるべきです。この bugs リストに投稿された全て のバグは、次の MySQL リリースで修正されるかドキュメント化されま す! 小さなコードの変更だけですめば、我々はこの問題を修正するパッチの投 稿も行ないます。

多すぎる情報を含むメッセージに答えることはできますが、少なすぎる情報を含 むものにはできないということを覚えていてください。しばしば人は事実を省い てしまいます。問題の原因をわかっていると思い、いくつかの詳細を重大でない と見なしてしまうからです。良い原則は: 何かを言おうか迷ったときには、言っ てください! 最初にあなたが十分な情報を含めなかったために、再び質問して 回答を待つことを強要されるより、数行をあなたのレポートに書く方が千倍速く て迷惑ではありません。

良くある間違いは、使用している MySQL 配布のバージョン番号を示さ ない、または MySQL server をインストールしたプラットフォームを(プラッ トフォームのバージョン番号を含めて)示さない事です。これはとても関連した 情報で、100 のバグレポートのうち 99 の場合、この情報がないと役に立ちませ ん! 我々は ``何故私では動作しないの?'' のような質問をとても良く受けま す。そして我々は、要求された機能はその MySQL バージョンに実装さ れていない、または、レポート中に述べられているバグは新しい MySQL バージョンで既に修正されているであることを見つけます。時々、 エラーはプラットフォーム依存で、オペレーティングシステムとプラットフォー ムのバージョン番号を知らないことには、何も修正することはできません。

問題に関連している場合は、コンパイラについての情報も与えることを忘れない でください。しばしば人はコンパイラのバグを見つけて、問題は MySQL に関連していると考えます。多くのコンパイラはいつも開発中 で、バージョンを上げることによってより良いバージョンになります。問題がコ ンパイラに依存しているかどうかを確定するには、どのコンパイラが使用されて いるかを知ることが必要です。全てのコンパイルの問題はバグレポートとみなさ れ、それに従って報告されるべきであることに注意してください。

最も役に立つのは、問題の良い説明がバグレポートに含められることです。つま り、問題に導かれる全ての行なったことの例と、正確に記述された問題それ自身 です。良いバグレポートは、バグや問題を再現する方法を示す完全な例を含むも のです。See section Making a Test Case When You Experience Table Corruption.

問題がエラーメッセージを与える場合、それをレポートに含めることはとても重 要です! 我々がプログラムを使用するアーカイブから何かを検索しようとする 場合、エラーメッセージはプログラムが与えたものと正確に一致する方が良いで す(大文字小文字も守られるべきです!)。どのようなエラーメッセージだったか を覚えるなんてことはしてはいけません;レポートに完全なメッセージをコピー し張りつけてください。

MyODBC での問題がある場合、MyODBC トレースファイルの生成を試みるべきです。 See section Reporting Problems with MyODBC.

あなたのレポートを読む多くの人が 80桁ディスプレイを使用しているというこ とを覚えておいて下さい。従って、mysql コマンドラインツールを使用 してレポートまたはサンプルを生成する時、そのようなディスプレイの有効幅を 超える出力(例えば、EXPLAIN SELECT ステートメント; 後述のサンプル を見てください)には、--vertical オプション(または \G ステー トメント終端)を使用すべきです。

次の情報をレポートに含めてください:

もしあなたがサポート顧客なら、より高い優先度で取り扱われるように、バグレポー トを mysql-support@mysql.com と、そして同様に、他の誰かが問題を経 験済み(そして、もしかしたら解決済み)かどうかを調べるために、適切なメーリン グリストにもクロスポストしてください。

MyODBC のバグ報告上の情報については、section MyODBC での問題をどのように報告すべきか? を参照 してください。

いくつかの一般的な問題の解決法のために → section Problems and Common Errors.

回答があなたに個人的に送られて、メーリングリストに送られていない時、回答 を要約し、あなたの問題の解決の手助けになった返事の恩恵を他の人にも与える ために、その要約をメーリングリストに送信することは、良いエチケットです!

メーリングリストで質問に答えるためのガイドライン

あなたの回答が広く関心を持たれると考えられる場合、尋ねた人に個人的に直接 返事をする代わりに、メーリングリストに投稿したいと思うでしょう。オリジナ ルの投稿者以外の人もそれから恩恵を受けられるように十分一般的に回答を作成 することを試みてください。メーリングリストに投稿する場合は、あなたの回答 が以前の回答と重複していないか確認して下さい。

あなた返事の中で、質問の本質部分の要約を試みてください。質問全体を引用す ることを義務と感じないで下さい。

HTML モードを ON にしたブラウザからメールメッセージを投稿しないでくださ い! 多くのユーザはブラウザでメールを読んでいません!

MySQL Community Support on IRC (Internet Relay Chat)

In addition to the various MySQL mailing lists, you can find experienced community people on IRC (Internet Relay Chat). These are the best networks/channels currently known to us:

If you are looking for IRC client software to connect to an IRC network, take a peek at X-Chat (http://www.xchat.org/). X-Chat is available for Unix as well as for Windows platforms.

MySQL はどのように標準互換か?

この章では、MySQL がどのように ANSI SQL 標準に関係するかを説明し ます。MySQL Server は ANSI SQL 標準に対して多くの拡張を持ちます。そして、 ここでそれらが何か、またそれらの使用方法を見つけられるでしょう。また、 MySQL Server に足りない機能についての情報と、いくつかの違いを回避する方 法も見つけられるでしょう。

Our goal is to not, without a very good reason, restrict MySQL Server usability for any usage. Even if we don't have the resources to do development for every possible use, we are always willing to help and offer suggestions to people who are trying to use MySQL Server in new territories.

One of our main goals with the product is to continue to work toward ANSI 99 compliancy, but without sacrificing speed or reliability. We are not afraid to add extensions to SQL or support for non-SQL features if this greatly increases the usability of MySQL Server for a big part of our users. (The new HANDLER interface in MySQL Server 4.0 is an example of this strategy. See section HANDLER Syntax.)

We will continue to support transactional and non-transactional databases to satisfy both heavy web/logging usage and mission-critical 24/7 usage.

MySQL Server was designed from the start to work with medium size databases (10-100 million rows, or about 100 MB per table) on small computer systems. We will continue to extend MySQL Server to work even better with terabyte-size databases, as well as to make it possible to compile a reduced MySQL version that is more suitable for hand-held devices and embedded usage. The compact design of the MySQL server makes both of these directions possible without any conflicts in the source tree.

We are currently not targeting realtime support or clustered databases (even if you can already do a lot of things with our replication services).

We don't believe that one should have native XML support in the database, but will instead add the XML support our users request from us on the client side. We think it's better to keep the main server code as ``lean and clean'' as possible and instead develop libraries to deal with the complexity on the client side. This is part of the strategy mentioned previously of not sacrificing speed or reliability in the server.

What Standards Does MySQL Follow?

Entry-level SQL92. ODBC levels 0-3.51.

We are aiming toward supporting the full ANSI SQL99 standard, but without concessions to speed and quality of the code.

Running MySQL in ANSI Mode

If you start mysqld with the --ansi option, the following behaviour of MySQL Server changes:

This is the same as using --sql-mode=REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES, IGNORE_SPACE,SERIALIZE,ONLY_FULL_GROUP_BY.

MySQL の ANSI SQL92 に対する拡張

MySQL Server は、他の SQL データベース内に見られないであろう、いくつか の拡張を含んでいます。あなたがそれらを使用する場合、コードは他の SQL サー バに移行できなくなるので注意してください。いくつかのケースでは、形式 /*! ... */ のコメントを使用することで、MySQL 拡張を含む 移行可能コードを書くことができます。この場合、MySQL Server はコメント 内のコードを実行しますが、ほかのSQLサーバーはこれを無視します。例えば:

SELECT /*! STRAIGHT_JOIN */ col_name FROM table1,table2 WHERE ...

'!' の後ろにバージョン番号を追加すると、文法は MySQL バー ジョンが使用されるバージョン番号と等しいか大きい場合にのみ実行されます:

CREATE /*!32302 TEMPORARY */ TABLE t (a int);

上記は バージョン 3.23.02 かそれ以上の場合という意味で、そのとき MySQL Server は TEMPORARY キーワードを使用します。

MySQL 拡張を以下に示します:

MySQL と ANSI SQL92 との違い

我々は MySQL Server を ANSI SQL 標準と ODBC SQL 標準に従うように試みてい ますが、いくつかのケースで MySQL Server には何らかの違いがあります:

次の機能が MySQL Server の現在のバージョンにはありません。新しい拡張の 優先度については、次を参考にしてください http://www.mysql.com/doc/en/TODO.html. これはこのマニュアル中の TODO リストの最新バージョンです。 See section MySQL and The Future (The TODO).

SubSELECTs

MySQL Server until version 4.0 only supports nested queries of the form INSERT ... SELECT ... and REPLACE ... SELECT .... You can, however, use the function IN() in other contexts. Subselects are being implemented in the 4.1 development tree. Subqueries have been implemented in the 4.1 development tree.

しかし多くの場合、副問い合わせ を使わないクエリに書き直すことができます:

SELECT * FROM table1 WHERE id IN (SELECT id FROM table2);

This can be rewritten as:

SELECT table1.* FROM table1,table2 WHERE table1.id=table2.id;

The queries:

SELECT * FROM table1 WHERE id NOT IN (SELECT id FROM table2);
SELECT * FROM table1 WHERE NOT EXISTS (SELECT id FROM table2
                                       WHERE table1.id=table2.id);

Can be rewritten as:

SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id=table2.id
                                       WHERE table2.id IS NULL;

さらに複雑なサブクエリでは、サブクエリを保持するために一時テーブルを作成で きます。しかし、この方法でも動かない場合があります。このケースには、 DELETE ステートメントでもっとも頻繁に遭遇します。DELETE ステー トメントでは、標準 SQL では(sub select の中を除いて)join をサポートして いません。サブクエリが MySQL Server にサポートされるまで、この状況には2 つの選択肢があります。

最初の選択肢は、手続きプログラミング言語(Perl や PHP のような)を使用して、 SELECT クエリを発行して削除されるレコードのプライマリキーを獲得し、 それから DELETE ステートメント(DELETE FROM ... WHERE ... IN (key1, key2, ...))を構築するためにその値を使用することです。

二番目の選択肢は、対話型 SQL を使用し、DELETE ステートメントのセッ トを(標準 || オペレータの代わりに)MySQL 拡張 CONCAT() を使用して、自動的に組み立てることです。例えば:

SELECT CONCAT('DELETE FROM tab1 WHERE pkid = ', "'", tab1.pkid, "'", ';')
  FROM tab1, tab2
 WHERE tab1.col1 = tab2.col2;

このクエリをスクリプトファイル中に置き、入力を mysql コマンドライン インタプリタに切替え、その出力を二番目のインタプリタインスタンスにパイプし ます:

shell> mysql --skip-column-names mydb < myscript.sql | mysql mydb

MySQL Server 4.0 supports multi-table deletes that can be used to efficiently delete rows based on information from one table or even from many tables at the same time.

SELECT INTO TABLE

MySQL Server doesn't yet support the Oracle SQL extension: SELECT ... INTO TABLE .... MySQL Server supports instead the ANSI SQL syntax INSERT INTO ... SELECT ..., which is basically the same thing. See section INSERT ... SELECT 構文.

INSERT INTO tblTemp2 (fldID) SELECT tblTemp1.fldOrder_ID
       FROM tblTemp1 WHERE tblTemp1.fldOrder_ID > 100;

Alternatively, you can use SELECT INTO OUTFILE... or CREATE TABLE ... SELECT.

Transactions and Atomic Operations

MySQL Server supports transactions with the InnoDB and BDB Transactional table handlers. See section MySQL テーブル型. InnoDB provides ACID compliancy.

However, the non-transactional table types in MySQL Server such as MyISAM follow another paradigm for data integrity called ``Atomic Operations.'' アトミック・オペレーションが同等かあるいはより良いパフォーマンスを 提供するというのが、我々の経験、および考えです。 With MySQL Server supporting both paradigms, the user is able to decide if he needs the speed of atomic operations or if he need to use transactional features in his applications. This choice can be made on a per-table basis.

厳密に integrity 維持するには MySQL Server の機能をどのように使用するの でしょう? そして、トランザクション的パラダイムでこれらの機能をどのように 比較するのでしょう?

  1. トランザクションのパラダイムでは、 もし、あなたのアプリケーションが 基本となる部分で COMMIT の代わりに ROLLBACK の呼び出しに依存しているなら、 トランザクションはより便利になるでしょう。 おまけに、トランザクションは完了できなかった更新や不整合を起こした データが、確実にデータベースに登録されないようにできます。 そのサーバーには、自動的な rollback をする機会が与えられ、 あなたのデータは守られるでしょう。 MySQL Server はほとんどの場合、更新前の簡単なチェックを含ませることができたり、 あるいはデータベースの矛盾を検査して自動修復や警告の表示を行ったりする 簡単なスクリプトを実行することができるような、 ポテンシャルをあなたに提供します。 MySQL ログの使用や外部へのログの追加を行ったりする事で、 通常、データに不整合のおきたテーブルを完全に修復できることに注意してください。
  2. More often than not, fatal transactional updates can be rewritten to be atomic. Generally speaking, all integrity problems that transactions solve can be done with LOCK TABLES or atomic updates, ensuring that you never will get an automatic abort from the database, which is a common problem with transactional databases.
  3. もしサーバーがダウンすれば、たとえトランザクションでもデータを失います。 The difference between different systems lies in just how small the time-lap is where they could lose data. No system is 100% secure, only ``secure enough.'' Even Oracle, reputed to be the safest of transactional databases, is reported to sometimes lose data in such situations. MySQL Server を安全にするには、バックアップを取ることと、 更新ログを有効にすることだけです。 これで、あなたが他のトランザクションを持つデータベースで行っているような いかなる場面での修復が可能です。 もちろん、バックアップをとることは、どのデータベースを使用しているかに 関わらず、常に良いことです。

The transactional paradigm has its benefits and its drawbacks. Many users and application developers depend on the ease with which they can code around problems where an abort appears to be, or is necessary. However, even if you are new to the atomic operations paradigm, or more familiar with transactions, do consider the speed benefit that non-transactional tables can offer on the order of three to five times the speed of the fastest and most optimally tuned transactional tables.

In situations where integrity is of highest importance, MySQL Server offers transaction-level or better reliability and integrity even for non-transactional tables. If you lock tables with LOCK TABLES, all updates will stall until any integrity checks are made. If you only obtain a read lock (as opposed to a write lock), reads and inserts are still allowed to happen. The new inserted records will not be seen by any of the clients that have a read lock until they release their read locks. With INSERT DELAYED you can queue inserts into a local queue, until the locks are released, without having the client wait for the insert to complete. See section INSERT DELAYED 構文.

``Atomic,'' in the sense that we mean it, is nothing magical. It only means that you can be sure that while each specific update is running, no other user can interfere with it, and there will never be an automatic rollback (which can happen with transactional tables if you are not very careful). MySQL Server also guarantees that there will not be any dirty reads.

Following are some techniques for working with non-transactional tables:

ストアドプロシジャとトリガ

ストアドプロシジャは、サーバ内でコンパイルでき格納できる SQL コマンドの セットです。一度これが行なわれると、クライアントはクエリ全体の再発行を保 持する必要がなく、ストアドプロシジャを参照できます。これはさらにより速い速度を提 供します。クエリは一度だけ解釈され、より少ないデータがサーバとクライアン ト間で送信されるからです。サーバ内に関数ライブラリを持つことによりレ ベルを上げることもできます。

トリガは特別なイベントが発生した時に呼び出されるストアドプロシジャです。 例えば、トランザクションテーブルからレコードが削除される度にトリガされ、 それに対応する顧客を顧客テーブルから自動的に削除するという、 ストアドプロシジャをインストールすることができます。

The planned update language will be able to handle stored procedures. Our aim is to have stored procedures implemented in MySQL Server around version 5.0. We are also looking at triggers.

外部キー

注意: SQL の外部キーはテーブルを結合するためには使用できませんが、指示の 完全性の検査のために良く使用されます(foreign key constraints)。 SELECT ステートメントで複数 テーブルから結果を得たい場合、テーブルの結合によってこれを行ないます:

SELECT * FROM table1,table2 WHERE table1.id = table2.id;

See section JOIN 構文. See section Using Foreign Keys.

In MySQL Server 3.23.44 and up, InnoDB tables support checking of foreign key constraints. See section InnoDB テーブル (3.23.6以上). For other table types, MySQL Server does parse the FOREIGN KEY syntax in CREATE TABLE commands, but without further action being taken.

MySQL 内での FOREIGN KEY 構文は、他の SQL ベンダの CREATE TABLE コマンドとの互換のためだけに存在します; これは何も行 ないません。ON DELETE ... がない FOREIGN KEY 構文は、目的 の作成のために主に使われます。いくつかの ODBC アプリケーションは、自動的 に WHERE 節を提供するために、これを使用しますが、しかしこれは通常 簡単に無効にできます。FOREIGN KEY は時々強制チェックとして使用さ れます。しかし、テーブルに正しい順で行が挿入される場合、このチェックは実 際には不要です。いくつかのアプリケーションがそれが存在することを要求する ため MySQL はこれらの節だけをサポートします(それが動作するかど うかに関わらず)。

MySQL Server では、外部キーを持つテーブルからレコードを削除する時に適 切な DELETE ステートメントをアプリケーションに追加することで、 ON DELETE ... が実装されていないという問題を回避できます。実際に は、これは速く(いくつかの場合はより速く)そして外部キーの使用よりもさらに 可搬性があります。

In MySQL Server 4.0 you can use multi-table delete to delete rows from many tables with one command. See section DELETE 構文.

In the near future we will extend the FOREIGN KEY implementation so that the information will be saved in the table specification file and may be retrieved by mysqldump and ODBC. At a later stage we will implement the foreign key constraints for applications that can't easily be coded to avoid them.

Do keep in mind that foreign keys are often misused, which can cause severe problems. Even when used properly, it is not a magic solution for the referential integrity problem, although it does make things easier in some cases.

Some advantages of foreign key enforcement:

Disadvantages:

ビュー

It is planned to implement views in MySQL Server around version 5.0.

Views are mostly useful for letting users access a set of relations as one table (in read-only mode). Many SQL databases don't allow one to update any rows in a view, but you have to do the updates in the separate tables.

As MySQL Server is mostly used in applications and on web systems where the application writer has full control on the database usage, most of our users haven't regarded views to be very important. (At least no one has been interested enough in this to be prepared to finance the implementation of views.)

One doesn't need views in MySQL Server to restrict access to columns, as MySQL Server has a very sophisticated privilege system. See section General Security Issues and the MySQL Access Privilege System.

コメント開始としての `--'

他のいくつかの SQL データベースは、`--' をコメントの開始のために使 用します。MySQL Server は `#' をコメント開始文字とします。 mysql コマンドラインツールが `--' で始まる全ての行を削除した としてもです。MySQL では C コメントスタイル /* これはコメ ント */ も使用できます。See section コメント 構文

MySQL Server バージョン 3.23.3 以上は `--' をサポートしません; この退化したコメントスタイルは、次のコードのように !payment! の payment の値を自動的に挿入するような何かを使用して自動的に生成される SQL クエリで多くの問題を引き起こすためです:

UPDATE tbl_name SET credit=credit-!payment!

payment の値が負の場合に何が起きると思いますか? 1--1 は正しい SQL なので、我々は `--' をコメント開始と見なす ことはひどいことだと思います。

しかし MySQL Server バージョン 3.23 では次を使用できます: 1-- これはコメント

以降の説明では、バージョン 3.23 よりも前の MySQL を実行している場 合だけが対象です:

テキストファイルの SQL プログラムが `--' コメントを含んでいる場合、 次を使用すべきです:

shell> replace " --" " #" < text-file-with-funny-comments.sql \
         | mysql database

通常の次の代わりに:

shell> mysql database < text-file-with-funny-comments.sql

次の方法でも、コマンドファイル中の `--' コメントを `#' コメン トに変更できます:

shell> replace " --" " #" -- text-file-with-funny-comments.sql

それらは次のコマンドで戻してください:

shell> replace " #" " --" -- text-file-with-funny-comments.sql

Known Errors and Design Deficiencies in MySQL

Errors in 3.23 fixed in later MySQL version

The following known errors/bugs are not fixed in MySQL 3.23 because fixing them would involves changing a lot of code which could introduce other even worse bugs. The bugs are also classified as 'not fatal' or 'bearable'.

Open bugs / Design Deficiencies in MySQL

The following problems are known and have a high priority to get fixed:

The following problems are known and will be fixed in due time:

The following are known bugs in earlier versions of MySQL:

For platform-specific bugs, see the sections about compiling and porting.

MySQL and The Future (The TODO)

This section lists the features that we plan to implement in MySQL Server.

もしあなたが優先順位に影響を及ぼしたければ、どうかライセンスかサポート登録して、 我々にあなたがより速く欲しいものを言ってください。 See section MySQL ライセンスとサポート.

The plan is that we in the future will support the full ANSI SQL99 standard, but with a lot of useful extensions. The challenge is to do this without sacrificing the speed or compromising the code.

Things That Should be in 4.0

All done. We now only do bug fixes for MySQL 4.0. See section Changes in release 4.0.x (Gamma). Development has shifted to 4.1 & 5.0

Things That Should be in 4.1

The following features are planned for inclusion into MySQL 4.1. For a list what is already done in MySQL 4.1, see See section Changes in release 4.1.x (Alpha).

Things That Should be in 5.0

The following features are planned for inclusion into MySQL 5.0. Note that because we have many developers that are working on different projects, there will also be many additional features. There is also a small chance that some of these features will be added to MySQL 4.1. For a list what is already done in MySQL 4.1, see See section Changes in release 4.1.x (Alpha).

近い将来に完了せねばならないもの

いつかは行うべきもの

Time is given according to amount of work, not real time.

行う予定のない物

MySQL と他のオープンソースデータベースの比較

Our users have successfully run their own benchmarks against a number of Open Source and traditional database servers. We are aware of tests against Oracle server, DB/2 server, Microsoft SQL Server, and other commercial products. Due to legal reasons we are restricted from publishing some of those benchmarks in our reference manual.

This section includes a comparison with mSQL for historical reasons and with PostgreSQL as it is also an Open Source database. If you have benchmark results that we can publish, please contact us at benchmarks@mysql.com.

For comparative lists of all supported functions and types as well as measured operational limits of many different database systems, see the crash-me web page at http://www.mysql.com/information/crash-me.php.

How MySQL Compares to mSQL

Performance
真の速度比較のためは、増加する MySQL ベンチマークスイートを見て下さい See section The MySQL Benchmark Suite. Because there is no thread creation overhead, a small parser, few features, and simple security, mSQL should be quicker at: これらのオペレーションはとても単純なので、開始のオーバーヘッドが高くなる 時にそれらを良くするのは難しいです。接続が確立された後は MySQL はとても良い性能になります。 MySQL Server は mSQL や多くの他の SQL 実装よりとても速いです:
SQL Features
Disk Space Efficiency
これは、テーブルをどのように小さくできるかです。 MySQL はとても精密な型を持ちます。とても小さい領域を使用するテーブルを作成でき るためです。MySQL データ型の有用な例は、3バイト長の MEDIUMINT です。10,000,000 レコードを持つ場合、1レコードあたり1バイトの節約でもと ても重要です。 mSQL2 は4つの型(char,text,int,real)しかないので、小さなテーブルを 得るのは難しいです。
Stability
これを客観的に判断するのは難しいです。MySQL の安定性については section MySQL はどれくらい安定か? を参照してください。 我々には mSQL 安定性の経験がありません。そのため、我々はこれにつ いては何も言えません。
Price
もう一つの重要な問題はもちろんライセンスです。MySQL は mSQL よりも柔軟なライセンスを持っています。そして mSQL よ りもより安いです。少なくとも、あなたが使用を選択した製品全てに、ライセン スまたは email サポートへの支払いを考慮することを覚えていて下さい。 MySQL を含めた製品を売る場合、もちろんこのライセンスの獲得が要求 されます。
Perl Interfaces
MySQL は基本的に mSQL と同じ perl インタフェースと、いくつかの追 加機能を持ちます。
JDBC (Java)
MySQL Server currently has a lot of different JDBC drivers: The recommended driver is the mm driver. The Resin driver may also be good (at least the benchmarks look good), but we haven't received that much information about this yet. We know that mSQL has a JDBC driver, but we have too little experience with it to compare.
開発の速度
MySQL はとても小さい開発チームを持っていますが、我々は C と C++ のコーディ ングをとても速く行ないます。スレッド、関数、 GROUP BY などはまだ mSQL には実装されていませんので、it has a lot of chatching up to do. この上でいくつかの見通しを得るために、去年の mSQL `HISTORY' ファ イルを見て、MySQL Reference Manual News 節と比較できます(see section MySQL Change History)。 速く開発された多くのものが、かなり明白になります。
ユーティリティプログラム
mSQL と MySQL は多くの興味深いサードパーティツールを持っ ています。上位への移行 (mSQL -> MySQL) はとても簡単です。 MySQL は、ほとんど全ての興味深い mSQL アプリケーションを 持っています。 MySQL には、簡単な msql2mysql プログラムが用意されています。 これは、mSQL と MySQL の C API 関数のスペルの違いを修正するプログラムです。 For example, it changes instances of msqlConnect() to mysql_connect(). mSQL から MySQL への変換は通常、数分使用するだけです。

How to Convert mSQL Tools for MySQL

According to our experience, it doesn't take long to convert tools such as msql-tcl and msqljava that use the mSQL C API so that they work with the MySQL C API.

The conversion procedure is:

  1. シェルスクリプト msql2mysql をソースに実行します。バイナリプログラム replace が必要です。これは MySQL で配布されます。
  2. Compile.
  3. 全てのコンパイラエラーを修復します.

MySQL と mSQL 間の C API の違い:

How mSQL and MySQL Client/Server Communications Protocols Differ

There are enough differences that it is impossible (or at least not easy) to support both.

The most significant ways in which the MySQL protocol differs from the mSQL protocol are listed here:

How mSQL 2.0 SQL Syntax Differs from MySQL

Column types

MySQL Server
Has the following additional types (among others; see section CREATE TABLE 構文):
MySQL Server also supports the following additional type attributes:
mSQL2
mSQL column types correspond to the MySQL types shown in the following table:
mSQL type Corresponding MySQL type
CHAR(len) CHAR(len)
TEXT(len) TEXT(len). len is the maximal length. And LIKE works.
INT INT. With many more options!
REAL REAL. Or FLOAT. Both 4- and 8-byte versions are available.
UINT INT UNSIGNED
DATE DATE. Uses ANSI SQL format rather than mSQL's own format.
TIME TIME
MONEY DECIMAL(12,2). A fixed-point value with two decimals.

Index Creation

MySQL Server
Indexes may be specified at table creation time with the CREATE TABLE statement.
mSQL
Indexes must be created after the table has been created, with separate CREATE INDEX statements.

To Insert a Unique Identifier into a Table

MySQL Server
Use AUTO_INCREMENT as a column type specifier. See section mysql_insert_id().
mSQL
Create a SEQUENCE on a table and select the _seq column.

To Obtain a Unique Identifier for a Row

MySQL Server
Add a PRIMARY KEY or UNIQUE key to the table and use this. New in Version 3.23.11: If the PRIMARY or UNIQUE key consists of only one column and this is of type integer, one can also refer to it as _rowid.
mSQL
Use the _rowid column. Observe that _rowid may change over time depending on many factors.

To Get the Time a Column Was Last Modified

MySQL Server
Add a TIMESTAMP column to the table. This column is automatically set to the current date and time for INSERT or UPDATE statements if you don't give the column a value or if you give it a NULL value.
mSQL
Use the _timestamp column.

NULL Value Comparisons

MySQL Server
MySQL Server follows ANSI SQL, and a comparison with NULL is always NULL.
mSQL
In mSQL, NULL = NULL is TRUE. You must change =NULL to IS NULL and <>NULL to IS NOT NULL when porting old code from mSQL to MySQL Server.

String Comparisons

MySQL Server
Normally, string comparisons are performed in case-independent fashion with the sort order determined by the current character set (ISO-8859-1 Latin1 by default). If you don't like this, declare your columns with the BINARY attribute, which causes comparisons to be done according to the ASCII order used on the MySQL server host.
mSQL
All string comparisons are performed in case-sensitive fashion with sorting in ASCII order.

Case-insensitive Searching

MySQL Server
LIKE is a case-insensitive or case-sensitive operator, depending on the columns involved. If possible, MySQL uses indexes if the LIKE argument doesn't start with a wildcard character.
mSQL
Use CLIKE.

Handling of Trailing Spaces

MySQL Server
Strips all spaces at the end of CHAR and VARCHAR columns. Use a TEXT column if this behaviour is not desired.
mSQL
Retains trailing space.

WHERE Clauses

MySQL Server
MySQL correctly prioritises everything (AND is evaluated before OR). To get mSQL behaviour in MySQL Server, use parentheses (as shown in an example later in this section).
mSQL
Evaluates everything from left to right. This means that some logical calculations with more than three arguments cannot be expressed in any way. It also means you must change some queries when you upgrade to MySQL Server. You do this easily by adding parentheses. Suppose you have the following mSQL query:
mysql> SELECT * FROM table WHERE a=1 AND b=2 OR a=3 AND b=4;
To make MySQL Server evaluate this the way that mSQL would, you must add parentheses:
mysql> SELECT * FROM table WHERE (a=1 AND (b=2 OR (a=3 AND (b=4))));

Access Control

MySQL Server
Has tables to store grant (permission) options per user, host, and database. See section 特権システムはどのように動くか?.
mSQL
Has a file `mSQL.acl' in which you can grant read/write privileges for users.

How MySQL Compares to PostgreSQL

When reading the following, please note that both products are continually evolving. We at MySQL AB and the PostgreSQL developers are both working on making our respective databases as good as possible, so we are both a serious alternative to any commercial database.

The following comparison is made by us at MySQL AB. We have tried to be as accurate and fair as possible, but although we know MySQL Server thoroughly, we don't have a full knowledge of all PostgreSQL features, so we may have got some things wrong. We will, however, correct these when they come to our attention.

We would first like to note that PostgreSQL and MySQL Server are both widely used products, but with different design goals, even if we are both striving toward ANSI SQL compliancy. This means that for some applications MySQL Server is more suited, while for others PostgreSQL is more suited. When choosing which database to use, you should first check if the database's feature set satisfies your application. If you need raw speed, MySQL Server is probably your best choice. If you need some of the extra features that only PostgreSQL can offer, you should use PostgreSQL.

MySQL and PostgreSQL development strategies

When adding things to MySQL Server we take pride to do an optimal, definite solution. The code should be so good that we shouldn't have any need to change it in the foreseeable future. We also do not like to sacrifice speed for features but instead will do our utmost to find a solution that will give maximal throughput. This means that development will take a little longer, but the end result will be well worth this. This kind of development is only possible because all server code are checked by one of a few (currently two) persons before it's included in the MySQL server.

We at MySQL AB believe in frequent releases to be able to push out new features quickly to our users. Because of this we do a new small release about every three weeks, and a major branch every year. All releases are thoroughly tested with our testing tools on a lot of different platforms.

PostgreSQL is based on a kernel with lots of contributors. In this setup it makes sense to prioritise adding a lot of new features, instead of implementing them optimally, because one can always optimise things later if there arises a need for this.

Another big difference between MySQL Server and PostgreSQL is that nearly all of the code in the MySQL server is coded by developers that are employed by MySQL AB and are still working on the server code. The exceptions are the transaction engines and the regexp library.

This is in sharp contrast to the PostgreSQL code, the majority of which is coded by a big group of people with different backgrounds. It was only recently that the PostgreSQL developers announced that their current developer group had finally had time to take a look at all the code in the current PostgreSQL release.

Both of the aforementioned development methods have their own merits and drawbacks. We here at MySQL AB think, of course, that our model is better because our model gives better code consistency, more optimal and reusable code, and in our opinion, fewer bugs. Because we are the authors of the MySQL server code, we are better able to coordinate new features and releases.

Featurewise Comparison of MySQL and PostgreSQL

On the crash-me page (http://www.mysql.com/information/crash-me.php) you can find a list of those database constructs and limits that one can detect automatically with a program. Note, however, that a lot of the numerical limits may be changed with startup options for their respective databases. This web page is, however, extremely useful when you want to ensure that your applications work with many different databases or when you want to convert your application from one database to another.

MySQL Server offers the following advantages over PostgreSQL:

Drawbacks with MySQL Server compared to PostgreSQL:

PostgreSQL currently offers the following advantages over MySQL Server:

Note that because we know the MySQL road map, we have included in the following table the version when MySQL Server should support this feature. Unfortunately we couldn't do this for previous comparisons, because we don't know the PostgreSQL roadmap.

Feature MySQL version
Subqueries 4.1
Foreign keys 5.0 (3.23 with InnoDB)
Views 5.0
Stored procedures 5.0
Triggers 5.0
Unions 4.0
Full join 4.1
Constraints 4.1 or 5.0
Cursors 4.1 or 5.0
R-trees 4.1 (for MyISAM tables)
Inherited tables Not planned
Extensible type system Not planned

Other reasons someone may consider using PostgreSQL:

Drawbacks with PostgreSQL compared to MySQL Server:

For a complete list of drawbacks, you should also examine the first table in this section.

Benchmarking MySQL and PostgreSQL

The only Open Source benchmark that we know of that can be used to benchmark MySQL Server and PostgreSQL (and other databases) is our own. It can be found at http://www.mysql.com/information/benchmarks.html.

We have many times asked the PostgreSQL developers and some PostgreSQL users to help us extend this benchmark to make it the definitive benchmark for databases, but unfortunately we haven't gotten any feedback for this.

We, the MySQL developers, have, because of this, spent a lot of hours to get maximum performance from PostgreSQL for the benchmarks, but because we don't know PostgreSQL intimately, we are sure that there are things that we have missed. We have on the benchmark page documented exactly how we did run the benchmark so that it should be easy for anyone to repeat and verify our results.

The benchmarks are usually run with and without the --fast option. When run with --fast we are trying to use every trick the server can do to get the code to execute as fast as possible. The idea is that the normal run should show how the server would work in a default setup and the --fast run shows how the server would do if the application developer would use extensions in the server to make his application run faster.

When running with PostgreSQL and --fast we do a VACUUM after every major table UPDATE and DROP TABLE to make the database in perfect shape for the following SELECTs. The time for VACUUM is measured separately.

When running with PostgreSQL 7.1.1 we could, however, not run with --fast because during the INSERT test, the postmaster (the PostgreSQL daemon) died and the database was so corrupted that it was impossible to restart postmaster. After this happened twice, we decided to postpone the --fast test until the next PostgreSQL release. The details about the machine we run the benchmark on can be found on the benchmark page.

Before going to the other benchmarks we know of, we would like to give some background on benchmarks.

It's very easy to write a test that shows any database to be the best database in the world, by just restricting the test to something the database is very good at and not testing anything that the database is not good at. If one, after doing this, summarises the result as a single figure, things are even easier.

This would be like us measuring the speed of MySQL Server compared to PostgreSQL by looking at the summary time of the MySQL benchmarks on our web page. Based on this MySQL Server would be more than 40 times faster than PostgreSQL, something that is, of course, not true. We could make things even worse by just taking the test where PostgreSQL performs worst and claim that MySQL Server is more than 2000 times faster than PostgreSQL.

The case is that MySQL does a lot of optimisations that PostgreSQL doesn't do. This is, of course, also true the other way around. An SQL optimiser is a very complex thing, and a company could spend years just making the optimiser faster and faster.

When looking at the benchmark results you should look for things that you do in your application and just use these results to decide which database would be best suited for your application. The benchmark results also show things a particular database is not good at and should give you a notion about things to avoid and what you may have to do in other ways.

We know of two benchmark tests that claim that PostgreSQL performs better than MySQL Server. These both where multi-user tests, a test that we here at MySQL AB haven't had time to write and include in the benchmark suite, mainly because it's a big task to do this in a manner that is fair to all databases.

One is the benchmark paid for by Great Bridge, the company that for 16 months attempted to build a business based on PostgreSQL but now has ceased operations. This is probably the worst benchmark we have ever seen anyone conduct. This was not only tuned to only test what PostgreSQL is absolutely best at, but it was also totally unfair to every other database involved in the test.

Note: We know that even some of the main PostgreSQL developers did not like the way Great Bridge conducted the benchmark, so we don't blame the PostgreSQL team for the way the benchmark was done.

This benchmark has been condemned in a lot of postings and newsgroups, so here we will just briefly repeat some things that were wrong with it.

Tim Perdue, a long-time PostgreSQL fan and a reluctant MySQL user, published a comparison on PHPbuilder (http://www.phpbuilder.com/columns/tim20001112.php3).

When we became aware of the comparison, we phoned Tim Perdue about this because there were a lot of strange things in his results. For example, he claimed that MySQL Server had a problem with five users in his tests, when we know that there are users with similar machines as his that are using MySQL Server with 2000 simultaneous connections doing 400 queries per second. (In this case the limit was the web bandwidth, not the database.)

It sounded like he was using a Linux kernel that either had some problems with many threads, such as kernels before 2.4, which had a problem with many threads on multi-CPU machines. We have documented in this manual how to fix this and Tim should be aware of this problem.

The other possible problem could have been an old glibc library and that Tim didn't use a MySQL binary from our site, which is linked with a corrected glibc library, but had compiled a version of his own. In any of these cases, the symptom would have been exactly what Tim had measured.

We asked Tim if we could get access to his data so that we could repeat the benchmark and if he could check the MySQL version on the machine to find out what was wrong and he promised to come back to us about this. He has not done that yet.

Because of this we can't put any trust in this benchmark either. :(

Over time things also change and the preceding benchmarks are not that relevant anymore. MySQL Server now has a couple of different storage engines with different speed/concurrency tradeoffs. See section MySQL テーブル型. It would be interesting to see how the above tests would run with the different transactional table types in MySQL Server. PostgreSQL has, of course, also got new features since the test was made. As these tests are not publicly available there is no way for us to know how the database would perform in the same tests today.

Conclusion:

The only benchmarks that exist today that anyone can download and run against MySQL Server and PostgreSQL are the MySQL benchmarks. We here at MySQL AB believe that Open Source databases should be tested with Open Source tools! This is the only way to ensure that no one does tests that nobody can reproduce and use this to claim that one database is better than another. Without knowing all the facts it's impossible to answer the claims of the tester.

The thing we find strange is that every test we have seen about PostgreSQL, that is impossible to reproduce, claims that PostgreSQL is better in most cases while our tests, which anyone can reproduce, clearly show otherwise. With this we don't want to say that PostgreSQL isn't good at many things (it is!) or that it isn't faster than MySQL Server under certain conditions. We would just like to see a fair test where PostgreSQL performs very well, so that we could get some friendly competition going!

For more information about our benchmark suite, see section The MySQL Benchmark Suite.

We are working on an even better benchmark suite, including multi-user tests, and a better documentation of what the individual tests really do and how to add more tests to the suite.

MySQL のインストール

この章では、どのようにして MySQL を得、インストールするのかをのべます:

Quick Standard Installation of MySQL

Installing MySQL on Linux

(訳注:もし RedHat 以外の Linux を使用しており、.rpm を、自分が使用している パッケージ管理システムの管理下におきたい場合、 alien : http://kitenet.net/programs/alien/ というツールを 使用します。これは RPM(Debian, Slackware) を自分が使用しているパッケージの形式に変換してくれます。)

RPM を使用して MySQL をインストールすることを推奨します。 MySQL RPM は SuSE Linux 7.3 で作成していますが、 他の rpmglibc をサポートしている Linux でも動作するでしょう。

RPM file での問題, 例えば, ``Sorry, the host 'xxxx' could not be looked up'' に遭遇した場合には → section Linux Notes for Binary Distributions.

以下が使用するであろう RPM files です:

To see all files in an RPM package, run:

shell> rpm -qpl MySQL-VERSION.i386.rpm

インストールの最小の方法:

shell> rpm -i MySQL-server-VERSION.i386.rpm MySQL-client-VERSION.i386.rpm

クライアントパッケージだけをインストール:

shell> rpm -i MySQL-client-VERSION.i386.rpm

RPM はデータを `/var/lib/mysql' に保存します。 RPM は起動時にサーバーを立ちあげるように、`/etc/init.d/' に登録します。 (以前にインストールがされていて、前にインストールされた MySQL 起 動ファイルを何か変更している場合、それをコピーしておいた方がいいでしょう。 そうすればその変更を失うことはありません。)

If you want to install the MySQL RPM on older Linux distributions that do not support init scripts in `/etc/init.d' (directly or via a symlink), you should create a symbolic link pointing to the old location before installing the RPM:

shell> cd /etc ; ln -s rc.d/init.d .

However, all current major Linux distributions should already support this new directory layout as it is required for LSB (Linux Standard Base) compliance.

RPM ファイルのインストール後は、mysqld デーモンが実行されていて、 MySQL の使用を開始することができます。 See section インストール後の設定とテスト.

うまくいかない場合、バイナリインストールの章でさらに情報を探すことができま す。 See section Installing a MySQL Binary Distribution.

Windows への MySQL のインストール

Windows用の MySQLサーバ には,2つの配布形態があります。:

  1. バイナリ配布は,セットアッププログラムが含まれ,必要な全てのインストール作業を行い, あなたは直ぐにサーバをスタートさせることができます。
  2. The source distribution contains all the code and support files for building the executables using the VC++ 6.0 compiler. See section Windows Source Distribution.

大雑把な言い方をすると,バイナリ配布を使用する方がいいでしょう。

You will need the following:

Installing the Binaries

  1. If you are working on an NT/2000/XP server, logon as a user with administrator privileges.
  2. If you are doing an upgrade of an earlier MySQL installation, it is necessary to stop the server. If you are running the server as a service, use:
    C:\> NET STOP MySQL
    
    Otherwise, use:
    C:\mysql\bin> mysqladmin -u root shutdown
    
  3. On NT/2000/XP machines, if you want to change the server executable (e.g., -max or -nt), it is also necessary to remove the service:
    C:\mysql\bin> mysqld-max-nt --remove
    
  4. Unzip the distribution file to a temporary directory.
  5. Run the `setup.exe' file to begin the installation process. If you want to install into another directory than the default `c:\mysql', use the Browse button to specify your preferred directory.
  6. Finish the install process.

Preparing the Windows MySQL Environment

Starting with MySQL 3.23.38, the Windows distribution includes both the normal and the MySQL-Max server binaries. Here is a list of the different MySQL servers you can use:

Binary Description
mysqld Compiled with full debugging and automatic memory allocation checking, symbolic links, InnoDB, and BDB tables.
mysqld-opt Optimised binary with no support for transactional tables.
mysqld-nt Optimised binary for NT/2000/XP with support for named pipes. You can run this version on Windows 9x/Me, but in this case no named pipes are created and you must have TCP/IP installed.
mysqld-max Optimised binary with support for symbolic links, InnoDB and BDB tables.
mysqld-max-nt Like mysqld-max, but compiled with support for named pipes.

Starting from 3.23.50, named pipes are only enabled if one starts mysqld with --enable-named-pipe.

All of the preceding binaries are optimised for the Pentium Pro processor but should work on any Intel processor >= i386.

You will need to use an option file to specify your MySQL configuration under the following circumstances:

Normally you can use the WinMySQLAdmin tool to edit the option file my.ini. In this case you don't have to worry about the following section.

There are two option files with the same function: `my.cnf' and `my.ini'. However, to avoid confusion, it's best if you use only of one them. Both files are plain text. The `my.cnf' file, if used, should be created in the root directory of the C drive. The `my.ini' file, if used, should be created in the Windows system directory. (This directory is typically something like `C:\WINDOWS' or `C:\WINNT'. You can determine its exact location from the value of the windir environment variable.) MySQL looks first for the my.ini file, then for the `my.cnf' file.

If your PC uses a boot loader where the C drive isn't the boot drive, your only option is to use the `my.ini' file. Also note that if you use the WinMySQLAdmin tool, it uses only the `my.ini' file. The `\mysql\bin' directory contains a help file with instructions for using this tool.

Using notepad.exe, create the option file and edit the [mysqld] section to specify values for the basedir and datadir parameters:

[mysqld]
# set basedir to installation path, e.g., c:/mysql
basedir=the_install_path
# set datadir to location of data directory,
# e.g., c:/mysql/data or d:/mydata/data
datadir=the_data_path

Note that Windows pathnames should be specified in option files using forward slashes rather than backslashes. If you do use backslashes, you must double them.

If you would like to use a data directory different from the default of `c:\mysql\data', you must copy the entire contents of the `c:\mysql\data' directory to the new location.

If you want to use the InnoDB transactional tables, you need to manually create two new directories to hold the InnoDB data and log files@-e.g., `c:\ibdata' and `c:\iblogs'. You will also need to add some extra lines to the option file. See section InnoDB 起動オプション.

If you don't want to use InnoDB tables, add the skip-innodb option to the option file.

Now you are ready to test starting the server.

Starting the Server for the First Time

Testing from a DOS command prompt is the best thing to do because the server displays status messages that appear in the DOS window. If something is wrong with your configuration, these messages will make it easier for you to identify and fix any problems.

Make sure you are in the directory where the server is located, then enter this command:

C:\mysql\bin> mysqld-max --standalone

You should see the following messages as the server starts up:

InnoDB: The first specified datafile c:\ibdata\ibdata1 did not exist:
InnoDB: a new database to be created!
InnoDB: Setting file c:\ibdata\ibdata1 size to 209715200
InnoDB: Database physically writes the file full: wait...
InnoDB: Log file c:\iblogs\ib_logfile0 did not exist: new to be created
InnoDB: Setting log file c:\iblogs\ib_logfile0 size to 31457280
InnoDB: Log file c:\iblogs\ib_logfile1 did not exist: new to be created
InnoDB: Setting log file c:\iblogs\ib_logfile1 size to 31457280
InnoDB: Log file c:\iblogs\ib_logfile2 did not exist: new to be created
InnoDB: Setting log file c:\iblogs\ib_logfile2 size to 31457280
InnoDB: Doublewrite buffer not found: creating new
InnoDB: Doublewrite buffer created
InnoDB: creating foreign key constraint system tables
InnoDB: foreign key constraint system tables created
011024 10:58:25  InnoDB: Started

For further information about running MySQL on Windows, see section Windows Notes.

Installing MySQL on Mac OS X

Beginning with MySQL 4.0.11, you can install MySQL on Mac OS X 10.2 ("Jaguar") using a Mac OS X PKG binary package instead of the binary tarball distribution. Please note that older versions of Mac OS X (e.g. 10.1.x) are not supported by this package!

The package is located inside a disk image (.dmg) file, that you first need to mount by double-clicking its icon in the Finder. It should then mount the image and display its contents.

NOTE: Before proceeding with the installation, please make sure that no other MySQL server is running!

Please shut down all running MySQL instances before continuing by either using the MySQL Manager Application (on Mac OS X Server) or via mysqladmin shutdown on the command line.

To actually install the MySQL PKG, double click on the package icon. This will launch the Mac OS Package Installer, which will guide you through the installation of MySQL.

The Mac OS X PKG of MySQL will install itself into `/usr/local/mysql-<version>' and will also install a symbolic link `/usr/local/mysql', pointing to the new location. If a directory named `/usr/local/mysql' already exists, it will be renamed to `/usr/local/mysql.bak' first. Additionally, it will install the mysql grant tables by executing mysql_install_db after the installation.

The installation layout is similar to the one of the binary distribution, all MySQL binaries are located in directory `/usr/local/mysql/bin'. The MySQL socket will be put into `/etc/mysql.sock' by default. See section インストールレイアウト.

It requires a user account named mysql (which should exist by default on Mac OS X 10.2 and up).

If you are running Mac OS X Server, you already have a version of MySQL installed:

This manual section covers the installation of the official MySQL Mac OS X PKG only. Make sure to read Apple's help about installing MySQL (Run the "Help View" application, select "Mac OS X Server" help, and do a search for "MySQL" and read the item entitled "Installing MySQL").

Especially note, that the pre-installed version of MySQL on Mac OS X Server is being started with the command safe_mysqld instead of mysqld_safe!

If you previously used Marc Liyanage's MySQL packages for Mac OS X from http://www.entropy.ch, you can simply follow the update instructions for packages using the binary installation layout as given on his pages.

If you are upgrading from Marc's version or from the Mac OS X Server version of MySQL to the official MySQL PKG, you also need to convert the existing MySQL privilege tables. See section バージョン 3.23 から バージョン 4.0 へのアップグレード.

After the installation, you can start up MySQL by running the following commands in a terminal window. Please note that you need to have administrator privileges to perform this task!

shell> cd /usr/local/mysql
shell> sudo ./bin/mysqld_safe
(Enter your password)
(Press CTRL+Z)
shell> bg
(Press CTRL+D to exit the shell)

You should now be able to connect to the MySQL server, e.g. by running `/usr/local/mysql/bin/mysql'.

To enable the automatic startup of MySQL on bootup, you can download Marc Liyanage's MySQL StartupItem from the following location:

http://www2.entropy.ch/download/mysql-startupitem.pkg.tar.gz

We plan to add a StartupItem to the official MySQL PKG in the near future.

Please note that installing a new MySQL PKG does not remove the directory of an older installation - unfortunately the Mac OS X Installer does not yet offer the functionality required to properly upgrade previously installed packages. After you have copied over the MySQL database files from the previous version and have successfully started the new version, you should consider removing the old installation files to save up disk space. Additionally, you should also remove older versions of the Package Receipt directories located in `/Library/Receipts/mysql-<version>.pkg'.

General Installation Issues

MySQL を得る方法

現在のバージョンとダウンロードの指示についての情報は MySQL ウェブページ (http://www.mysql.com/) をチェックしてください。

主なダウンロードミラーはここにあります: http://mirrors.sunsite.dk/mysql/. For a complete upto-date list of MySQL web/download mirrors, see http://www.mysql.com/downloads/mirrors.html. There you will also find information about becoming a MySQL mirror site and how to report a bad or out-of-date mirror.

Verifying Package Integrity Using MD5 Checksums or GnuPG

After you have downloaded the MySQL package that suits your needs and before you attempt to install it, you should make sure it is intact and has not been tampered with.

MySQL AB offers two means of integrity checking: MD5 checksums and cryptographic signatures using GnuPG, the GNU Privacy Guard.

Verifying the MD5 Checksum

After you have downloaded the package, you should check, if the MD5 checksum matches the one provided on the MySQL download pages. Each package has an individual checksum, that you can verify with the following command:

shell> md5sum <package>

Note, that not all operating systems support the md5sum command - on some it is simply called md5, others do not ship it at all. On Linux, it is part of the GNU Text Utilities package, which is available for a wide range of platforms. You can download the source code from http://www.gnu.org/software/textutils/ as well. If you have OpenSSL installed, you can also use the command openssl md5 <package> instead. A DOS/Windows implementation of the md5 command is available from http://www.fourmilab.ch/md5/.

Example:

shell> md5sum mysql-standard-4.0.10-gamma-pc-linux-i686.tar.gz
155836a7ed8c93aee6728a827a6aa153
                mysql-standard-4.0.10-gamma-pc-linux-i686.tar.gz

You should check, if the resulting checksum matches the one printed on the download page right below the respective package.

Most mirror sites also offer a file named `MD5SUMS', which also includes the MD5 checksums for all files included in the `Downloads' directory. Please note however that it's very easy to modify this file and it's not a very reliable method! If in doubt, you should consult different mirror sites and compare the results.

Signature Checking Using GnuPG

A more reliable method of verifying the integrity of a package is using cryptographic signatures. MySQL AB uses the GNU Privacy Guard (GnuPG), an Open Source alternative to the very well-known Pretty Good Privacy (PGP) by Phil Zimmermann. See http://www.gnupg.org/ and http://www.openpgp.org/ for more information about OpenPGP/GnuPG and how to obtain and install GnuPG on your system. Most Linux distributions already ship with GnuPG installed by default.

Beginning with MySQL 4.0.10 (February 2003), MySQL AB has started signing their downloadable packages with GnuPG. Cryptographic signatures are a much more reliable method of verifying the integrity and authenticity of a file.

To verify the signature for a specific package, you first need to obtain a copy of MySQL AB's public GPG build key build@mysql.com. You can either cut and paste it directly from here, or obtain it from http://www.keyserver.net/.

Key ID:
pub  1024D/5072E1F5 2003-02-03
     MySQL Package signing key (www.mysql.com) <build@mysql.com>
Fingerprint: A4A9 4068 76FC BD3C 4567  70C8 8C71 8D3B 5072 E1F5

Public Key (ASCII-armored):

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

mQGiBD4+owwRBAC14GIfUfCyEDSIePvEW3SAFUdJBtoQHH/nJKZyQT7h9bPlUWC3
RODjQReyCITRrdwyrKUGku2FmeVGwn2u2WmDMNABLnpprWPkBdCk96+OmSLN9brZ
fw2vOUgCmYv2hW0hyDHuvYlQA/BThQoADgj8AW6/0Lo7V1W9/8VuHP0gQwCgvzV3
BqOxRznNCRCRxAuAuVztHRcEAJooQK1+iSiunZMYD1WufeXfshc57S/+yeJkegNW
hxwR9pRWVArNYJdDRT+rf2RUe3vpquKNQU/hnEIUHJRQqYHo8gTxvxXNQc7fJYLV
K2HtkrPbP72vwsEKMYhhr0eKCbtLGfls9krjJ6sBgACyP/Vb7hiPwxh6rDZ7ITnE
kYpXBACmWpP8NJTkamEnPCia2ZoOHODANwpUkP43I7jsDmgtobZX9qnrAXw+uNDI
QJEXM6FSbi0LLtZciNlYsafwAPEOMDKpMqAK6IyisNtPvaLd8lH0bPAnWqcyefep
rv0sxxqUEMcM3o7wwgfN83POkDasDbs3pjwPhxvhz6//62zQJ7Q7TXlTUUwgUGFj
a2FnZSBzaWduaW5nIGtleSAod3d3Lm15c3FsLmNvbSkgPGJ1aWxkQG15c3FsLmNv
bT6IXQQTEQIAHQUCPj6jDAUJCWYBgAULBwoDBAMVAwIDFgIBAheAAAoJEIxxjTtQ
cuH1cY4AnilUwTXn8MatQOiG0a/bPxrvK/gCAJ4oinSNZRYTnblChwFaazt7PF3q
zIhMBBMRAgAMBQI+PqPRBYMJZgC7AAoJEElQ4SqycpHyJOEAn1mxHijft00bKXvu
cSo/pECUmppiAJ41M9MRVj5VcdH/KN/KjRtW6tHFPYhMBBMRAgAMBQI+QoIDBYMJ
YiKJAAoJELb1zU3GuiQ/lpEAoIhpp6BozKI8p6eaabzF5MlJH58pAKCu/ROofK8J
Eg2aLos+5zEYrB/LsrkCDQQ+PqMdEAgA7+GJfxbMdY4wslPnjH9rF4N2qfWsEN/l
xaZoJYc3a6M02WCnHl6ahT2/tBK2w1QI4YFteR47gCvtgb6O1JHffOo2HfLmRDRi
Rjd1DTCHqeyX7CHhcghj/dNRlW2Z0l5QFEcmV9U0Vhp3aFfWC4Ujfs3LU+hkAWzE
7zaD5cH9J7yv/6xuZVw411x0h4UqsTcWMu0iM1BzELqX1DY7LwoPEb/O9Rkbf4fm
Le11EzIaCa4PqARXQZc4dhSinMt6K3X4BrRsKTfozBu74F47D8Ilbf5vSYHbuE5p
/1oIDznkg/p8kW+3FxuWrycciqFTcNz215yyX39LXFnlLzKUb/F5GwADBQf+Lwqq
a8CGrRfsOAJxim63CHfty5mUc5rUSnTslGYEIOCR1BeQauyPZbPDsDD9MZ1ZaSaf
anFvwFG6Llx9xkU7tzq+vKLoWkm4u5xf3vn55VjnSd1aQ9eQnUcXiL4cnBGoTbOW
I39EcyzgslzBdC++MPjcQTcA7p6JUVsP6oAB3FQWg54tuUo0Ec8bsM8b3Ev42Lmu
QT5NdKHGwHsXTPtl0klk4bQk4OajHsiy1BMahpT27jWjJlMiJc+IWJ0mghkKHt92
6s/ymfdf5HkdQ1cyvsz5tryVI3Fx78XeSYfQvuuwqp2H139pXGEkg0n6KdUOetdZ
Whe70YGNPw1yjWJT1IhMBBgRAgAMBQI+PqMdBQkJZgGAAAoJEIxxjTtQcuH17p4A
n3r1QpVC9yhnW2cSAjq+kr72GX0eAJ4295kl6NxYEuFApmr1+0uUq/SlsQ==
=YJkx
-----END PGP PUBLIC KEY BLOCK-----

You can import this key into your public GPG keyring by using gpg --import. See the GPG documentation for more info on how to work with public keys.

After you have downloaded and imported the public build key, now download your desired MySQL package and the corresponding signature, which is also available from the download page. The signature has the file name extension `.asc'. For example, the signature for `mysql-standard-4.0.10-gamma-pc-linux-i686.tar.gz' would be `mysql-standard-4.0.10-gamma-pc-linux-i686.tar.gz.asc'. Make sure that both files are stored in the same directory and then run the following command to verify the signature for this file:

shell> gpg --verify <package>.asc

Example:

shell> gpg --verify mysql-standard-4.0.10-gamma-pc-linux-i686.tar.gz.asc
gpg: Warning: using insecure memory!
gpg: Signature made Mon 03 Feb 2003 08:50:39 PM MET using DSA key ID 5072E1F5
gpg: Good signature from
     "MySQL Package signing key (www.mysql.com) <build@mysql.com>"

The "Good signature" message indicates that everything is all right.

For RPM packages, there is no separate signature - RPM packages actually have a built-in GPG signature and MD5 checksum. You can verify them by running the following command:

shell> rpm --checksig <package>.rpm

Example:

shell> rpm --checksig MySQL-server-4.0.10-0.i386.rpm
MySQL-server-4.0.10-0.i386.rpm: md5 gpg OK

Note: If you are using RPM 4.1 and it complains about (GPG) NOT OK (MISSING KEYS: GPG#5072e1f5) (even though you have imported it into your GPG public keyring), you need to import the key into the RPM keyring first. RPM 4.1 does not use your GPG keyring (and GPG itself) anymore, but rather maintains its own keyring (because it's a system wide application and the GPG public keyring is user-specific file). To import the MySQL public key into the RPM keyring, please use the following command:

shell> rpm --import <pubkey>

Example:

shell> rpm --import mysql_pubkey.asc

In case you notice that the MD5 checksum or GPG signatures do not match, first try to download the respective package one more time, maybe from another mirror site. If you repeatedly can not successfully verify the integrity of the package, please notify us about such incidents including the full package name and the download site you have been using at webmaster@mysql.com or build@mysql.com.

MySQL がサポートする OS

我々は GNU Autoconf を使用していますので、MySQL は POSIX スレッ ドと C++ コンパイラが動作する全ての新しいシステムに移植可能です。(クライ アントコードのコンパイルだけは C++ を必要としますが、スレッドは必要ではありません。) 我々は自身のソフトウェアを、最初に Sun Solaris (現在は 2.5 〜 2.7) 上と SuSE Linux Version 7.x で使用し開発します。

多くの OS では、ネイティブスレッドは最新バージョ ンだけで動作することに注意してください。 MySQL は次の OS/スレッドパッケージの組み合わせで、コンパイルの 成功が報告されています。

全てのプラットフォームが MySQL Server をちゃんと動作させるものではありません。 我々は以下のような評価基準に基づいて重要な要件を任せるに足るプラットフォームで あるかを判断しています。:

Based on the preceding criteria, the best platforms for running MySQL at this point are x86 with SuSE Linux 7.1, 2.4 kernel, and ReiserFS (or any similar Linux distribution) and SPARC with Solaris 2.7 or 2.8. FreeBSD comes third, but we really hope it will join the top club once the thread library is improved. We also hope that at some point we will be able to include all other platforms on which MySQL compiles, runs okay, but not quite with the same level of stability and performance, into the top category. This will require some effort on our part in cooperation with the developers of the OS/library components MySQL depends upon. If you are interested in making one of those components better, are in a position to influence their development, and need more detailed instructions on what MySQL needs to run better, send an e-mail to internals@lists.mysql.com.

Please note that the preceding comparison is not to say that one OS is better or worse than the other in general. We are talking about choosing a particular OS for a dedicated purpose@-running MySQL, and compare platforms in that regard only. With this in mind, the result of this comparison would be different if we included more issues into it. And in some cases, the reason one OS is better than the other could simply be that we have put forth more effort into testing on and optimising for that particular platform. We are just stating our observations to help you decide on which platform to use MySQL on in your setup.

使用すべき MySQL のバージョン

make を行う前に決める事は、あなたが最新の開発リリースを使用するのか、 または最新の安定リリースを使用するのかです:

make 前の2番目の決定事項は、ソースディストリビューションとバイナリディ ストリビューションのどちらを使用するかです。多くの場合、バイナリがプラッ トフォーム用に存在していれば、おそらくバイナリディストリビューションを使 用すべきです。通常、それはソースディストリビューションよりも簡単にインス トールできます。

次のケースでは、おそらくソースインストールの方が良いでしょう:

MySQL の命名法では、リリース番号は3つの数値とサフィックスからな ります。例えば、mysql-3.21.17-beta のようなリリース名は次のように 解釈されます:

MySQL の全てのバージョンは、比較的安全に使用できることを確かめ るため、我々は標準テストとベンチマークを通して確認しています。標準テス トは以前に見つかった全てのバグをチェックするように拡張されるため、テスト スイートはより良く保持されます。

全てのリリースは少なくても次のテストがされていることに注意してください:

内部テストスイート
これは顧客のための製品システムの一部です。多くのテーブルと何百というメガ バイトのデータを持っています。
MySQL ベンチマークスイート
これは一般的な範囲のクエリを実行します。これは、最適化の最新バッチが実際 にコードをより速く作れるかどうかを確認するテストでもあります。 See section The MySQL Benchmark Suite.
crash-me テスト
これは、データベースがサポートしている機能と、その許容量と制限を決定しよ うとします。 See section The MySQL Benchmark Suite.

他のテストは我々の内部製品環境で最新の MySQL バージョンを我々が 少なくとも1つのマシンで使用することです。我々は動作のため 100ギガバイト 以上のデータを持ちます。

インストールレイアウト

この節では、バイナリとソース配布のインストールで生成されるディレクトリの デフォルトのレイアウトを説明します。

バイナリ配布はアンパックすることによりインストールされ、インストール場所 はあなたが選択した場所(通常 `/usr/local/mysql')の中の次のディレクト リを選択し生成します:

ディレクトリ ディレクトリの内容
`bin' クライアントプログラム, mysqld サーバ
`data' ログファイル, データベース
`include' インクルード(ヘッダ)ファイル
`lib' ライブラリ
`scripts' mysql_install_db
`share/mysql' エラーメッセージファイル
`sql-bench' ベンチマーク

ソース配布は configure しコンパイルした後にインストールされます。デフォ ルトではインストールステップは `/usr/local' 配下のファイルを次のサ ブディレクトリにインストールします:

ディレクトリ ディレクトリの内容
`bin' クライアントプログラムとスクリプト
`include/mysql' インクルードファイル
`info' Info 形式のドキュメント
`lib/mysql' ライブラリ
`libexec' mysqld サーバ
`share/mysql' エラーメッセージファイル
`sql-bench' ベンチマークと crash-me テスト
`var' データベースとログファイル

ソースインストールのレイアウトはバイナリインストールと次の点が異なります:

スクリプト `scripts/make_binary_distribution' を実行することにより、 コンパイルされたソースディストリビューションから、あなた自身のバイナリイン ストレーションを生成できます。

アップデートがリリースされる方法と時

MySQL は MySQL AB でかなり速く進化していて、我々はこれを他の MySQL ユーザに共有してもらいたいです。我々は、他の人が必要とし ていると思われるとても便利な機能を持った時に、リリースの作成を試みます。

我々は、実装が簡単な機能を要求するユーザの手助けも試みます。我々は、我々 のライセンスユーザが求めるものにも注目し、特に我々の拡張 email サポート 顧客が求めるものに注目して、彼らの手助けを試みます。

新しいリリースをダウンロードする必要はありません。News 節は、新しいリリー スが、あなたが本当に求める何かを持っているかどうかをあなたに教えます。 See section MySQL Change History.

我々は MySQL の更新時は次のポリシーにしたがって行います:

現在の安定リリースはバージョン 3.23 です; 我々はすでにバージョン 4.0 の開発に移行しています。 しかし、安定バージョンでもバグはまだ修正されます。 我々は、バグ修正と``行なわなければいけない''ことを無視するような、完全な 凍結を考えていません。``幾分かの凍結''とは、``ほとんど確実に既に動作して いるものに影響を与えない''小さなことを追加するかもしれないということを意 味します。

MySQL uses a slightly different naming scheme from most other products. In general it's relatively safe to use any version that has been out for a couple of weeks without being replaced with a new version. See section 使用すべき MySQL のバージョン.

MySQL Binaries Compiled by MySQL AB

サービスとして、我々 MySQL AB は MySQL のバイナリ配布を提供しています。 これらのコンパイルは MySQL AB 内部でおこなったり、我々にマシンの アクセスを提供してもらっている顧客のマシン上で行っています。

これらの配布物は Build-tools/Do-compile で作成され (このスクリプトは scripts/make_binary_distribution を使用して ソースをコンパイルし tar.gz バイナリを作成します)、 以下のコンパイルオプションで調整されています。

Binaries built on MySQL AB development systems:

Linux 2.4.xx i386 with gcc 2.95.3
CFLAGS="-O2 -mcpu=pentiumpro" CXX=gcc CXXFLAGS="-O2 -mcpu=pentiumpro -felide-constructors" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --enable-assembler --disable-shared --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static
Linux 2.4.xx ia64 with ecc (Intel C++ Itanium Compiler 7.0)
CC=ecc CFLAGS=-tpp1 CXX=ecc CXXFLAGS=-tpp1 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile
Linux 2.4.xx alpha with ccc (Compaq C V6.2-505 / Compaq C++ V6.3-006)
CC=ccc CFLAGS="-fast -arch generic" CXX=cxx CXXFLAGS="-fast -arch generic -noexceptions -nortti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --with-mysqld-ldflags=-non_shared --with-client-ldflags=-non_shared --disable-shared
Linux 2.2.xx sparc with egcs 1.1.2
CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXX=gcc CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --enable-assembler --disable-shared
Linux 2.4.xx s390 with gcc 2.95.3
CFLAGS="-O2" CXX=gcc CXXFLAGS="-O2 -felide-constructors" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --disable-shared --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static
Sun Solaris 2.8 sparc with gcc 3.2
CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXX=gcc CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --enable-assembler --with-named-z-libs=no --with-named-curses-libs=-lcurses --disable-shared
Sun Solaris 2.9 sparc with gcc 2.95.3
CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXX=gcc CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --enable-assembler --with-named-curses-libs=-lcurses --disable-shared
Sun Solaris 2.9 sparc with cc-5.0 (Sun Forte 5.0)
CC=cc-5.0 CXX=CC ASFLAGS="-xarch=v9" CFLAGS="-Xa -xstrconst -mt -D_FORTEC_ -xarch=v9" CXXFLAGS="-noex -mt -D_FORTEC_ -xarch=v9" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --enable-assembler --with-named-z-libs=no --enable-thread-safe-client --disable-shared
IBM AIX 4.3.2 ppc with gcc 3.2.1
CFLAGS="-O2 -mcpu=powerpc -Wa,-many " CXX=gcc CXXFLAGS="-O2 -mcpu=powerpc -Wa,-many -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --with-named-z-libs=no --disable-shared
IBM AIX 5.1.0 ppc with gcc 3.2.1
CFLAGS="-O2 -mcpu=powerpc -Wa,-many" CXX=gcc CXXFLAGS="-O2 -mcpu=powerpc -Wa,-many -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --with-server-suffix="-pro" --enable-thread-safe-client --enable-local-infile --with-named-z-libs=no --disable-shared --with-innodb
HP-UX 10.20 pa-risc1.1 with gcc 3.1
CFLAGS="-DHPUX -I/opt/dce/include -O3 -fPIC" CXX=gcc CXXFLAGS="-DHPUX -I/opt/dce /include -felide-constructors -fno-exceptions -fno-rtti -O3 -fPIC" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --with-pthread --with-named-thread-libs=-ldce --with-lib-ccflags=-fPIC --disable-shared
HP-UX 11.11 pa-risc2.0 with aCC (HP ANSI C++ B3910B A.03.33)
CC=cc CXX=aCC CFLAGS=+DD64 CXXFLAGS=+DD64 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --disable-shared
Apple Mac OS X 10.2 powerpc with gcc 3.1
CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXX=gcc CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --disable-shared
FreeBSD 4.7 i386 with gcc 2.95.4
CFLAGS=-DHAVE_BROKEN_REALPATH ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --enable-assembler --with-named-z-libs=not-used --disable-shared

The following binaries are built on third-party systems kindly provided to MySQL AB by other users. Please note that these are only provided as a courtesy. Since MySQL AB does not have full control over these systems, we can only provide limited support for the binaries built on these systems.

SCO Unix 3.2v5.0.6 i386 with gcc 2.95.3
CFLAGS="-O3 -mpentium" LDFLAGS=-static CXX=gcc CXXFLAGS="-O3 -mpentium -felide-constructors" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --with-named-z-libs=no --enable-thread-safe-client --disable-shared
Caldera Open Unix 8.0.0 i386 with CC 3.2
CC=cc CFLAGS="-O" CXX=CC ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --with-named-z-libs=no --enable-thread-safe-client --disable-shared
Compaq Tru64 OSF/1 V5.1 732 alpha with cc/cxx (Compaq C V6.3-029i / DIGITAL C++ V6.1-027)
CC="cc -pthread" CFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all" CXX="cxx -pthread" CXXFLAGS="-O4 -ansi_alias -fast -inline speed -speculate all -noexceptions -nortti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --with-prefix=/usr/local/mysql --with-named-thread-libs="-lpthread -lmach -lexc -lc" --disable-shared --with-mysqld-ldflags=-all-static
SGI Irix 6.5 IP32 with gcc 3.0.1
CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex --enable-thread-safe-client --enable-local-infile --disable-shared

The following compile options have been used for binary packages MySQL AB used to provide in the past. These binaries are currently not being updated anymore, but the compile options are kept in here for reference purposes.

Linux 2.2.x with x686 with gcc 2.95.2
CFLAGS="-O3 -mpentiumpro" CXX=gcc CXXFLAGS="-O3 -mpentiumpro -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --disable-shared --with-extra-charsets=complex
SunOS 4.1.4 2 sun4c with gcc 2.7.2.1
CC=gcc CXX=gcc CXXFLAGS="-O3 -felide-constructors" ./configure --prefix=/usr/local/mysql --disable-shared --with-extra-charsets=complex --enable-assembler
SunOS 5.5.1 (and above) sun4u with egcs 1.0.3a or 2.90.27 or gcc 2.95.2 and newer
CC=gcc CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex --enable-assembler
SunOS 5.6 i86pc with gcc 2.8.1
CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex
BSDI BSD/OS 3.1 i386 with gcc 2.7.2.1
CC=gcc CXX=gcc CXXFLAGS=-O ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex
BSDI BSD/OS 2.1 i386 with gcc 2.7.2
CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex
AIX 2 4 with gcc 2.7.2.2
CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex

上で示したオプション以外で最適化を施した方はだれでも、開発者向けの メーリングリストにポストできます。 internals@lists.mysql.com.

RPM 配布では MySQL 3.22 を user-contributed としています。 3.22 をはじめ、いくつかの RPM パッケージは MySQL AB 製です。

MySQL のデバッグバージョンをコンパイルしたい場合は、 --with-debug または --with-debug=full を上記の configure 行 に追加して、すべての -fomit-frame-pointer オプションを取り除いてく ださい。

For the Windows distribution, please see section Windows への MySQL のインストール.

Installing a MySQL Binary Distribution

See also section Installing the Binaries, section Installing MySQL on Linux, and section Building Client Programs.

MySQL の バイナリ配布プログラムをインストールする際は以下のツールが必要になります:

Linux では別の形式、RPM-based(RPM Package Manager)配布も行われています。 See section Installing MySQL on Linux.

もしもこの問題にぶつかってしまった場合は mysqlbug を使用してください。 質問等は mysql@lists.mysql.com に送ってください。 問題点がバグに該当しなくても mysqlbug は情報を集めていますので解決の 手助けになることと思います。 mysqlbug を使用すれば問題の解決方法を得る 確率が増します。mysqlbug は解凍されたプログラムの `bin' 以下にあります。 See section バグや問題を報告する方法.

MySQL バイナリ配布プログラムのインストール及び 立ち上げまでに必要となる基本操作は以下の通りです。

shell> groupadd mysql
shell> useradd -g mysql mysql
shell> cd /usr/local
shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -
shell> ln -s full-path-to-mysql-VERSION-OS mysql
shell> cd mysql
shell> scripts/mysql_install_db
shell> chown -R root  .
shell> chown -R mysql data
shell> chgrp -R mysql .
shell> bin/safe_mysqld --user=mysql &
or
shell> bin/mysqld_safe --user=mysql &
if you are running MySQL 4.x

新しいユーザを追加するには bin/mysql_setpermission スクリプトを 使用できます。使用の際はDBIMsql-Mysql-modulesの Perlモジュールをインストールする必要があります。

より詳細な情報をここから示します。

バイナリ配布のプログラムをインストールする際は以下に従ってください。 その後、section インストール後の設定とテストに進んでインストールの終了処理と動作試験を行ってください。

  1. バイナリ配布プログラムを解凍するためのディレクトリを用意してください。 そして、そこにバイナリ配布ファイルを置いてください。 以下の例では `/usr/local' にファイルを解凍し、`/usr/local/mysql' に MySQLをインストールします。(従って以下の例では操作するユーザが `/usr/local' に対して書き込み権限を持つことを前提としています。 もしも `/usr/local' への書き込みが禁じられている場合は rootとしてインストールを行う必要があります。
  2. プログラムの配布は以下のサイトから行ってください。 section MySQL を得る方法. MySQLのバイナリ配布は圧縮された tar 形式で行われており、 `mysql-VERSION-OS.tar.gz' のような形式の名前が付けられています。 ここで、VERSION はバージョン番号(例えば 3.21.15)を OS はプラットホームとなるOS(例えば pc-linux-gnu-i586)を示します。
  3. バイナリ配布ファイルに -max という表示があるものがありますが、 これはこのプログラムが transaction-safe 機能やその他の機能をサポート していることを示しています。See section mysqld-max, An Extended mysqld Server。 全てのバイナリプログラムは同じソースファイルからmakeされたものです。
  4. mysqldが動作するためのユーザとグループを作成してください。
    shell> groupadd mysql
    shell> useradd -g mysql mysql
    
    これらのコマンドは mysql グループと mysql ユーザを作成するものです。 useraddgroupadd というコマンドもありますが、 これらは使用プラットホームによって使い方が若干異なります。 また、adduseraddgroup と呼ばれる場合もあります。 mysql 以外のユーザやグループでも使用できます。
  5. インストール先のディレクトリを変更する場合は以下のようにします。 まずディレクトリを移動します。
    shell> cd /usr/local
    
  6. 以下のように移動したディレクトリ上でプログラムの展開を行い インストールディレクトリを作成してください。
    shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -
    shell> ln -s full-path-to-mysql-VERSION-OS mysql
    
    最初のコマンドで `mysql-VERSION-OS' という名前のディレクトリを作成します。 次のコマンドはそのディレクトリへのシンボリックリンクを作成し、 ユーザに単純な `/usr/local/mysql' という名前での利用を可能にします。
  7. 以下のようにインストールディレクトリへ移動します。
    shell> cd mysql
    
    複数のファイルが mysql 以下のディレクトリに展開されているのが おわかりになると思います。 中でもインストールに重要な役目を果たすものは `bin'`scripts' のサブディレクトリにあります。
    `bin'
    This directory contains client programs and the server You should add the full pathname of this directory to your PATH environment variable so that your shell finds the MySQL programs properly. See section Environment Variables.
    `scripts'
    このディレクトリには mysql_install_db という mysql への アクセス管理を行うデータベースを初期化するためのスクリプトが置いてあります。
  8. mysqlaccessを使う必要があり、なおかつ、標準ディレクトリとは異なる場所に インストールを行いたい場合は、mysqlaccessmysqlクライアントを 起動できるように環境設定を行う必要があります。 `bin/mysqlaccess'の18行目位にある以下のような行を変更してください。
    $MYSQL     = '/usr/local/bin/mysql';    # path to mysql executable
    
    これを実際に mysql がインストールされているディレクトリに変更してください。 これをしないと mysqlaccess を使う際に Broken pipe エラーが発生します。
  9. 以下のようにすることによりアクセス管理データベースを作ることができます (初めてMySQLをインストールする時だけ必要)。
    shell> scripts/mysql_install_db
    
    使用する MySQL のバージョンが 3.22.10 より古い場合はこの操作をする時に MySQL サーバが 立ち上がっている必要がありましたが、現在のバージョンでは必要ありません。
  10. Change ownership of binaries to root and ownership of the data directory to the user that you will run mysqld as:
    shell> chown -R root  /usr/local/mysql/.
    shell> chown -R mysql /usr/local/mysql/data
    shell> chgrp -R mysql /usr/local/mysql/.
    
    最初のコマンドによって全てのファイルの owner 属性が root になります。 二行目のコマンドによってデータディレクトリ以下のファイル全ての owner 属性が mysql になります。 最後のコマンドによって全てのファイルの group 属性が mysql になります。
  11. PerlモジュールDBIDBDのインストールが必要ならsection Perl Installation Commentsの項をご覧下さい。
  12. MySQL を OS のブート時に自動的に起動したい場合は support-files/mysql.server を 貴方のシステムの的確な場所にコピーして使用できます。 より詳しい情報は support-files/mysql.server のスクリプト自体や section MySQL の自動起動と自動停止 にあります。

全てのファイルの展開とインストールが終了したら初期化と稼動試験を行います。

以下のようにしてMySQLサーバを立ち上げることができます。

shell> bin/safe_mysqld --user=mysql &

Now proceed to section safe_mysqld, The Wrapper Around mysqld, and See section インストール後の設定とテスト.

MySQL ソースディストリビューションのインストール

ソースインストールに取り掛かる前に、最初に我々のバイナリがあなたのプラット フォームに有効で、動作するかどうかをチェックしてください。我々は、我々のバ イナリが可能な限りのオプションで構築されていることを確認するために多くの努 力をしています。

ソースから MySQL を作成しインストールするためには次のツールが必 要です:

-fno-exceptions オプションを解釈する gcc の最近のバージョ ンを使用している場合は、それを使用することがとても重要です。そう でなければ、ランダムにクラッシュするバイナリができあがるでしょう。また、 -fno-exceptions に加え、-felide-contructors-fno-rtti を使用することをお奨めします。 疑いがある時は、次を行なってください:


CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions \
       -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler \
       --with-mysqld-ldflags=-all-static

多くのシステムで、これは速くて安定したバイナリを与えます。

問題が起きたときは、mysql@lists.mysql.com に質問を投稿する時に mysqlbug を常に使用してください。問題がバグでないとして も、mysqlbug はあなたの問題を解決する助けになるであろうシステム情 報を収集します。mysqlbug を使用しないと、あなたの問題の解決を得る 可能性が小さくなります! mysqlbug は、配布のアンパック後に `scripts' ディレクトリ内に見つけられます。 See section バグや問題を報告する方法.

素早いインストールの概要

MySQL をソースからインストールするために行なわなければならない 基本的なコマンド:

shell> groupadd mysql
shell> useradd -g mysql mysql
shell> gunzip < mysql-VERSION.tar.gz | tar -xvf -
shell> cd mysql-VERSION
shell> ./configure --prefix=/usr/local/mysql
shell> make
shell> make install
shell> scripts/mysql_install_db
shell> chown -R root  /usr/local/mysql
shell> chown -R mysql /usr/local/mysql/var
shell> chgrp -R mysql /usr/local/mysql
shell> cp support-files/my-medium.cnf /etc/my.cnf
shell> /usr/local/mysql/bin/safe_mysqld --user=mysql &
or
shell> /usr/local/mysql/bin/mysqld_safe --user=mysql &
if you are running MySQL 4.x.

InnoDB テーブルをサポートしたい場合は、/etc/my.cnf ファイルを編集し て、innodb_... で始まるパラメータの前の # 文字を削除すべきで す。 See section `my.cnf' オプションファイル, and section InnoDB 起動オプション.

RPM ソースから開始する場合は:

shell> rpm --rebuild --clean MySQL-VERSION.src.rpm

これはインストールできるRPMバイナリを作成します

もし DBIMsql-Mysql-modules Perl モジュールをインストールするなら、 bin/mysql_setpermission スクリプトが使用する新しいユーザーを 追加することができます。

次にさらに詳細な説明を行ないます:

ソース配布のインストールには、次のステップに従い、それから インストール 後の初期化とテストのために section インストール後の設定とテスト に進んでください。

  1. 配布をアンパックしたいディレクトリを選んで、そこに移ってください。
  2. 配布ファイルを section MySQL を得る方法. にリストされたサイトの一つから得てください。
  3. MySQL で Berkeley DB テーブルの使用に興味がある場合、Berkeley DB ソースコー ドのパッチバージョンを入手する必要があります。処理の前に Berkeley DB テー ブルの章を読んでください。 See section BDB or BerkeleyDB Tables. MySQL ソース配布は圧縮された tar アーカイブとして提供さ れ、`mysql-VERSION.tar.gz' のような名前を持ちます。ここで VERSION は のような番号です。
  4. mysqld を実行するユーザーとグループを追加します:
    shell> groupadd mysql
    shell> useradd -g mysql mysql
    
    これらのコマンドは mysql グループと mysql ユーザを追加します。 useraddgroupadd 構文は、別のバージョンの UNIX 上では少し異なるでしょ う。adduseraddgroup と呼ばれることもあります。ユーザとグ ループは mysql の代わりに他の何かにすることもできます。
  5. カレントディレクトリに配布をアンパックしてください:
    shell> gunzip < /path/to/mysql-VERSION.tar.gz | tar xvf -
    
    このコマンドは `mysql-VERSION' という名前のディレクトリを作成します。
  6. Change into the top-level directory of the unpacked distribution:
    shell> cd mysql-VERSION
    
    注意: 現在のこのトップレベルディレクトリで MySQL の configure と build を行なう必要があります。別のディレクトリでは build できません。
  7. リリースを configure し、全てをコンパイルしてください:
    shell> ./configure --prefix=/usr/local/mysql
    shell> make
    
    configure の実行時、いくつかのオプションを指定できます。オプショ ンの一覧は ./configure --help を実行してください。section 典型的な configure オプション, さらに有用なオプションのいくつかに ついて議論しています。 configure が失敗して、援助を得るために mysql@lists.mysql.com にメー ルを送ろうとする場合、`config.log' から問題の解決の手助けにできると 考えられる行を含めてください。configure が異常終了する場合、 configure からの出力の最後の数行も含めてください。バグレポートは mysqlbug スクリプトを使用して投稿してください。See section バグや問題を報告する方法。 コンパイルが失敗する場合、いくらかのよくある問題での手助けのため、 section MySQL コンパイル時の問題 を参照してください。
  8. 全てをインストールしてください:
    shell> make install
    
    このコマンドは root として実行する必要があります。
  9. MySQL 権限テーブルを生成してください(以前に MySQL をイ ンストールしていない時にだけ必要です):
    shell> scripts/mysql_install_db
    
    注意: 3.22.10 より古い MySQL バージョンでは、 mysql_install_db 実行時に MySQL サーバが開始されましたが、 これはもはや真ではありません!
  10. バイナリのオーナーを root に、 データディレクトリの所有権を mysqld を実行するユーザに変更し てください:
    shell> chown -R root  /usr/local/mysql
    shell> chown -R mysql /usr/local/mysql/var
    shell> chgrp -R mysql /usr/local/mysql
    
    最初のコマンドはファイルの owner 属性を root ユーザーに変更し、 2番目のコマンドは ownermysql ユーザに変更し、 3番目のコマンドは group 属性を mysql グループに変更します。
  11. Perl DBI/DBD インタフェースのサポートをインストールしたい 場合、section Perl Installation Comments を見てください。
  12. MySQL をマシン起動時に自動的に開始したい場合、 support-files/mysql.server をシステムのスタートアップファイルがあ る場所にコピーしてください。さらなる情報は support-files/mysql.server スクリプト自身の中と、 section MySQL の自動起動と自動停止 に見つけられます。 section MySQL の自動起動と自動停止.

全てがインストールされた後、配布の初期化とテストを行なうべきです。

shell> /usr/local/mysql/bin/safe_mysqld --user=mysql &

コマンドがすぐに mysqld daemon ended エラーで失敗する場合、 `mysql-data-directory/'hostname'.err' ファイルになんらかの情報を 見つけることができます。 よくあることとして、すでに他の mysqld が 走っている場合などがあります。 See section 同一マシン上に複数の MySQL サーバーを走らせる.

Now proceed to section インストール後の設定とテスト.

パッチの適用

時々、パッチは、メーリング・リストに流されたり、または MySQL Web サイトのパッチエリア (http://www.mysql.com/downloads/patches.html) に置かれます。

メーリング・リストからのパッチを適用するには、パッチが載っているメッセージを ファイルに保存して、あなたの MySQL ソース・ツリーの 一番上のディレクトリーに移動し、以下のようにコマンドを実行します:

shell> patch -p1 < patch-file-name
shell> rm config.cache
shell> make clean

FTPサイトに置かれるパッチは、プレーンテキストファイルとして、 あるいは gzip で圧縮されたファイルとして頒布されます。 プレーンテキストのパッチの場合は、上に示したメーリングリストの パッチと同様に適用します。 圧縮されたパッチを適用するには、 MySQL ソース・ツリーの 一番上のディレクトリーに移動し、以下のようにコマンドを実行します:

shell> gunzip < patch-file-name.gz | patch -p1
shell> rm config.cache
shell> make clean

それから通常のソースインストールの指示を ./configure ステップから 始めます。make install ステップ実行後、あなたの MySQL サー バを再起動します。

make install を実行する前に、現在走っているサーバーを止める必要があるかもしれません。 ( mysqladmin shutdown で止めます ) いくつかのシステムでは、現在実行しているものを止めない限り、 新しいバージョンをインストールできないようになっています。

典型的な configure オプション

configure スクリプトは MySQL 配布をどのようにコンフィグ するかを制御するための多くの処理を提供します。典型的には、 configure コマンドラインにオプションを使用してこれを行ないます。 いくつかの環境変数を使用しても configure に影響を与えることができ ます。 See section Environment Variables. configure がサポートするオプションの一覧は、次のコマンドを 実行してください:

shell> ./configure --help

一般的に使用される configure オプションのいくつかを以下に説明します:

開発ソースツリーからのインストール

警告: 我々の新しいテストコードについて我々を手助けすることに興味 がある場合にだけ、この節を読むべきです。MySQL を得て、あなたのシ ステム上で実行したいだけの場合は、標準リリースディストリビューションを使 用すべきです(ソースまたはバイナリディストリビューション)。

我々のもっとも新しい開発ソースツリーを得るには、次の手順に従ってください:

  1. Download BitKeeper from http://www.bitmover.com/cgi-bin/download.cgi. You will need Bitkeeper 3.0 or newer to access our repository.
  2. Follow the instructions to install it.
  3. After BitKeeper is installed, first go to the directory you want to work from, and then use one of the following commands to clone the MySQL version branch of your choice: To clone the 3.23 branch, use this command:
    shell> bk clone bk://mysql.bkbits.net/mysql-3.23 mysql-3.23
    
    To clone the 4.0 branch, use this command:
    shell> bk clone bk://mysql.bkbits.net/mysql-4.0 mysql-4.0
    
    To clone the 4.1 branch, use this command:
    shell> bk clone bk://mysql.bkbits.net/mysql-4.1 mysql-4.1
    
    In the preceding examples the source tree will be set up in the `mysql-3.23/', `mysql-4.0/', or `mysql-4.1/' subdirectory of your current directory. If you are behind a firewall and can only initiate HTTP connections, you can also use BitKeeper via HTTP. If you are required to use a proxy server, simply set the environment variable http_proxy to point to your proxy:
    shell> export http_proxy="http://your.proxy.server:8080/"
    
    Now, simply replace the bk:// with http:// when doing a clone. Example:
    shell> bk clone http://mysql.bkbits.net/mysql-4.1 mysql-4.1
    
    The initial download of the source tree may take a while, depending on the speed of your connection - please be patient.
  4. You will need GNU make, autoconf 2.53 (or newer), automake 1.5, libtool 1.4, and m4 to run the next set of commands. Note that automake 1.7 or newer doesn't yet work. If you are using trying to configure MySQL 4.1 you will also need bison 1.75. Older versions of bison may report this error: sql_yacc.yy:#####: fatal error: maximum table size (32767) exceeded. Note: the maximum table size is not actually exceeded, the error is caused by bugs in these earlier bison versions. The typical command to do in a shell is:
    cd mysql-4.0
    bk -r get -Sq
    aclocal; autoheader; autoconf; automake
    (cd innobase ; aclocal; autoheader; autoconf; automake) # for InnoDB
    (cd bdb/dist ; sh s_all ) # for Berkeley DB
    ./configure  # Add your favorite options here
    make
    
    If you get some strange error during this stage, check that you really have libtool installed! A collection of our standard configure scripts is located in the `BUILD/' subdirectory. If you are lazy, you can use `BUILD/compile-pentium-debug'. To compile on a different architecture, modify the script by removing flags that are Pentium-specific.
  5. When the build is done, run make install. Be careful with this on a production machine; the command may overwrite your live release installation. If you have another installation of MySQL, we recommand that you run ./configure with different values for the prefix, with-tcp-port, and unix-socket-path options than those used for your production server.
  6. Play hard with your new installation and try to make the new features crash. Start by running make test. See section MySQL Test Suite.
  7. If you have gotten to the make stage and the distribution does not compile, please report it to bugs@lists.mysql.com. If you have installed the latest versions of the required GNU tools, and they crash trying to process our configuration files, please report that also. However, if you execute aclocal and get a command not found error or a similar problem, do not report it. Instead, make sure all the necessary tools are installed and that your PATH variable is set correctly so that your shell can find them.
  8. After the initial bk clone operation to get the source tree, you should run bk pull periodically to get the updates.
  9. You can examine the change history for the tree with all the diffs by using bk sccstool. If you see some funny diffs or code that you have a question about, do not hesitate to send e-mail to internals@lists.mysql.com. Also, if you think you have a better idea on how to do something, send an e-mail to the same address with a patch. bk diffs will produce a patch for you after you have made changes to the source. If you do not have the time to code your idea, just send a description.
  10. BitKeeper has a nice help utility that you can access via bk helptool.
  11. Please note that any commits (bk ci or bk citool) will trigger the posting of a message with the changeset to our internals mailing list, as well as the usual openlogging.org submission with just the changeset comments. Generally, you wouldn't need to use commit (since the public tree will not allow bk push), but rather use the bk diffs method described previously.

You can also browse changesets, comments and sourcecode online by browsing to e.g. http://mysql.bkbits.net:8080/mysql-4.1 For MySQL 4.1.

The manual is in a separate tree which can be cloned with:

shell> bk clone bk://mysql.bkbits.net/mysqldoc mysqldoc

MySQL コンパイル時の問題

Solaris や Linux 上で gcc を使用した場合、一切警告無く 全ての MySQL プログラムがきれいに作れます。 他のシステムではインクルードファイルの違いから警告が出るかもしれません。 MIT-pthreads を使用した際の警告は section MIT-pthreads に関して を参照してください。 他の問題は、以下をチェックしてください。

多くの問題の解決のために、再 configure が必要です。 あなたが再構成する必要があるならば、以下に気をつけてください:

古いコンフィグやオブジェクトファイルの使用を防ぐため、 configure 前に以下のコマンドを実行してください:

shell> rm config.cache
shell> make clean

こうするかわりに、make distclean としても構いません。

以下に、 MySQL をコンパイルする際に起こりやすい問題をあげておきます:

MIT-pthreads に関して

このセクションではMIT-pthreadsを使っているさいに起こる問題についていくつか述べて います。

Linux では、MIT-pthreads を使用してはならず、 LinuxThreads をインストールするべきです! See section Linux Notes (All Linux Versions).

もしあなたのシステムが本来のスレッドのサポートを提供しなければ、あなたは、 MIT-pthreadsパッケージを使って、MySQL を構築する必要があります。 これにはほとんどのFreeBSDシステム、SunOS4.x,Solaris 2.4とそれ以前、ほかいくつか が含まれます。 See section MySQL がサポートする OS.

Note, that beginning with MySQL 4.0.2 MIT-pthreads are no longer part of the source distribution! If you require this package, you need to download it separately from http://www.mysql.com/Downloads/Contrib/pthreads-1_60_beta6-mysql.tar.gz

After downloading, extract this source archive into the top level of the MySQL source directory. It will create a new subdirectory mit-pthreads.

Windows Source Distribution

You will need the following:

Building MySQL

  1. Create a work directory (e.g., workdir).
  2. Unpack the source distribution in the aforementioned directory.
  3. Start the VC++ 6.0 compiler.
  4. In the File menu, select Open Workspace.
  5. Open the `mysql.dsw' workspace you find on the work directory.
  6. From the Build menu, select the Set Active Configuration menu.
  7. Click over the screen selecting mysqld - Win32 Debug and click OK.
  8. Press F7 to begin the build of the debug server, libs, and some client applications.
  9. When the compilation finishes, copy the libs and the executables to a separate directory.
  10. Compile the release versions that you want, in the same way.
  11. Create the directory for the MySQL stuff: e.g., `c:\mysql'
  12. From the workdir directory copy for the c:\mysql directory the following directories:
  13. Create the directory `c:\mysql\bin' and copy all the servers and clients that you compiled previously.
  14. If you want, also create the `lib' directory and copy the libs that you compiled previously.
  15. Do a clean using Visual Studio.

Set up and start the server in the same way as for the binary Windows distribution. See section Preparing the Windows MySQL Environment.

インストール後の設定とテスト

初めて MySQLをインストールしたら(バイナリからでもソースからでもですが)、 サーバーを動作させるために、許可テーブルを初期化しなくてはなりません。 またマシンの起動時、停止時に、サーバーを自動で開始、停止することもできます。

通常、許可テーブルのインストールとサーバーの開始は、 ソースディストリビューションなら以下のようにします:

shell> ./scripts/mysql_install_db
shell> cd mysql_installation_directory
shell> ./bin/safe_mysqld --user=mysql &

バイナリディストリビューション(RPM または pkg パッケージではない)では次を 行ないます:

shell> cd mysql_installation_directory
shell> ./scripts/mysql_install_db
shell> ./bin/safe_mysqld --user=mysql &
or
shell> ./bin/mysqld_safe --user=mysql &
if you are running MySQL 4.x.

これは、いくつかのデータベースを生成します。mysql データベースは全 てのデータベース権限を保持します。test データベースは MySQL をテストするために使用できます。そして、 mysql_install_db を実行したユーザの権限エントリと root ユー ザも生成します(パスワードはありません)。これは mysqld サーバの起動 も行ないます。

mysql_install_db は古い権限テーブルを上書きしません。そのため、どの ような環境でも安全に実行できます。test データベースを持ちたくないな ら、mysqladmin -u root drop test で削除できます。

テストは、MySQL のトップディレクトリーから簡単に実行できます。 バイナリ配布を使用する場合、これ(トップディレクトリ)は インストール先のディレクトリーになるでしょう(`/usr/local/mysql')。 ソース配布の場合、これは MySQL のソースディレクトリです。

コマンドは本節といかに続く節で説明しますが、BINDIRmysqladminsafe_mysqld がインストールされたディレクトリを示します。 バイナリ配布を使用している場合、BINDIR はバイナリ配布の `bin' ディレクトリになります。 ソースからインストールした場合、BINDIR は、configure で特別指定しない限り、 `/usr/local/bin' です。 EXECDIRmysqld サーバーのインストール先です。 バイナリ配布を使用している場合、これは BINDIR ディレクトリと同一になります。 ソースからインストールした場合、`/usr/local/libexec' です。

テストについて以下に詳細に説明します:

  1. If necessary, start the mysqld server and set up the initial MySQL grant tables containing the privileges that determine how users are allowed to connect to the server. This is normally done with the mysql_install_db script:
    shell> scripts/mysql_install_db
    
    通常、mysql_install_db の実行は初めて MySQL をインストール したあと一度だけ必要です。 すでにインストールされているものを アップグレードする際にはこの手順は飛ばせます。 (しかし、mysql_install_db は実に安全で、すでにテーブルが 存在している場合はいかなるテーブルも更新しません。したがって、 実行すべきかどうかわからない場合は、mysql_install_db を常に 走らせることができます) mysql_install_db は 6個のテーブルを作ります (user, db, host, tables_priv, columns_priv, func) mysql データベースに。 初期の権限状態についての説明は section MySQL 権限許可の初期設定. これらの権限は MySQL root ユーザーに なんでもできるように許可し、そして、だれもが 'test' という名前か 'test_' ではじまる名前をもつ データベースを作成、使用できるように許可されています。 もし許可テーブルを設定していない場合、サーバーを起動時に以下のエラーが出ます:
    mysqld: Can't find file: 'host.frm'
    
    バイナリ配布の MySQL では、もし MySQL を ./bin/safe_mysqld を実行しないで起動した場合に、このエラーがおきます! section safe_mysqld, The Wrapper Around mysqld. rootmysql_install_db を実行する必要があるとあなたは思うかもしれません。 しかし、 MySQL は root 以外のユーザーで起動できます。 データベースディレクトリがサーバーを起動したユーザに対して読み書きが許可されていれば良いのです。 MySQL を一般ユーザーで走らせる方法は section 一般ユーザで MySQL を動かす方法. もし mysql_install_db で問題が出たら、 section mysql_install_db 実行時の問題. を参照のこと。 mysql_install_db スクリプトを走らせるにはいくつか選択があります: これらの選択については section MySQL 権限許可の初期設定 からさらに情報が得られます。
  2. MySQL サーバーを以下のようにして起動します:
    shell> cd mysql_installation_directory
    shell> bin/safe_mysqld &
    
    サーバの起動に問題があれば、section MySQL サーバー起動時の問題 を見てください。
  3. code{mysqladmin} でサーバーが走っているか確認します。 サーバーが立ち上がり接続を受け付けるか確認する簡単な方法を以下に示します:
    shell> BINDIR/mysqladmin version
    shell> BINDIR/mysqladmin variables
    
    例えば、mysqladmin version の出力はあなたのプラットフォームと MySQL のバージョンを出力します。 出力は以下の様にでます:
    shell> BINDIR/mysqladmin version
    mysqladmin  Ver 8.14 Distrib 3.23.32, for linux on i586
    Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
    This software comes with ABSOLUTELY NO WARRANTY. This is free software,
    and you are welcome to modify and redistribute it under the GPL license.
    
    Server version          3.23.32-debug
    Protocol version        10
    Connection              Localhost via Unix socket
    TCP port                3306
    UNIX socket             /tmp/mysql.sock
    Uptime:                 16 sec
    
    Threads: 1  Questions: 9  Slow queries: 0
    Opens: 7  Flush tables: 2  Open tables: 0
    Queries per second avg: 0.000
    Memory in use: 132K  Max memory used: 16773K
    
    BINDIR/mysqladmin の使用方法は、--help オプションで起動することにより得られます。
  4. Verify that you can shut down the server:
    shell> BINDIR/mysqladmin -u root shutdown
    
  5. サーバーをリスタートするには、safe_mysqldmysqld を直接実行します。 例えば:
    shell> BINDIR/safe_mysqld --log &
    
    safe_mysqld が失敗するなら、 MySQL のインストールディレクトリーから実行してみてください。 もしそれでも起動しないなら、section MySQL サーバー起動時の問題 を参照のこと。
  6. いくつかの簡単なテストでサーバーが動いているか確認できます。 以下のようになります:
    shell> BINDIR/mysqlshow
    +-----------+
    | Databases |
    +-----------+
    | mysql     |
    +-----------+
    
    shell> BINDIR/mysqlshow mysql
    Database: mysql
    +--------------+
    |    Tables    |
    +--------------+
    | columns_priv |
    | db           |
    | func         |
    | host         |
    | tables_priv  |
    | user         |
    +--------------+
    
    shell> BINDIR/mysql -e "SELECT host,db,user FROM db" mysql
    +------+--------+------+
    | host | db     | user |
    +------+--------+------+
    | %    | test   |      |
    | %    | test_% |      |
    +------+--------+------+
    
    他のプラットフォームで MySQL のパフォーマンスを比較するために `sql-bench' にベンチマークがあります。 `sql-bench/Results' ディレクトリには、他のデータベースやプラットフォームで ベンチを実行した結果があります。 全てのテストを実行するには、以下のようにします:
    shell> cd sql-bench
    shell> run-all-tests
    
    RPM バイナリ配布には `sql-bench' ディレクトリがありません。 (RPM のソース配布には含まれます) この場合、ベンチマークをインストールしなくてはなりません。 MySQL バージョン 3.22 のバイナリ配布から、 `mysql-bench-VERSION-i386.rpm' という名前で RPM パッケージを作っており、 これにはベンチマークのデータとコードが含まれます。 `tests' サブディレクトリでテストすることも可能です。 例えば、`auto_increment.tst' の実行は以下のようにします:
    shell> BINDIR/mysql -vvf test < ./tests/auto_increment.tst
    
    The expected results are shown in the `./tests/auto_increment.res' file.

mysql_install_db 実行時の問題

mysql_install_db スクリプトの目的は、新しい MySQL 権限テー ブルを生成することです。他のデータには何も影響しません! 既に MySQL 権限テー ブルをインストールしている場合は、何も行ないません!

権限テーブルを再生成したい場合は、mysqld サーバが動作していれば、それを落 としてから、次のように行なってください:

mv mysql-data-directory/mysql mysql-data-directory/mysql-old
mysql_install_db

この節では mysql_install_db を実行した際にでくわすかもしれない問題について述べます:

mysql_install_db doesn't install the grant tables
これは mysql_install_db が権限テーブルをインストールできなかった事のメッセージですが、 続いて以下のようにメッセージが出た場合:
starting mysqld daemon with databases from XXXXXX
mysql daemon ended
この場合、注意深く log ファイルを調べてください! エラーメッセージに出ている `XXXXXX' ディレクトリにログファイルがあり、 これに mysqld がなぜスタートしなかったか記されているはずです。 もし何が起こったかわからない場合、このログファイルを含んで mysqlbug を使用して バグレポートを投稿してください! See section バグや問題を報告する方法.
There is already a mysqld daemon running
この場合、 mysql_install_db を実行する必要はありません。 mysql_install_db を実行するのは MySQL を初めてインストールした後、 たった一回だけです。
Installing a second mysqld daemon doesn't work when one daemon is running
これはすでに MySQL がインストールされており、 しかし新しいインストールを違うところに行おうとした場合に発生します。 (例えば、一度に二つのインストールを実行した場合など) 一般にこの問題は二つ目のサーバーを動いているサーバーと同じポート、ソケットを使用して起動しようとした場合に発生します。 この場合、Can't start server: Bind on TCP/IP port: Address already in use エラーメッセージか Can't start server : Bind on unix socket... エラーメッセージが出ます。 See section 同じマシンに多くのサーバをインストールする.
You don't have write access to `/tmp'
もしソケットファイルを標準の場所(`/tmp')に作成するための書き込み許可がないなら、 あるいは、一時ファイルを `/tmp' に作成できないなら、 mysql_install_db の実行時、あるいは mysqld の起動/使用時に エラーとなるでしょう。 違うディレクトリーにソケットファイルや一時ファイルを指定するには:
shell> TMPDIR=/some_tmp_dir/
shell> MYSQL_UNIX_PORT=/some_tmp_dir/mysqld.sock
shell> export TMPDIR MYSQL_UNIX_PORT
See section MySQL ソケットファイル `/tmp/mysql.sock' を変更する方法、削除から守る方法. `some_tmp_dir' は書き込みが可能なディレクトリーを指定しなくてはなりません。 See section Environment Variables. この後、mysql_install_db を走らせ、サーバーを起動する事ができます:
shell> scripts/mysql_install_db
shell> BINDIR/safe_mysqld &
mysqld crashes immediately
もし RedHat バージョン 5.0 上で 2.0.7-5 より古い glibc を使用している場合、 全ての glibc パッチを当てなくてはなりません! これに関しては MySQL メールのアーカイブに情報が多くあります。 http://lists.mysql.com/. Also, see section Linux Notes (All Linux Versions). mysqld--skip-grant-tables 指定で起動することもできます。 そして以下のように mysql を使用して自分自身の手により許可を加えます:
shell> BINDIR/safe_mysqld --skip-grant-tables &
shell> BINDIR/mysql -u root mysql
mysql から手動で mysql_install_db に書かれている SQL コマンドを実行します。 許可テーブルをサーバーに読み込ますためには、 mysqladmin flush-privilegesmysqladmin reload を実行します。

MySQL サーバー起動時の問題

トランザクションをサポートするテーブル(BDB, InnoDB)を使用しようとする場合、 最初に `my.cnf' ファイルを生成して、使用しようとするテーブル型の起動オプショ ンを設定すべきです。 See section MySQL テーブル型.

通常 mysqld サーバーの起動は、以下の三つの方法のうち一つで行います:

mysqld デーモンの起動時に、デーモンはデータディレクトリにディレクトリを変えます。 ログファイルと pid (process ID) ファイルがこのディレクトリに書ける事、 そしてデータベースがこのディレクトリにある事を、デーモンは要求します。

データディレクトリの場所は配布物のコンパイル時に指定されています。 mysqld があなたのシステム上にデータベースディレクトリを見つけれなかった場合、 サーバーは動きません。 mysqld--help オプションで起動すれば mysqld の デフォルトのパスを知ることができますので、 サーバーが起動しない理由が違うパスを使用しているために起こっているかどうかがわかります。 パスが違う場合、mysqld のコマンドラインの引数に正しいパスを指定して、デフォルト値を 上書きすることが可能です。(これらオプションは safe_mysqld にも同様に使用できます)

通常、MySQL がインストールされたディレクトリのベースディレクトリだけを mysqld に教えればいいはずです。 これは --basedir オプションを指定します。 --help オプションを使用すればパスの変更が確認できます。 (--help必ず 最後に指定のこと)  例えば:

shell> EXECDIR/mysqld --basedir=/usr/local --help

パスの設定が思い通りに言ったことを確認したら、 --help オプションを外してサーバーを起動します。

どの方法でサーバーを起動しても、もし起動に失敗すれば、ログファイルを確認してください。 なぜ失敗したか記録されています。ログファイルはデータベースディレクトリにあります。 (バイナリ配布の場合 `/usr/local/mysql/data' 、ソース配布の場合 `/usr/local/var'、 Windows では `\mysql\data\mysql.err' ) データベースディレクトリに `host_name.err'`host_name.log' という ファイル (host_name はあなたのサーバー名) を探してください。 以下のようにしてそのファイルの最後の数行を確認します:

shell> tail host_name.err
shell> tail host_name.log

ログファイル中に次のような何かを見つけた場合:

000729 14:50:10  bdb:  Recovery function for LSN 1 27595 failed
000729 14:50:10  bdb:  warning: ./test/t1.db: No such file or directory
000729 14:50:10  Can't init databases

これは --bdb-recover 付きで mysqld が起動され、Berkeley DB がデータ ベースを復元しようとした時にログファイルに悪い何かを見つけたということを意 味します。継続を可能にするためには、古い Berkeley DB ログファイルをデータ ベースディレクトリから、あとで検査できる他の場所に移すべきです。ログファイ ルは `log.0000000001' (番号は時間の経つと増加します)と名付けられてい ます。

BDB テーブルサポートで mysqld を実行していて、mysqld が起動時にコア ダンプする場合、BDB recover log にいくつかの問題の原因があり得ます。この場 合、mysqld--bdb-no-recover で起動を試みることができます。 これで救える場合は、データディレクトリから全ての `log.*' ファイルを削 除し、そして mysqld を再び起動してみてください。

以下のエラーの場合、他のプログラム(か他の mysqld サーバー)が mysqld が使用しようとしている TCP/IP ソケットを使っています:

Can't start server: Bind on TCP/IP port: Address already in use
  or
Can't start server : Bind on unix socket...

他の mysqld サーバーが走っていないかを ps で確認します。 もし他のサーバーが起動していないなら、 telnet your-host-name tcp-ip-port-number コマンドを実行し、何回か RETURN キーをたたいてみてください。 もし、 telnet: Unable to connect to remote host: Connection refused のような エラーが出た場合、なにかが mysqld が使用しようとしているポートを既に使っています。 See section mysql_install_db 実行時の問題 and section 同一マシン上に複数の MySQL サーバーを走らせる.

もし mysqld がすでに走っている場合、以下のコマンドにてパスの設定を知ることができます:

shell> mysqladmin variables

または

shell> mysqladmin -h 'your-host-name' variables

If you get Errcode 13, which means Permission denied, when starting mysqld this means that you didn't have the right to read/create files in the MySQL database or log directory. In this case you should either start mysqld as the root user or change the permissions for the involved files and directories so that you have the right to use them.

もし safe_mysqld がサーバーを起動しても接続できないようなら、 `/etc/hosts' ファイルに以下のような記述を持たせてください:

127.0.0.1       localhost

この問題はスレッドライブラリーがなくて MySQL を MIT-pthreads を 使用するようにして作ったシステムにだけ起こります。

mysqld を起動できない場合、問題を見つけるためにトレースファイルの作 成を試みることができます。 See section Creating Trace Files.

InnoDB テーブルを使用している場合、InnoDB 固有の起動オプションを参照してく ださい。 See section InnoDB 起動オプション.

BDB (Berkeley DB) テーブルを使用する場合は、BDB 固有の起動オプションに精通 すべきです。 See section BDB startup options.

MySQL の自動起動と自動停止

mysql.serversafe_mysqld スクリプトは、システム起動時に自 動的にサーバを起動するために使用できます。mysql.server はサーバを停 止するためにも使用できます。

mysql.server とスクリプトは start, stop 引数を指定することにより サーバーを起動、停止できます:

shell> mysql.server start
shell> mysql.server stop

mysql.server は MySQL インストールディレクトリの `share/mysql' ディレクトリ、 または MySQL ソースツリーの `support-files' ディレクトリにあります。

mysql.server はサーバーを起動時する前に MySQL がインストールされた ディレクトリにディレクトリを変え、safe_mysqld を起動します。 もし標準以外にインストールしているバイナリ配布を使用しているなら、 mysql.server を編集する必要があるかもしれません。 safe_mysqld を起動する前に正しいディレクトリに cd するように変更します。 safe_mysqld に他のオプションを与えるように mysql.server を変えても構いません。 他のユーザーで実行したい場合、この節の後で示すように、適切な user 行を `/etc/my.cnf' ファイルに追加してください。

mysql.server stop はサーバーにシグナルを送ってサーバーを停止します。 You can also take down the server manually by executing mysqladmin shutdown.

You need to add these start and stop commands to the appropriate places in your `/etc/rc*' files when you want to start up MySQL automatically on your server.

On most current Linux distributions, it is sufficient to copy the file mysql.server into the `/etc/init.d' directory (or `/etc/rc.d/init.d' on older Red Hat systems). Afterwards, run the following command to enable the startup of MySQL on system bootup:

shell> chkconfig --add mysql.server

As an alternative to the above, some operating systems also use `/etc/rc.local' or `/etc/init.d/boot.local' to start additional services on bootup. To start up MySQL using this method, you could append something like the following to it:

/bin/sh -c 'cd /usr/local/mysql ; ./bin/safe_mysqld --user=mysql &'

グローバル設定ファイルである `/etc/my.cnf' に、 mysql.server の オプションを記述することも可能です。`/etc/my.cnf' ファイルは以下のような 記述になっています:

[mysqld]
datadir=/usr/local/mysql/var
socket=/var/tmp/mysql.sock
port=3306
user=mysql

[mysql_server]
basedir=/usr/local/mysql

mysql.server スクリプトは次のオプションを理解します: datadir, basedir そして pid-file.

次の表は、各起動スクリプトがオプションファイルからどのオプショングループを読み込むかを示しています:

Script Option groups
mysqld mysqld and server
mysql.server mysql.server, mysqld, and server
safe_mysqld mysql.server, mysqld, and server

See section `my.cnf' オプションファイル.

MySQL のアップグレード/ダウングレード

MySQL 形式とデータファイルは、MySQL が同じベースバージョ ンである限り、同じアーキテクチャ上の異なるバージョン間でいつでも移動でき ます。現在のベースバージョンは 3 です。MySQL の実行時に キャラクタ・セットが変更された場合(これはソート順も変更します)、全てのテーブル に myisamchk -r -q --set-character-set=charset を行なう必要があります。 そうしなければ、インデックスが正しい順になりません。

もしあなたが神経質だったり新しいバージョンを恐れている場合、いつでもあな たの古い mysqldmysqld-old-version-number のような何 かにリネームできます。もし新しい mysqld が予期せぬ何かを行った場 合、単純にそれをシャットダウンし、古い mysqld を再起動することが できます!

アップグレード時には、もちろん、古いデータベースをバックアップもしておく べきです。

アップグレード後、再コンパイルされたクライアントプログラムで、 Commands out sync や予期せぬコアダンプのような問題が起きる場合、 おそらく、プログラムのコンパイル時に古いヘッダやライブラリファイルを使用 したのでしょう。この場合、`mysql.h' ファイルと `libmysql.a' ラ イブラリが、新しい MySQL 配布からのものであるかどうかを確かめる ために、日付をチェックすべきです。もし違っていれば、プログラムを再コンパ イルしてください!

もし新しい mysqld サーバーが起動できないとか、パスワード無しで 接続できないとか、いくつかの問題が発生した場合、以前のインストールでできた 古い `my.cnf' ファイルがあるかどうかを確認してください! program-name --print-defaults で確認できます. もしこの出力が プログラムの名称以外の物を返した場合、有効になっている my.cnf ファイルが あります!

新しいリリースの MySQL をインストールした場合に常に Msql-Mysql-modules を再構築、再インストールすることは いい考えです。すべての DBI スクリプトが MySQL の アップグレード後にコアダンプする兆候に気づいた場合は、特に そうしてください。

Upgrading From Version 4.0 to Version 4.1

In general what you have to do when upgrading to 4.1 from an earlier MySQL version:

The following is a more complete lists tell what you have to watch out for when upgrading to version 4.1;

Note that the table definition format (.frm) has changed slightly in 4.1. MySQL 4.0.11 can read the new .frm format but older version can not. If you need to go move tables from 4.1 to and earlier MySQL version you should use mysqldump. See section mysqldump, データベースとテーブルから、構造とデータをダンプ.

バージョン 3.23 から バージョン 4.0 へのアップグレード

In general what you have to do when upgrading to 4.0 from an earlier MySQL version:

MySQL 4.0 will work even if you don't do the above, but you will not be able to use the new security privileges that MySQL 4.0 and you may run into problems when upgrading later to MySQL 4.1 or newer. The ISAM file format still works in MySQL 4.0 but it's deprecated and will be disabled in MySQL 5.0.

古いクライアントは、4.0 のサーバ と問題なく動作するはずです。

Even if you do the above, you can still downgrade to MySQL 3.23.52 or newer if you run into problems with the MySQL 4.0 series. In this case you have to do a mysqldump of any tables using a full-text index and restore these in 3.23 (because 4.0 uses a new format for full-text index).

次のリストは、バージョン 4.0 にアップグレードする際に気をつけなければなら ないことです;

バージョン 3.22 から バージョン 3.23 へのアップグレード

MySQL バージョン 3.23 は新しい MyISAM 型のテーブルと、 古い ISAM 型のテーブルをサポートします。 バージョン 3.23 を使用する際、古いテーブル(ISAM) を変換する必要はありません。 デフォルトでは、新しく作られるテーブルが MyISAM 型になります。 (これは mysqld--default-table-type=isam オプションで 起動することにより、変更できます)。 ISAM テーブルを MyISAM に変更するには、 ALTER TABLE table_name TYPE=MyISAM を使用するか、mysql_convert_table_format perl スクリプトを使用します。

バージョン 3.22 と バージョン 3.21 のクライアントは問題なく バージョン 3.23 サーバーで動作します。

以下に、バージョン 3.23 にアップグレードするときに、注目する必要があるものを列挙します:

バージョン 3.21 から バージョン 3.22 へのアップグレード

バージョン 3.21 と バージョン 3.22 の間には互換性に影響する変更はありません。

DATE 型のフィールドを持たせて作成した新しいテーブルは、 日付の格納に新しい方法を使用することだけが、唯一の落とし穴です。 これらの新しいフィールドに古いバージョンの mysqld からアクセスすることはできません。

MySQL バージョン 3.22 インストール後、新しいサーバを開始して、 mysql_fix_privilege_tables スクリプトを実行すべきです。これは GRANT コマンドを使用するために必要な権限を追加します。これを忘れ ると、ALTER TABLECREATE INDEXDROP INDEX を 使用しようとした時に Access denied になります。 MySQL root ユーザがパスワードを要求する場合、 mysql_fix_privilege_tables への引数としてそれを与えてください。

C API インタフェース mysql_real_connect() は変更されました。この 関数を呼び出す古いクライアントプログラムを持っている場合は、新しい db 引数に 0 を置く(またはより速い接続のために db 要 素を送るようにクライアントをコーディングしなおす)必要があります。 mysql_real_connect() を呼び出す前に mysql_init() を呼ばなくてはなりません! この変更は、MYSQL の構造体にオプションを保存するための 新しい mysql_options() 関数を有効にします。

mysqld 変数 key_bufferkey_buffer_size に名前が 変わりました。しかし、まだ前の名前もスターとアップファイル中で使用できま す。

バージョン 3.20 から バージョン 3.21 へのアップグレード

既に バージョン 3.20.28 より前のバージョンが稼働していて、バージョン 3.21.x に変更したい場合は、 次を行なう必要があります:

safe_mysqld --old-protocolmysqld 3.21 サーバを起動すれ ば、バージョン 3.20 配布からのクライアントでそれを使用できます。この場合、新しいク ライアント関数 mysql_errno() はサーバのエラーは何も返さず、 CR_UNKNOWN_ERROR だけを返します (ただしクライアントのエラーについ ては働きます)。そして サーバは古い password() チェックを新しいものの代わ りに使用します。

mysqld--old-protocol オプションを使わない場合、 次の変更をする必要があります:

MySQL バージョン 3.20.28 とそれ以降は、クライアントに影響を及ぼさずに、新 しい user テーブル形式を処理することができます。バージョン 3.20.28 より前の MySQL バージョンを持っている場合は、user テーブルを変換 すると、パスワードはその上ではもう働きません。安全のため、最初に少なくと も バージョン 3.20.28 にアップグレードし、それから バージョン 3.21.x に アップグレードすべきです。

新しいクライアントコードは バージョン 3.20.x mysqld サーバで動作するので、 もし バージョン 3.21.x で問題があった場合は、クライアントをもう一度再コンパイルする必 要はなく、古い バージョン 3.20.x サーバを使用することができます。

mysqld--old-protocol オプションを使用しない場合、古い クライアントはエラーメッセージを発します:

ERROR: Protocol mismatch. Server Version = 10 Client Version = 9

新しい Perl インタフェース DBI/DBD は古い mysqlperl インタフェースもサポートします。mysqlperl を使用する場合に行う必 要のある変更は、connect() 関数の引数の変更だけです。新しい引数は: host, database, user, password (userpassword 引数の順番が変更されました)。 See section The DBI Interface.

次の変更は古いアプリケーションでのクエリに影響します:

他のアーキテクチャへのアップグレード

もし、MySQL バージョン 3.23 を使用しているならば、 違うアーキテクチャのマシンに、.frm, .MYI,.MYD ファイルを コピーすることが出来ます。 ただし、両者間で、同じ浮動小数点のフォーマットをサポートしている場合に限ります。 (MySQL はどのようなバイト交換にも気をつけます)。

現在 MySQL ISAM データファイルとインデックスファイル ( `*.ISD'`*.ISM' ファイル) はアーキテクチャ依存で、 いくつかのケースでは OS 依存です。 アプリケーションを、現在のマシンとは異なるアーキテクチャ/OS を 持つ他のマシンに移したい場合は、単純にファイルを他のマシンにコピーするこ とでデータベースを移行しようとすべきではありません。mysqldump を 使用すべきです。

デフォルトでは mysqldump は、完全な SQL ステートメントファイルを 生成します。それからそのファイルを他のマシンへ転送し、mysql クラ イアントへの入力として与えることができます。

有効なオプションが何かを見るためには、mysqldump --help を試してく ださい。データを MySQL のより新しいバージョンに移す場合、速くコ ンパクトなダンプを得るために、より新しいバージョンで mysqldump --opt を使用すべきです。

2つのマシン間でデータベースを移動する最も簡単な (しかし最も速くはない) 方法は、データベースが置かれているマシン上で次のコマンドを実行することで す:

shell> mysqladmin -h 'other hostname' create db_name
shell> mysqldump --opt db_name \
        | mysql -h 'other hostname' db_name

遅いネットワーク上でリモートマシンからデータベースをコピーしたい場合は、 次を使用できます:

shell> mysqladmin create db_name
shell> mysqldump -h 'other hostname' --opt --compress db_name \
        | mysql db_name

You can also store the result in a file, then transfer the file to the target machine and load the file into the database there. For example, you can dump a database to a file on the source machine like this:

shell> mysqldump --quick db_name | gzip > db_name.contents.gz

(The file created in this example is compressed.) データベースの中身を含んでいるファイルを、目的のマシンに転送して、次のコ マンドを実行してください:

shell> mysqladmin create db_name
shell> gunzip < db_name.contents.gz | mysql db_name

データベース転送を実行するために、mysqldumpmysqlimport も使用できます。大きなテーブルでは、これは単純な mysqldump の使用 よりもとても速いです。次に示すコマンドでは、DUMPDIRmysqldump からの出力を格納するために使用するディレクトリの完全な パス名を表わしています。

まず、出力ファイルのためのディレクトリを作成して、データベースをダンプし ます:

shell> mkdir DUMPDIR
shell> mysqldump --tab=DUMPDIR db_name

それから、DUMPDIR ディレクトリ内のファイルを目的のマシン上の対応 するディレクトリに転送し、MySQL にファイルをロードします:

shell> mysqladmin create db_name           # create database
shell> cat DUMPDIR/*.sql | mysql db_name   # create tables in database
shell> mysqlimport db_name DUMPDIR/*.txt   # load data into tables

mysql データベースのコピーも忘れないでください。それは承認テーブ ル (user, db, host) が格納されるためです。 mysql データベースをその場所に置くまで、新しいマシン上では MySQL root ユーザとしてコマンドを実行する必要があります。

新しいマシン上へ mysql データベースを導入した後、サーバが承認テー ブル情報を再ロードするために、mysqladmin flush-privileges を実行してください。

Operating System Specific Notes

Linux Notes (All Linux Versions)

以下の注意は、glibc に関して、MySQL をあなた自身で作成す るシチュエーションだけに適用されます。Linux を x86 マシンで実行する場合、 多くの場合は我々のバイナリを使用した方が良いです。我々は glibc の 最良パッチバージョンと我々のバイナリをリンクします。我々は最良のコンパイラ オプションでそれを作成し、高負荷サーバについて適切になるように試みています。 以下のテキストを読んで、何をあなたがやるべきかについて迷った時は、あなたの 必要にかなうかどうかをみるために、我々のバイナリをまず試してください。そし て、我々のバイナリが十分でないとわかった後にだけ、あなた自身の作成について 考えてください。この場合、それについての評価します。そのため、次回にはより 良いバイナリを作成できます。典型的なユーザについて、そして、多くの同時接続 と 2G Bytes 制限を超えるテーブルを設定する場合でも、多くの場合、我々のバイナリ は最良の選択です。

Linux では MySQL は LinuxThreads を使用します。 もし glibc2 を持たない古い Linux を使用している場合、 MySQL のコンパイルの前に、 LinuxThreads をインストールしなければなりません。 LinuxThreads は http://www.mysql.com/downloads/os-linux.html. から得ることが できます。

注意: 我々は SMP システム上での Linux 2.2.14 と MySQL で奇妙な問 題を経験しました; SMP システムの場合、Linux 2.4 ASAP にアップグレードする ことをお勧めします! これを行なうことで、あなたのシステムはより速くより安 定するでしょう!

注意: 2.1.1 以前の glibc バージョンは pthread_mutex_timedwait 処理に致命的なバグがあります。これは INSERT DELAYED を行なう時に使用されます。glibc をアップグレードする 前に INSERT DELAYED は使用しないようにお奨めします。

1000以上の同時接続を使用する予定であれば、LinuxThreads にいくつかの変更 をして、再コンパイルし、MySQL を新しい `libpthread.a' を使用するように再リ ンクする必要があります。`sysdeps/unix/sysv/linux/bits/local_lim.h' 内の PTHREAD_THREADS_MAX を 4096 に増加し、 `linuxthreads/internals.h' 中の STACK_SIZE を 256 KB に減少させてください。注意: STACK_SIZE がデフォルトの 2MB である 場合、MySQL は 600-1000 程度の接続で安定でなくなります。

MySQL が十分なファイルをオープンまたは接続できないという問題を 得た場合、十分なファイルを操作するように構築された Linux を持っていない ということです。

Linux 2.2 以降では、割り当てられたファイル記述子の数を次のようにしてチェッ クできます:

cat /proc/sys/fs/file-max
cat /proc/sys/fs/dquot-max
cat /proc/sys/fs/super-max

16M 以上のメモリがある場合は、次のような何かを起動スクリプト(SuSE では `/etc/init.d/boot.local')に追加すべきです:

echo 65536 > /proc/sys/fs/file-max
echo 8192 > /proc/sys/fs/dquot-max
echo 1024 > /proc/sys/fs/super-max

上記は、root でコマンドラインからも実行できますが、この場合、コンピュータ をリブートすると古い制限が使われます。

You can also run the preceding commands from the command-line as root, but these settings will be lost the next time your computer reboots.

Alternatively, you can set these parameters on bootup by using the sysctl tool, which is used by many Linux distributions (SuSE has added it as well, beginning with SuSE Linux 8.0). Just put the following values into a file named `/etc/sysctl.conf':

# Increase some values for MySQL
fs.file-max = 65536
fs.dquot-max = 8192
fs.super-max = 1024

`/etc/my.cnf' にも追加すべきです:

[safe_mysqld]
open-files-limit=8192

上記は MySQL に、最大 8192 接続/ファイルを生成することを許可します。

The STACK_SIZE constant in LinuxThreads controls the spacing of thread stacks in the address space. It needs to be large enough so that there will be plenty of room for the stack of each individual thread, but small enough to keep the stack of some threads from running into the global mysqld data. Unfortunately, the Linux implementation of mmap(), as we have experimentally discovered, will successfully unmap an already mapped region if you ask it to map out an address already in use, zeroing out the data on the entire page, instead of returning an error. So, the safety of mysqld or any other threaded application depends on the "gentleman" behaviour of the code that creates threads. The user must take measures to make sure the number of running threads at any time is sufficiently low for thread stacks to stay away from the global heap. With mysqld, you should enforce this "gentleman" behaviour by setting a reasonable value for the max_connections variable.

If you build MySQL yourself and do not want to mess with patching LinuxThreads, you should set max_connections to a value no higher than 500. It should be even less if you have a large key buffer, large heap tables, or some other things that make mysqld allocate a lot of memory, or if you are running a 2.2 kernel with a 2G patch. If you are using our binary or RPM version 3.23.25 or later, you can safely set max_connections at 1500, assuming no large key buffer or heap tables with lots of data. The more you reduce STACK_SIZE in LinuxThreads the more threads you can safely create. We recommend the values between 128K and 256K.

多くの同時接続を使用したい場合は、fork 爆弾攻撃を避けようとして、子供の fork や複製について、プロセスにペナルティを課すという、バージョン 2.2 カー ネルの "機能" に悩まされるでしょう。これにより、あなたが並行クライアントの 数を増加するようには、MySQL がスケールしません。シングル CPU システムでは、 とても遅いスレッド生成で明らかにこれが見られます。これは、MySQL への接続に 長い時間(1分程度)が掛かり、それを切断するのにも長い時間掛かるということを 意味します。複数 CPU システムでは、クライアント数の増加に従って、クエリ速 度が徐々に落ちていくのが観測されました。問題の解決を見つけようとする処理の 中で、我々のユーザからカーネルパッチを受け取りました。我々はいくつかの限定 されたテストで、このパッチが MySQL のスケーラビリティを非常に改善した結果 を得ました。このパッチはここにあります http://www.mysql.com/Downloads/Patches/linux-fork.patch. We have now done rather extensive testing of this patch on both development and production systems. It has significantly improved MySQL performance without causing any problems and we now recommend it to our users who are still running high-load servers on 2.2 kernels. This issue has been fixed in the 2.4 kernel, so if you are not satisfied with the current performance of your system, rather than patching your 2.2 kernel, it might be easier to just upgrade to 2.4, which will also give you a nice SMP boost in addition to fixing this fairness bug.

We have tested MySQL on the 2.4 kernel on a 2-CPU machine and found MySQL scales much better@-there was virtually no slowdown on queries throughput all the way up to 1000 clients, and the MySQL scaling factor (computed as the ratio of maximum throughput to the throughput with one client) was 180%. We have observed similar results on a 4-CPU system@-virtually no slowdown as the number of clients was increased up to 1000, and 300% scaling factor. So for a high-load SMP server we would definitely recommend the 2.4 kernel at this point. We have discovered that it is essential to run mysqld process with the highest possible priority on the 2.4 kernel to achieve maximum performance. This can be done by adding renice -20 $$ command to safe_mysqld. In our testing on a 4-CPU machine, increasing the priority gave 60% increase in throughput with 400 clients.

We are currently also trying to collect more info on how well MySQL performs on 2.4 kernel on 4-way and 8-way systems. If you have access such a system and have done some benchmarks, please send a mail to docs@mysql.com with the results - we will include them in the manual.

There is another issue that greatly hurts MySQL performance, especially on SMP systems. The implementation of mutex in LinuxThreads in glibc-2.1 is very bad for programs with many threads that only hold the mutex for a short time. On an SMP system, ironic as it is, if you link MySQL against unmodified LinuxThreads, removing processors from the machine improves MySQL performance in many cases. We have made a patch available for glibc 2.1.3 to correct this behaviour (http://www.mysql.com/Downloads/Linux/linuxthreads-2.1-patch).

With glibc-2.2.2 MySQL version 3.23.36 will use the adaptive mutex, which is much better than even the patched one in glibc-2.1.3. Be warned, however, that under some conditions, the current mutex code in glibc-2.2.2 overspins, which hurts MySQL performance. The chance of this condition can be reduced by renicing mysqld process to the highest priority. We have also been able to correct the overspin behaviour with a patch, available at http://www.mysql.com/Downloads/Linux/linuxthreads-2.2.2.patch. It combines the correction of overspin, maximum number of threads, and stack spacing all in one. You will need to apply it in the linuxthreads directory with patch -p0 </tmp/linuxthreads-2.2.2.patch. We hope it will be included in some form in to the future releases of glibc-2.2. In any case, if you link against glibc-2.2.2 you still need to correct STACK_SIZE and PTHREAD_THREADS_MAX. We hope that the defaults will be corrected to some more acceptable values for high-load MySQL setup in the future, so that your own build can be reduced to ./configure; make; make install.

We recommend that you use the above patches to build a special static version of libpthread.a and use it only for statically linking against MySQL. We know that the patches are safe for MySQL and significantly improve its performance, but we cannot say anything about other applications. If you link other applications against the patched version of the library, or build a patched shared version and install it on your system, you are doing it at your own risk with regard to other applications that depend on LinuxThreads.

If you experience any strange problems during the installation of MySQL, or with some common utilties hanging, it is very likely that they are either library or compiler related. If this is the case, using our binary will resolve them.

一つ知られている問題として、バイナリ配布を libc5 の古い Linux システム (RedHat 4.x , Slackware 3.6 以下, Debian 1.3 bo 以下など) で使用すると、ホスト名解決の致命的なエラーが出ます. See section Linux Notes for Binary Distributions.

LinuxThreads を使用している場合、最低3つのプロセスが走ります。 これらは実スレッドで、一つは LinuxThreads マネージャーのために、 一つは接続のハンドルに、もうひとつはアラームとシグナルのハンドルです。

注意: linux カーネルと linuxthread ライブラリはデフォルトでは 1024 スレッ ドだけ持つことができます。これはパッチを適用していないシステム上では MySQL への接続は最大 1021 だけであるということを意味します。ページ http://www.volano.com/linuxnotes.html はこの制限をどのように回避 するかの情報が含まれています。

もし mysqld デーモンプロセスが ps などでみると死んでいるようであれば, 通常これは MySQL バグか、壊れたテーブルを持っています。 See section What To Do If MySQL Keeps Crashing.

Linux 上で、mysqld が SIGSEGV シグナルで死んだ時にコアダンプを得たい場合、 --core-file オプションを付けて mysqld を起動できます。注意: ulimit -c 1000000safe_mysqld に追加するか --core-file-size=1000000 をつけて safe_mysqld を起動して、 core file size を増加する必要があります。 See section safe_mysqld, The Wrapper Around mysqld.

もし MySQL クライアントをリンクしようとして以下のエラーになった場合:

ld.so.1: ./my: fatal: libmysqlclient.so.4:
open failed: No such file or directory

実行時には、以下のうちの一つの方法で問題を解決できます:

富士通コンパイラ (fcc / FCC) を使用している場合、MySQL のコンパイルにいくつかの問題があります。Linux ヘッダファイルはとても gcc 指向であるためです。

次の configure 行は fcc/FCC で動作します:

CC=fcc CFLAGS="-O -K fast -K lib -K omitfp -Kpreex -D_GNU_SOURCE \
-DCONST=const -DNO_STRTOLL_PROTO" CXX=FCC CXXFLAGS="-O -K fast -K lib \
-K omitfp -K preex --no_exceptions --no_rtti -D_GNU_SOURCE -DCONST=const \
-Dalloca=__builtin_alloca -DNO_STRTOLL_PROTO \
'-D_EXTERN_INLINE=static __inline'" ./configure --prefix=/usr/local/mysql \
--enable-assembler --with-mysqld-ldflags=-all-static --disable-shared \
--with-low-memory

Linux Notes for Binary Distributions

MySQL は少なくとも Linux バージョン 2.0 を必要とします。

Warning: We have reports from some MySQL users that they have got serious stability problems with MySQL with Linux kernel 2.2.14. If you are using this kernel you should upgrade to 2.2.19 (or newer) or to a 2.4 kernel. If you have a multi-cpu box, then you should seriously consider using 2.4 as this will give you a significant speed boost.

バイナリリリースは -static でリンクされており、これはあなたのシステムが どのバージョンのライブラリーを使用しているか気にする必要がありません。 よって、LinuxThreads もこの場合必要ありません。 -static でリンクされたプログラムのサイズは ダイナミックリンクされたプログラムより大きくなりますが、少し(3-5%)速くなります。 しかし一つの問題として、このスタティックリンクされたプログラムでは、 ユーザー定義関数(UDF)が使用できないことです。 もし UDF を使用する(書く)場合(C, C++とかで)、自分自身で MySQL を ダイナミックリンクを使用してコンパイルしなくてはなりません。

もし glibc2 ではなく libc ベースのシステムを使用しているなら、 このバイナリリリースではホスト名解決と getpwnam() にいくつか問題が出ます。 (これは glibc がホスト名解決と getpwent() にいくつかの外部ライブラリに 依存しているためで、たとえ -static リンクしても解決しません). この場合、mysql_install_db 実行時に以下のエラーが出るでしょう:

Sorry, the host 'xxxx' could not be looked up

あるいは、--user オプションで mysqld を起動しようとしたとき、 以下のエラーが出る場合:

getpwnam: No such file or directory

この問題は、以下のうちのどれかの方法で解決できます:

Linux-Intel binary と MySQL RPM リリースは、もっとも速くなるように 調整されています。我々はもっとも早く安定したコンパイラーを常に使用しています。

MySQL Perl サポートは Perl 5.004_03 以上のバージョンを必要としま す。

Linux 2.2 バージョンのいくつかでは、TCP/IP 上で mysqld サーバに多く の新しい接続を行なう時に、エラー Resource temporarily unavailable を得ることがあります。

この問題は、Linux では TCP/IP ソケットをクローズする時と、それがシステムに よって実際に解放される間に遅延があるためです。TCP/IP スロットの数は有限な ので、TCP/IP 上で MySQL `test-connect' ベンチマークを実行し た時のように、短い時間にとても多くの新しい TCP/IP 接続が行なわれた場合に上 記エラーが得られます。

我々はこの問題について、異なる Linux メーリングリストで何回かメールを受け ました。しかし、当然、我々はこれを解決することはできません。

この問題の知られている'解決策'は、あなたのクライアント内で永続的な接続を使 用するか、データベースサーバとクライアントが同じマシン上で実行されている場 合にソケットを使用することだけです。我々は、将来、Linux 2.4 カーネ ルでこの問題が解決されることを希望します。

Linux x86 Notes

MySQL は libc 5.4.12 以上が必要です。libc 5.4.46 で動作します。 glibc 2.0.6 以上でも動作します。 glibc の RPM にはいくつか問題があり、アップデートをチェックしてください。 glibc 2.0.7-19 と 2.0.7-29 RPM で動作します。

If you are using Red Hat 8.0 or a new glibc 2.2.x library you should start mysqld with the option --thread-stack=192K. If you don't do it mysqld will die in gethostbyaddr() because the new glibc library requires > 128K memory on stack for this call. This stack size is now the default on MySQL 4.0.10 and above.

If you are using gcc 3.0 and above to compile MySQL, you must install the libstdc++v3 library before compiling MySQL; if you don't do this you will get an error about a missing __cxa_pure_virtual symbol during linking!

古い Linux 配布物では、configure 時に以下のようなエラーが出るかもしれません:

Syntax error in sched.h. Change _P to __P in the /usr/include/sched.h file.
See the Installation chapter in the Reference Manual.

これは _P マクロが一つのアンダースコアしか持っていないためで、 このエラーメッセージに示されたように対処してください。

以下のようなワーニングは無視して構いません:

mysqld.cc -o objs-thread/mysqld.o
mysqld.cc: In function `void init_signals()':
mysqld.cc:315: warning: assignment of negative value `-1' to
`long unsigned int'
mysqld.cc: In function `void * signal_hand(void *)':
mysqld.cc:346: warning: assignment of negative value `-1' to
`long unsigned int'

Debian GNU/Linux では、MySQL をマシンの起動時に立ちあげるためには、 以下のようにします:

shell> cp support-files/mysql.server /etc/init.d/mysql.server
shell> /usr/sbin/update-rc.d mysql.server defaults 99

mysql.server スクリプトは MySQL をインストールした先の `share/mysql' directory にあります。 あるいは、MySQL のソースの中の `support-files' ディレクトリにあります。

mysqld がつねにスタート時にコアをはく場合、 古い `/lib/libc.a' を使用しているかもしれません。 `sql/mysqld' を消去して、新しく make install してみてください。 これはいくつかの Slackware で報告された現象です。

もし mysqld をリンクする場合に以下のようなエラーが出た場合、 `libg++.a' が正しくインストールされていません:

/usr/lib/libc.a(putc.o): In function `_IO_putc':
putc.o(.text+0x0): multiple definition of `_IO_putc'

`libg++.a' の使用を避けるには、 configure を以下のようにします:

shell> CXX=gcc ./configure

Linux SPARC Notes

いくつかの埋め込み関数, readdir_r() が壊れます。 この顕れとして、SHOW DATABASES が常に空を返します。 これは configure 後、コンパイルする前に、 `config.h' から HAVE_READDIR_R を取り除くことで解決します。

その他いくつかの問題は、あなたの Linux にパッチを当てる必要があります。 パッチは http://www.mysql.com/Downloads/patches/Linux-sparc-2.0.30.diff. にあります。 このパッチは、vger.rutgers.edu にある `sparclinux-2.0.30.tar.gz' 用です。 (これは正式の 2.0.30 とは違います。パッチを正式2.0.30に当てないように) そして LinuxThreads Version 0.6 かそれ以上にしなくてはなりません。

Linux Alpha Notes

MySQL Version 3.23.12 が、Linux-Alpha 上で最初にテストされたバージョンです。 もし MySQL を Linux-Alpha 上で使用したいと考えたなら、 このバージョンより新しいものを使用します。

We have tested MySQL on Alpha with our benchmarks and test suite, and it appears to work nicely.

We currently build the MySQL binary packages on SuSE Linux 7.0 for AXP, kernel 2.4.4-SMP, Compaq C compiler (V6.2-505) and Compaq C++ compiler (V6.3-006) on a Compaq DS20 machine with an Alpha EV6 processor.

You can find the above compilers at http://www.support.compaq.com/alpha-tools/). By using these compilers, instead of gcc, we get about 9-14% better performance with MySQL.

Note that until MySQL version 3.23.52 and 4.0.2 we optimised the binary for the current CPU only (by using the -fast compile option); this meant that you could only use our binaries if you had an Alpha EV6 processor.

Starting with all following releases we added the -arch generic flag to our compile options, which makes sure the binary runs on all Alpha processors. We also compile statically to avoid library problems.

CC=ccc CFLAGS="-fast -arch generic" CXX=cxx \
CXXFLAGS="-fast -arch generic -noexceptions -nortti" \
./configure --prefix=/usr/local/mysql --disable-shared \
--with-extra-charsets=complex --enable-thread-safe-client \
--with-mysqld-ldflags=-non_shared --with-client-ldflags=-non_shared

If you want to use egcs the following configure line worked for us:

CFLAGS="-O3 -fomit-frame-pointer" CXX=gcc \
CXXFLAGS="-O3 -fomit-frame-pointer -felide-constructors \
-fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql \
--disable-shared

Some known problems when running MySQL on Linux-Alpha:

Linux PowerPC Notes

MySQL は最新の glibc を使用した MkLinux で動作します。 (glibc 2.0.7 でテストしました).

Linux MIPS Notes

Qube2 (Linux Mips) 上で MySQL を動作させるには、 最新の glibc ライブラリでなくてはなりません (glibc-2.0.7-29C2 は動作することが分かっています)。 そして、 egcs C++ compiler (egcs-1.0.2-9, gcc 2.95.2 以上) を 使用しなくてはなりません。

Linux IA64 Notes

To get MySQL to compile on Linux IA64, we use the following compile line: Using gcc-2.96:

CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXX=gcc \
CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors \
-fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql \
"--with-comment=Official MySQL binary" --with-extra-charsets=complex

On IA64 the MySQL client binaries are using shared libraries. This means that if you install our binary distribution in some other place than `/usr/local/mysql' you need to either modify `/etc/ld.so.conf' or add the path to the directory where you have `libmysqlclient.so' to the LD_LIBRARY_PATH environment variable.

See section Problems When Linking with the MySQL Client Library.

Windows Notes

This section describes using MySQL on Windows. This information is also provided in the `README' file that comes with the MySQL Windows distribution. See section Windows への MySQL のインストール.

Starting MySQL on Windows 95, 98 or Me

MySQL は TCP/IP をクライアントからサーバーへの接続に使用します。 こうすればネットワーク上のどのマシンからでも MySQL サーバーに 接続できるようになります。 このため、MySQL を起動する前に、 あなたは TCP/IP をインストールしなくてはなりません。 これは Windows CD-ROM にあります。

もし古い Win95 (for example OSR2) を使用しているなら、 これは古い Winsock パッケージを使用しているかもしれません! MySQL は Winsock 2 を要求します! 最新の Winsock は http://www.microsoft.com/ にあります。 Win98 はデフォルトで新しい Winsock 2 ライブラリですので、 これは Win98 には当てはまりません。

mysqld サーバーを起動するには, MS-DOS を起動し、以下のように入力します:

C:\> C:\mysql\bin\mysqld

これは mysqld をバックグラウンドで動かします。

MySQL サーバーの kill には:

C:\> C:\mysql\bin\mysqladmin -u root shutdown

This calls the MySQL administation utility as user `root', which is the default Administrator in the MySQL grant system. Please note that the MySQL grant system is wholly independent from any login users under Windows.

注意: Win95 と Win98 は名前付パイプをサポートしていません。Win95 と Win98 では、Windows NT サーバホスト上で動いているリモートの MySQL への接続だけに、名前付パイプを使用できます。 (The MySQL server must also support named pipes, of course. For example, using mysqld-opt under NT/2000/XP will not allow named pipe connections. You should use either mysqld-nt or mysqld-max-nt.)

mysqld が起動しない場合、`\mysql\data\mysql.err' ファイルがそ の問題の原因を示す何らかのメッセージをサーバが書き出していないかチェック してください。mysqld --standalone でサーバの起動を試みることもでき ます; この場合、問題の解決の助けになるであろう、いくつかの有用な情報が画 面上で得られます。

最後の選択肢は mysqld--standalone --debug 付きで起動す ることです。この場合、mysqld はログをファイル `C:\mysqld.trace' に書き出します。これには、mysqld が何故起動 しないかの理由が含まれます。 See section Creating Trace Files.

Use mysqld --help to display all the options that mysqld understands!

Starting MySQL on Windows NT, 2000 or XP

NT 4 上で TCP/IP を用いて MySQL を動作させるには、service pack 3(以上) が必須です!

Normally you should install MySQL as a service on Windows NT/2000/XP. In case the server was already running, first stop it using the following command:

C:\mysql\bin> mysqladmin -u root shutdown

This calls the MySQL administation utility as user `root', which is the default Administrator in the MySQL grant system. Please note that the MySQL grant system is wholly independent from any login users under Windows.

Now install the server service:

C:\mysql\bin> mysqld-max-nt --install

If any options are required, they must be specified as ``Start parameters'' in the Windows Services utility before you start the MySQL service.

The Services utility (Windows Service Control Manager) can be found in the Windows Control Panel (under Administrative Tools on Windows 2000). It is advisable to close the Services utility while performing the --install or --remove operations, this prevents some odd errors.

For information about which server binary to run, see section Preparing the Windows MySQL Environment.

Please note that from MySQL version 3.23.44, you have the choice of set up the service as Manual instead (if you don't wish the service to be started automatically during the boot process):

C:\mysql\bin> mysqld-max-nt --install-manual

サービスは MySQL という名前で登録されます。 一度インストールしたら、 これは Services (コントロールパネルにある) を使用するか、NET START MySQL コマンドを使用するかして、 起動されなくてはなりません。

Once running, mysqld-max-nt can be stopped using mysqladmin, from the Services utility, or by using the command NET STOP MySQL.

When running as a service, the operating system will automatically stop the MySQL service on computer shutdown. In MySQL versions < 3.23.47, Windows only waited for a few seconds for the shutdown to complete, and killed the database server process if the time limit was exceeded (potentially causing problems). For instance, at the next startup the InnoDB storage engine had to do crash recovery. Starting from MySQL version 3.23.48, the Windows will wait longer for the MySQL server shutdown to complete. If you notice this is not enough for your intallation, it is safest to run the MySQL server not as a service, but from the Command prompt, and shut it down with mysqladmin shutdown.

There is a problem that Windows NT (but not Windows 2000/XP) by default only waits 20 seconds for a service to shut down, and after that kills the service process. You can increase this default by opening the Registry Editor `\winnt\system32\regedt32.exe' and editing the value of WaitToKillServiceTimeout at `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control' in the Registry tree. Specify the new larger value in milliseconds, for example 120000 to have Windows NT wait upto 120 seconds.

Please note that when run as a service, mysqld-max-nt has no access to a console and so no messages can be seen. Errors can be checked in `c:\mysql\data\mysql.err'.

もし mysqld-max-nt をサービスとしてインストールする場合に 問題が発生した場合、フルパスで実行してみてください:

C:\> C:\mysql\bin\mysqld-max-nt --install

If this doesn't work, you can get mysqld-max-nt to start properly by fixing the path in the registry!

サービスとして mysqld-max-nt を起動したくないなら以下のようにします:

C:\> C:\mysql\bin\mysqld-max-nt --standalone

or

C:\> C:\mysql\bin\mysqld --standalone --debug

最新のバージョンでは、デバッグのトレースを `C:\mysqld.trace' に出します。 See section Creating Trace Files.

Windows 上で MySQL を実行

MySQL supports TCP/IP on all Windows platforms and named pipes on NT/2000/XP. The default is to use named pipes for local connections on NT/2000/XP and TCP/IP for all other cases if the client has TCP/IP installed. The host name specifies which protocol is used:

Host name Protocol
NULL (none) On NT/2000/XP, try named pipes first; if that doesn't work, use TCP/IP. On 9x/Me, TCP/IP is used.
. Named pipes
localhost TCP/IP to current host
hostname TCP/IP

MySQL クライアントに named pipes を強制的に使用させるには、 --pipe オプションか、ホストに . を指定します。 そして、--socket オプションでパイプの名前を指定します。 In MySQL 4.1 you should use the --protocol=PIPE option.

Note that starting from 3.23.50, named pipes are only enabled if mysqld is started with --enable-named-pipe. This is because some users have experienced problems shutting down the MySQL server when one uses named pipes.

MySQL が動いているかどうかは、以下のようにして確認できます:

C:\> C:\mysql\bin\mysqlshow
C:\> C:\mysql\bin\mysqlshow -u root mysql
C:\> C:\mysql\bin\mysqladmin version status proc
C:\> C:\mysql\bin\mysql test

If mysqld is slow to answer to connections on Windows 9x/Me, there is probably a problem with your DNS. In this case, start mysqld with --skip-name-resolve and use only localhost and IP numbers in the MySQL grant tables. You can also avoid DNS when connecting to a mysqld-nt MySQL server running on NT/2000/XP by using the --pipe argument to specify use of named pipes. This works for most MySQL clients.

2つの MySQL コマンドラインツールがあります:
Binary Description
mysql ネイティブな Windows 用にコンパイルされている。非常に限られたコマンドライン編集機能しか持たない
mysqlc Cygnus GNU コンパイラとライブラリを用いてコンパイルされている。GNU readline によるコマンドライン編集機能を持つ。

もし mysqlc.exe を使用したいなら, `C:\mysql\lib\cygwinb19.dll' をあなたの Windows システムディレクトリ (`\windows\system' もしくは同様のパス)にコピーしなくてはなりません。

Windows の MySQL の初期の権限は、ローカルの全てのユーザーに 対して、全てのデータベースで全ての権限がパスワードなしに与えられています。 MySQL を安全にするために、全てのユーザーにパスワードを 設定すべきです。また、mysql.user テーブルから Host='localhost'User='' となっているレコードを 削除すべきです。

root ユーザーにもパスワードを設定すべきです。次の例では、 すべての権限を持つ匿名ユーザを削除したあとに、 root ユーザパスワードを設定しています:

C:\> C:\mysql\bin\mysql mysql
mysql> DELETE FROM user WHERE Host='localhost' AND User='';
mysql> QUIT
C:\> C:\mysql\bin\mysqladmin reload
C:\> C:\mysql\bin\mysqladmin -u root password your_password

パスワードを設定した後、もし mysqld サーバーを停止させるなら、 以下のようにします:

C:\> mysqladmin --user=root --password=your_password shutdown

もしあなたが Windows 下で、古い MySQL バージョン 3.21 のシェアウェ アバージョンを使用しているなら、上記のコマンドは次のエラーで失敗します: parse error near 'SET password'。回避策は、現在の MySQL バージョンにアップグレードすることです。これもフリーです。

現在の MySQL バージョンでは、GRANTREVOKE コ マンドで、簡単に新しいユーザを追加でき、権限を変更することができます。 See section GRANTREVOKE 構文.

SSH を利用してリモートの MySQL に Windows から接続

以下は SSH を用いてリモートの MySQL サーバに安全に接続するための 方法について述べたものです。 (by David Carlson dcarlson@mplcomm.com):

You should now have an ODBC connection to MySQL, encrypted using SSH.

Windows 上で、異なるディスクにデータを分割する

Windows 上では、3.23.16 以上のバージョンの MySQL ディストリビュー ション中の mysqld-maxmysql-max-nt サーバは、 -DUSE_SYMDIR オプション付きでコンパイルされています。これはデータ ベースに対するシンボリックリンクを追加することで異なるディスクにデータベー スを置くことを可能にします(Unix におけるシンボリック・リンクと同様の方法 で)。

Windows 上では、宛先ディレクトリへのパスを持つファイルを作成し、 そのファイルを database.sym というファイル名で mysql_data ディレクトリ の中に保存することで、データベースへのシンボリックリンクを作成します。 Note that the symbolic link will only be used if the directory mysql_data_dir\database doesn't exist.

例えば、MySQL データディレクトリが `C:\mysql\data' で、 `D:\data\foo' に置かれているデータベース foo を持ちたければ、 テキスト D:\data\foo\ を含む `C:\mysql\data\foo.sym' を作成す べきです。その後、データベース foo に作成されるすべてのテーブルは `D:\data\foo' に作成されるでしょう。

Note that because of the speed penalty you get when opening every table, we have not enabled this by default even if you have compiled MySQL with support for this. To enable symlinks you should put in your `my.cnf' or `my.ini' file the following entry:

[mysqld]
use-symbolic-links

In MySQL 4.0 we will enable symlinks by default. Then you should instead use the skip-symlink option if you want to disable this.

Windows 上で MySQL クライアントをコンパイルする

ソースファイル中で `mysql.h' をインクルードする前に `windows.h' を インクルードするべきです:

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
#include <mysql.h>

あなたのコードを、必要に応じて `libmysql.dll' 中でロードするための ラッパーである `libmysql.lib' ライブラリに動的にリンクすることも できますし、また `mysqlclient.lib' ライブラリを静的にリンクすることも できます。

mysqlclient ライブラリはスレッド対応ライブラリとしてコンパイル されていますので、あなたのコードもマルチスレッド対応になるように コンパイルするべきことに注意してください。

Windows 用 MySQL と Unix 用 MySQL の比較

MySQL-Windows バージョンは現在それ自体とても安定した(stableな)状態で供給されています。 MySQL-win32 バージョンは すべての機能が UNIX バージョンの MySQL と対応しています。 ただし、下記のような例外があります。

Win95 とスレッド
Win95は、各々のスレッドの作成のためにメインメモリのおよそ200バイトをメモリリーク します。もしあなたが多くの接続をすれば、MySQL の各々の接続が新しい スレッドを作成するので、あなたはWin95では長時間、mysqld を実行させるべきではあり ません! WindowsNT と Windows98 はこのバグを持ちません。
並行読み出し
MySQL は INSERTSELECT を混ぜることを可能にするために pread() 及び pwrite() 関数コールに依存します。現時点では pread()/pwrite() をエミュレートするために Mutex を用いています。長期的な計画では、 ファイルレベルのインターフェースを仮想インターフェースで置き換えて いくつもりなので、さらに速度を上げるために Windows NT/2000/XP 上で readfile()/writefile() インターフェースを使うことができます。 現在の実装は、しかし MySQL が利用可能なファイル数の上限が 1024 に なっています。これは Unix では可能な数の並行スレッドを NT/2000/XP 上では 動作させることができないことを意味しています。
ブロック読み込み
MySQL はそれぞれの接続のためにブロック読み込みを使います。 これは以下の事柄を意味しています: We plan to fix this problem when our Windows developers have figured out a nice workaround.
DROP DATABASE
複数のスレッドで使われているデータベースはDROPをすることができません。
タスクマネージャーからの MySQL の終了
Windows95では「Windowsの終了」やタスクマネージャから MySQL を終了することはできません。 mysqladmin shutdown で終了しなければなりません。
大文字小文字を区別しない名前
Windowsではファイルネームは大文字小文字が区別されません。 そのため、Windows用の MySQL では、テーブル名は大文字小文字が区別されません。 唯一の制限は、ステートメント(SQL文)中においては、データベースとテーブルの名前は 同じケース(大文字小文字)を使用して指定されなければならないという点です。 See section 名前のケース依存性.
The `\' directory character
Windows 95のパス名コンポーネントは、 `\' によって離されますが、その文字は同じく MySQL のエスケープ文字でもあります。もしあなたが LOAD DATA INFILE または SELECT ... INTO OUTFILE を使う場合には、`\' を二重に使わなくてはなりません。
mysql> LOAD DATA INFILE "C:\\tmp\\skr.txt" INTO TABLE skr;
mysql> SELECT * INTO OUTFILE 'C:\\tmp\\skr.txt' FROM skr;
かわりに、UNIX でのファイルネーム形式 `/' で書く必要があります。
mysql> LOAD DATA INFILE "C:/tmp/skr.txt" INTO TABLE skr;
mysql> SELECT * INTO OUTFILE 'C:/tmp/skr.txt' FROM skr;
Can't open named pipe エラー
もしあなたが NT 上で最新の mysql-clients と MySQL 3.22 バージョン を使えば、あなたは、次のエラーを得ることになるはずです:
error 2017: can't open named pipe to host: . pipe...
これは、MySQL のリリースバージョンがデフォルトで NT の 名前つきパイプを 使っているために起こっています。 新しい MySQL クライアントで --host=localhost オプションを用いるか、 以下の情報を含むオプションファイル `C:\my.cnf' を作成することで、このエラーを 回避することができます。
[client]
host = localhost
Starting from 3.23.50, named pipes are only enabled if mysqld is started with --enable-named-pipe.
Access denied for user error
もしあなたが同じマシン上の MySQL サーバーにアクセスした時 Access denied for user: 'some-user@unknown' to database 'mysql' エラーを得るなら、これはあなたの MySQL があなた のマシンのホスト名を正しく解決できてないことを意味します。 これを修正するには、 以下の情報を持つファイル `\windows\hosts' を作成するべきです。 (注:Windows95,98には\Windowsフォルダ上にサンプルとして「lmhosts.sam」ファイルが 既にあるはずです)
127.0.0.1       localhost
ALTER TABLE
ALTER TABLE ステートメントの実行中、テーブルは他のスレッドが使用できないようロック されます。これは Windows が他のスレッドによって使用中のファイルを削除 できないという事実のためにしなければならないことです(私たちはこの 問題を回避するための方法を将来見出すかもしれません)。
DROP TABLE on a table that is in use by a MERGE table will not work on Windows because the MERGE handler does the table mapping hidden from the upper layer of MySQL. Because Windows doesn't allow you to drop files that are open, you first must flush all MERGE tables (with FLUSH TABLES) or drop the MERGE table before dropping the table. We will fix this at the same time we introduce VIEWs.
DATA DIRECTORY and INDEX DIRECTORY directives in CREATE TABLE is ignored on Windows, because Windows doesn't support symbolic links.

Here are some open issues for anyone who might want to help us with the Windows release:

他の Windows 特有の事柄は MySQL-Windows ディストリビューションに同梱されている `README' ファイルで説明されています。

Solaris Notes

Solaris では MySQL ソースを展開するときトラブルが出るでしょう! Solaris の tar は長い名前を扱えず、 MySQL を展開する場合、 以下のようなエラーになります:

x mysql-3.22.12-beta/bench/Results/ATIS-mysql_odbc-NT_4.0-cmp-db2,\
informix,ms-sql,mysql,oracle,solid,sybase, 0 bytes, 0 tape blocks
tar: directory checksum error

この場合、GNU tar (gtar) を展開に使用してください。 コンパイルずみのものが以下にあります: http://www.mysql.com/downloads/os-solaris.html.

Sun ネイティブスレッドは Solaris 2.5 以上で動きます。 バージョン 2.4 以下の場合、MySQL は時動的に MIT-pthreads を使用します See section MIT-pthreads に関して.

もし、configure 時に、以下のエラーが出たなら:

checking for restartable system calls... configure: error can not run test
programs while cross compiling

これはコンパイラーのインストールでなにかを間違っています! この場合、あなたは、より新しいバージョンへコンパイラーをアップグレードすべきです。 以下の行を config.cache ファイルに追加することによって、 この問題を解決してもかまいません:

ac_cv_sys_restartable_syscalls=${ac_cv_sys_restartable_syscalls='no'}

もしあなたが SPARC の Solaris を使用しているなら、 gcc 2.95.2 を推奨します。 これは ttp://gcc.gnu.org/. で見つけれます。 egcs 1.1.1 と gcc 2.8.1 は SPARC 上では完全に動作しないことに注意!

gcc 2.95.2 を使用した、推奨する configure は:

CC=gcc CFLAGS="-O3" \
CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" \
./configure --prefix=/usr/local/mysql --with-low-memory --enable-assembler

If you have an UltraSPARC, you can get 4% more performance by adding "-mcpu=v8 -Wa,-xarch=v8plusa" to CFLAGS and CXXFLAGS.

If you have Sun's Forte 5.0 (or newer) compiler, you can run configure like this:

CC=cc CFLAGS="-Xa -fast -native -xstrconst -mt" \
CXX=CC CXXFLAGS="-noex -mt" \
./configure --prefix=/usr/local/mysql --enable-assembler

You can create a 64 bit binary with:

CC=cc CFLAGS="-Xa -fast -native -xstrconst -mt -xarch=v9" \
CXX=CC CXXFLAGS="-noex -mt -xarch=v9" ASFLAGS="-xarch=v9" \
./configure --prefix=/usr/local/mysql --enable-assembler

In the MySQL benchmarks, we got a 4% speedup on an UltraSPARC when using Forte 5.0 in 32 bit mode compared to using gcc 3.2 with -mcpu flags.

If you create a 64 bit binary, it's 4 % slower than the 32 bit binary, but mysqld can instead handle more treads and memory.

If you get a problem with fdatasync or sched_yield, you can fix this by adding LIBS=-lrt to the configure line

The following paragraph is only relevant for older compilers than WorkShop 5.3:

You may also have to edit the configure script to change this line:

#if !defined(__STDC__) || __STDC__ != 1

to this:

#if !defined(__STDC__)

もし -Xc オプションで __STDC__ を有効にした場合、 Sun compiler は Solaris の `pthread.h' ヘッダーファイルを使用して コンパイルすることができません。 これはサンのバグです(インクルードファイルかコンパイラーのバグ)

もし mysqld を起動時に以下のエラーが出た場合、 マルチスレッドを外して(オプション -mt を指定) Sun compiler を使って MySQL をコンパイルし直してください:

libc internal error: _rmutex_unlock: rmutex not held

-mtCFLAGSCXXFLAGS に加えます。

If you are using the SFW version of gcc (which comes with Solaris 8), you must add `/opt/sfw/lib' to the environment variable LD_LIBRARY_PATH before running configure.

If you are using the gcc available from sunfreeware.com, you may have many problems. You should recompile gcc and GNU binutils on the machine you will be running them from to avoid any problems.

If you get the following error when compiling MySQL with gcc, it means that your gcc is not configured for your version of Solaris:

shell> gcc -O3 -g -O2 -DDBUG_OFF  -o thr_alarm ...
./thr_alarm.c: In function `signal_hand':
./thr_alarm.c:556: too many arguments to function `sigwait'

The proper thing to do in this case is to get the newest version of gcc and compile it with your current gcc compiler! At least for Solaris 2.5, almost all binary versions of gcc have old, unusable include files that will break all programs that use threads (and possibly other programs)!

Solaris は スタテックリンクのシステムライブラリーを用意していません (libpthreads and libdl)。 そのため、--static オプションで MySQL をコンパイルできません。 もしこれを試みた場合、以下のエラーになります:

ld: fatal: library -ldl: not found

or

undefined reference to `dlopen'

or

cannot find -lrt

もし多くのプロセスが速く mysqld に接続を試みた場合、 MySQL ログに以下のようにエラーが出ます:

Error in accept: Protocol error

サーバーを --set-variable back_log=50 オプションで起動すれば、この問題に対処できるでしょう。 Please note that --set-variable is deprecated since MySQL 4.0, just use --back_log=50 on its own. See section mysqld コマンド行オプション.

もし自分の MySQL クライアントプログラムをリンクして 実行時に以下のようにエラーが出た場合:

ld.so.1: ./my: fatal: libmysqlclient.so.#:
open failed: No such file or directory

これは以下のどれかで回避できます:

configure や MySQL が -lz のリンクを試み、あなたがそれを インストールしていないという問題がある場合は、2つの選択肢があります:

If you are using gcc and have problems with loading UDF functions into MySQL, try adding -lgcc to the link line for the UDF function.

MySQL を自動的に開始させたい場合、 `support-files/mysql.server'`/etc/init.d' にコピーし、 /etc/rc3.d/S99mysql.server という名前でシンボリックリンクを生成し てください。

As Solaris doesn't support core files for setuid() applications, you can't get a core file from mysqld if you are using the --user option.

Solaris 2.7/2.8 Notes

通常、Solaris 2.6 のバイナリは Solaris 7 , 8 で使用できます。 ほとんどの Solaris 2.6 の問題も Solaris 7 , 8 に適用できます。

注意: MySQL Version 3.23.4 以上では、新しいバージョンの Solaris を自動 検出し、以下の問題についての回避策を有効にします!

Solaris 7 , 8 は、インクルードファイルにいくつかバグがあります。 gcc で以下のようなエラーが出た場合:

/usr/include/widec.h:42: warning: `getwc' redefined
/usr/include/wchar.h:326: warning: this is the location of the previous
definition

以下のようにして回避します:

/usr/include/widec.h.../lib/gcc-lib/os/gcc-version/include にコピー 41 行目を変更:

変更前:
#if     !defined(lint) && !defined(__lint)

変更後:

#if     !defined(lint) && !defined(__lint) && !defined(getwc)

代わりに、`/usr/include/widec.h' を直接変更してもかまいません。 どちらの方法にしても、ファイルを修正後は、`config.cache' を 消して configure を再実行しなくてはなりません!

make 実行時に以下のようなエラーになった場合、configure`curses.h' ファイルを検出できていません (これは /usr/include/widec.h の エラーのためにおきます):

In file included from mysql.cc:50:
/usr/include/term.h:1060: syntax error before `,'
/usr/include/term.h:1081: syntax error before `;'

これを解決するには、以下のうち一つを行います:

クライアントプログラムのリンク時に、リンカが -lz を見つけられない という問題が発生した場合、問題はおそらく `libz.so' ファイルが `/usr/local/lib' にインストールされたことです。次の方法の一つでこれ を修正できます:

Solaris x86 Notes

On Solaris 2.8 on x86, mysqld will core dump if you run 'strip' in. (訳注: GNU binutils を Sun 上で使用すると、CPU, version にかかわらず、 この現象に遭遇します。その場合は、/usr/ccs/bin/ の方を使います。)

gccegcs を Solaris x86 で使用した場合、load 時にコアダンプする場合、 以下のように configure します:

CC=gcc CFLAGS="-O3 -fomit-frame-pointer -DHAVE_CURSES_H" \
CXX=gcc \
CXXFLAGS="-O3 -fomit-frame-pointer -felide-constructors -fno-exceptions \
-fno-rtti -DHAVE_CURSES_H" \
./configure --prefix=/usr/local/mysql

これは libstdc++ ライブラリーと C++ の問題を回避します。

もしこれが該当しない場合、デバッグモードでコンパイルして デバッグのトレースファイルを書き出すようにして起動するか、 gdb を使用して起動してください. See section Debugging mysqld under gdb.

BSD Notes

This section provides information for the various BSD flavours, as well as specific versions within those.

FreeBSD Notes

FreeBSD 3.x is recommended for running MySQL since the thread package is much more integrated.

The easiest and therefore the preferred way to install is to use the mysql-server and mysql-client ports available on http://www.freebsd.org/.

Using these gives you:

It is recommended you use MIT-pthreads on FreeBSD 2.x and native threads on Versions 3 and up. It is possible to run with native threads on some late 2.2.x versions but you may encounter problems shutting down mysqld.

The MySQL `Makefile's require GNU make (gmake) to work. If you want to compile MySQL you need to install GNU make first.

Be sure to have your name resolver setup correct. Otherwise, you may experience resolver delays or failures when connecting to mysqld.

Make sure that the localhost entry in the `/etc/hosts' file is correct (otherwise, you will have problems connecting to the database). The `/etc/hosts' file should start with a line:

127.0.0.1       localhost localhost.your.domain

The recommended way to compile and install MySQL on FreeBSD with gcc (2.95.2 and up) is:

CC=gcc CFLAGS="-O2 -fno-strength-reduce" \
CXX=gcc CXXFLAGS="-O2 -fno-rtti -fno-exceptions -felide-constructors \
-fno-strength-reduce" \
./configure --prefix=/usr/local/mysql --enable-assembler
gmake
gmake install
./scripts/mysql_install_db
cd /usr/local/mysql
./bin/mysqld_safe &

If you notice that configure will use MIT-pthreads, you should read the MIT-pthreads notes. See section MIT-pthreads に関して.

If you get an error from make install that it can't find `/usr/include/pthreads', configure didn't detect that you need MIT-pthreads. This is fixed by executing these commands:

shell> rm config.cache
shell> ./configure --with-mit-threads

FreeBSD is also known to have a very low default file handle limit. See section File Not Found. Uncomment the ulimit -n section in safe_mysqld or raise the limits for the mysqld user in /etc/login.conf (and rebuild it with cap_mkdb /etc/login.conf). Also be sure you set the appropriate class for this user in the password file if you are not using the default (use: chpass mysqld-user-name). See section safe_mysqld, The Wrapper Around mysqld.

If you have a lot of memory you should consider rebuilding the kernel to allow MySQL to take more than 512M of RAM. Take a look at option MAXDSIZ in the LINT config file for more info.

If you get problems with the current date in MySQL, setting the TZ variable will probably help. See section Environment Variables.

To get a secure and stable system you should only use FreeBSD kernels that are marked -RELEASE.

NetBSD notes

To compile on NetBSD you need GNU make. Otherwise, the compile will crash when make tries to run lint on C++ files.

OpenBSD 2.5 Notes

On OpenBSD Version 2.5, you can compile MySQL with native threads with the following options:

CFLAGS=-pthread CXXFLAGS=-pthread ./configure --with-mit-threads=no

OpenBSD 2.8 Notes

Our users have reported that OpenBSD 2.8 has a threading bug which causes problems with MySQL. The OpenBSD Developers have fixed the problem, but as of January 25th, 2001, it's only available in the ``-current'' branch. The symptoms of this threading bug are: slow response, high load, high CPU usage, and crashes.

If you get an error like Error in accept:: Bad file descriptor or error 9 when trying to open tables or directories, the problem is probably that you haven't allocated enough file descriptors for MySQL.

In this case try starting safe_mysqld as root with the following options:

--user=mysql --open-files-limit=2048

BSD/OS Version 2.x Notes

If you get the following error when compiling MySQL, your ulimit value for virtual memory is too low:

item_func.h: In method `Item_func_ge::Item_func_ge(const Item_func_ge &)':
item_func.h:28: virtual memory exhausted
make[2]: *** [item_func.o] Error 1

Try using ulimit -v 80000 and run make again. If this doesn't work and you are using bash, try switching to csh or sh; some BSDI users have reported problems with bash and ulimit.

If you are using gcc, you may also use have to use the --with-low-memory flag for configure to be able to compile `sql_yacc.cc'.

If you get problems with the current date in MySQL, setting the TZ variable will probably help. See section Environment Variables.

BSD/OS Version 3.x Notes

Upgrade to BSD/OS Version 3.1. If that is not possible, install BSDIpatch M300-038.

Use the following command when configuring MySQL:

shell> env CXX=shlicc++ CC=shlicc2 \
       ./configure \
           --prefix=/usr/local/mysql \
           --localstatedir=/var/mysql \
           --without-perl \
           --with-unix-socket-path=/var/mysql/mysql.sock

The following is also known to work:

shell> env CC=gcc CXX=gcc CXXFLAGS=-O3 \
       ./configure \
           --prefix=/usr/local/mysql \
           --with-unix-socket-path=/var/mysql/mysql.sock

You can change the directory locations if you wish, or just use the defaults by not specifying any locations.

If you have problems with performance under heavy load, try using the --skip-thread-priority option to mysqld! This will run all threads with the same priority; on BSDI Version 3.1, this gives better performance (at least until BSDI fixes their thread scheduler).

If you get the error virtual memory exhausted while compiling, you should try using ulimit -v 80000 and run make again. If this doesn't work and you are using bash, try switching to csh or sh; some BSDI users have reported problems with bash and ulimit.

BSD/OS Version 4.x Notes

BSDI Version 4.x has some thread-related bugs. If you want to use MySQL on this, you should install all thread-related patches. At least M400-023 should be installed.

On some BSDI Version 4.x systems, you may get problems with shared libraries. The symptom is that you can't execute any client programs, for example, mysqladmin. In this case you need to reconfigure not to use shared libraries with the --disable-shared option to configure.

Some customers have had problems on BSDI 4.0.1 that the mysqld binary after a while can't open tables. This is because some library/system related bug causes mysqld to change current directory without asking for this!

The fix is to either upgrade to 3.23.34 or after running configure remove the line #define HAVE_REALPATH from config.h before running make.

Note that the above means that you can't symbolic link a database directories to another database directory or symbolic link a table to another database on BSDI! (Making a symbolic link to another disk is okay).

Mac OS X Notes

Mac OS X 10.x

MySQL should work without any problems on Mac OS X 10.x (Darwin). You don't need the pthread patches for this OS!

This also applies to Mac OS X 10.x Server. Compiling for the Server platform is the same as for the client version of Mac OS X. However please note that MySQL comes preinstalled on the Server!

See section Installing MySQL on Mac OS X.

Mac OS X Server 1.2 (Rhapsody)

Before trying to configure MySQL on Mac OS X server you must first install the pthread package from http://www.prnet.de/RegEx/mysql.html.

Our binary for Mac OS X is compiled on Darwin 6.3 with the following configure line:

CC=gcc CFLAGS="-O3 -fno-omit-frame-pointer" CXX=gcc \
CXXFLAGS="-O3 -fno-omit-frame-pointer -felide-constructors \
-fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql \
--with-extra-charsets=complex --enable-thread-safe-client \
--enable-local-infile --disable-shared

You might want to also add aliases to your shell's resource file to access mysql and mysqladmin from the command-line:

alias mysql '/usr/local/mysql/bin/mysql'
alias mysqladmin '/usr/local/mysql/bin/mysqladmin'

Alternatively, you could simply add /usr/local/mysql/bin to your PATH environment variable, e.g. by adding the following to `$HOME/.tcshrc':

setenv PATH $PATH:/usr/local/bin

Other Unix Notes

HP-UX Notes for Binary Distributions

Some of the binary distributions of MySQL for HP-UX are distributed as an HP depot file and as a tar file. To use the depot file you must be running at least HP-UX 10.x to have access to HP's software depot tools.

The HP version of MySQL was compiled on an HP 9000/8xx server under HP-UX 10.20, and uses MIT-pthreads. It is known to work well under this configuration. MySQL Version 3.22.26 and newer can also be built with HP's native thread package.

Other configurations that may work:

The following configurations almost definitely won't work:

To install the distribution, use one of the commands here, where /path/to/depot is the full pathname of the depot file:

The depot places binaries and libraries in `/opt/mysql' and data in `/var/opt/mysql'. The depot also creates the appropriate entries in `/etc/init.d' and `/etc/rc2.d' to start the server automatically at boot time. Obviously, this entails being root to install.

To install the HP-UX tar.gz distribution, you must have a copy of GNU tar.

HP-UX Version 10.20 Notes

There are a couple of small problems when compiling MySQL on HP-UX. We recommend that you use gcc instead of the HP-UX native compiler, because gcc produces better code!

We recommend using gcc 2.95 on HP-UX. Don't use high optimisation flags (like -O6) as this may not be safe on HP-UX.

The following configure line should work with gcc 2.95:

CFLAGS="-I/opt/dce/include -fpic" \
CXXFLAGS="-I/opt/dce/include -felide-constructors -fno-exceptions \
-fno-rtti" CXX=gcc ./configure --with-pthread \
--with-named-thread-libs='-ldce' --prefix=/usr/local/mysql --disable-shared

The following configure line should work with gcc 3.1:

CFLAGS="-DHPUX -I/opt/dce/include -O3 -fPIC" CXX=gcc \
CXXFLAGS="-DHPUX -I/opt/dce/include -felide-constructors -fno-exceptions \
-fno-rtti -O3 -fPIC" ./configure --prefix=/usr/local/mysql \
--with-extra-charsets=complex --enable-thread-safe-client \
--enable-local-infile  --with-pthread \
--with-named-thread-libs=-ldce --with-lib-ccflags=-fPIC
--disable-shared

HP-UX Version 11.x Notes

For HP-UX Version 11.x we recommend MySQL Version 3.23.15 or later.

Because of some critical bugs in the standard HP-UX libraries, you should install the following patches before trying to run MySQL on HP-UX 11.0:

PHKL_22840 Streams cumulative
PHNE_22397 ARPA cumulative

This will solve the problem of getting EWOULDBLOCK from recv() and EBADF from accept() in threaded applications.

If you are using gcc 2.95.1 on an unpatched HP-UX 11.x system, you will get the error:

In file included from /usr/include/unistd.h:11,
                 from ../include/global.h:125,
                 from mysql_priv.h:15,
                 from item.cc:19:
/usr/include/sys/unistd.h:184: declaration of C function ...
/usr/include/sys/pthread.h:440: previous declaration ...
In file included from item.h:306,
                 from mysql_priv.h:158,
                 from item.cc:19:

The problem is that HP-UX doesn't define pthreads_atfork() consistently. It has conflicting prototypes in `/usr/include/sys/unistd.h':184 and `/usr/include/sys/pthread.h':440 (details below).

One solution is to copy `/usr/include/sys/unistd.h' into `mysql/include' and edit `unistd.h' and change it to match the definition in `pthread.h'. Here's the diff:

183,184c183,184
<      extern int pthread_atfork(void (*prepare)(), void (*parent)(),
<                                                void (*child)());
---
>      extern int pthread_atfork(void (*prepare)(void), void (*parent)(void),
>                                                void (*child)(void));

After this, the following configure line should work:

CFLAGS="-fomit-frame-pointer -O3 -fpic" CXX=gcc \
CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti -O3" \
./configure --prefix=/usr/local/mysql --disable-shared

If you are using MySQL 4.0.5 with the HP-UX compiler you can use: (tested with cc B.11.11.04):

CC=cc CXX=aCC CFLAGS=+DD64 CXXFLAGS=+DD64 ./configure --with-extra-character-set=complex

You can ignore any errors of the following type:

aCC: warning 901: unknown option: `-3': use +help for online documentation

If you get the following error from configure

checking for cc option to accept ANSI C... no
configure: error: MySQL requires a ANSI C compiler (and a C++ compiler).
Try gcc. See the Installation chapter in the Reference Manual.

Check that you don't have the path to the K&R compiler before the path to the HP-UX C and C++ compiler.

Another reason for not beeing able to compile is that you didn't define the +DD64 flags above.

IBM-AIX notes

Automatic detection of xlC is missing from Autoconf, so a configure command something like this is needed when compiling MySQL (This example uses the IBM compiler):

export CC="xlc_r -ma -O3 -qstrict -qoptimize=3 -qmaxmem=8192 "
export CXX="xlC_r -ma -O3 -qstrict -qoptimize=3 -qmaxmem=8192"
export CFLAGS="-I /usr/local/include"
export LDFLAGS="-L /usr/local/lib"
export CPPFLAGS=$CFLAGS
export CXXFLAGS=$CFLAGS

./configure --prefix=/usr/local \
		--localstatedir=/var/mysql \
		--sysconfdir=/etc/mysql \
		--sbindir='/usr/local/bin' \
		--libexecdir='/usr/local/bin' \
		--enable-thread-safe-client \
		--enable-large-files

Above are the options used to compile the MySQL distribution that can be found at http://www-frec.bull.com/.

If you change the -O3 to -O2 in the above configure line, you must also remove the -qstrict option (this is a limitation in the IBM C compiler).

If you are using gcc or egcs to compile MySQL, you must use the -fno-exceptions flag, as the exception handling in gcc/egcs is not thread-safe! (This is tested with egcs 1.1.) There are also some known problems with IBM's assembler, which may cause it to generate bad code when used with gcc.

We recommend the following configure line with egcs and gcc 2.95 on AIX:

CC="gcc -pipe -mcpu=power -Wa,-many" \
CXX="gcc -pipe -mcpu=power -Wa,-many" \
CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti" \
./configure --prefix=/usr/local/mysql --with-low-memory

The -Wa,-many is necessary for the compile to be successful. IBM is aware of this problem but is in to hurry to fix it because of the workaround available. We don't know if the -fno-exceptions is required with gcc 2.95, but as MySQL doesn't use exceptions and the above option generates faster code, we recommend that you should always use this option with egcs / gcc.

If you get a problem with assembler code try changing the -mcpu=xxx to match your CPU. Typically power2, power, or powerpc may need to be used, alternatively you might need to use 604 or 604e. I'm not positive but I would think using "power" would likely be safe most of the time, even on a power2 machine.

If you don't know what your CPU is then do a "uname -m", this will give you back a string that looks like "000514676700", with a format of xxyyyyyymmss where xx and ss are always 0's, yyyyyy is a unique system id and mm is the id of the CPU Planar. A chart of these values can be found at http://publib.boulder.ibm.com/doc_link/en_US/a_doc_lib/cmds/aixcmds5/uname.htm. This will give you a machine type and a machine model you can use to determine what type of CPU you have.

If you have problems with signals (MySQL dies unexpectedly under high load) you may have found an OS bug with threads and signals. In this case you can tell MySQL not to use signals by configuring with:

shell> CFLAGS=-DDONT_USE_THR_ALARM CXX=gcc \
       CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti \
       -DDONT_USE_THR_ALARM" \
       ./configure --prefix=/usr/local/mysql --with-debug --with-low-memory

This doesn't affect the performance of MySQL, but has the side effect that you can't kill clients that are ``sleeping'' on a connection with mysqladmin kill or mysqladmin shutdown. Instead, the client will die when it issues its next command.

On some versions of AIX, linking with libbind.a makes getservbyname core dump. This is an AIX bug and should be reported to IBM.

For AIX 4.2.1 and gcc you have to do the following changes.

After configuring, edit `config.h' and `include/my_config.h' and change the line that says

#define HAVE_SNPRINTF 1

to

#undef HAVE_SNPRINTF

And finally, in `mysqld.cc' you need to add a prototype for initgoups.

#ifdef _AIX41
extern "C" int initgroups(const char *,int);
#endif

If you need to allocate a lot of memory to the mysqld process, it's not enough to just set 'ulimit -d unlimited'. You may also have to set in mysqld_safe something like:

export LDR_CNTRL='MAXDATA=0x80000000'

You can find more about using a lot of memory at: http://publib16.boulder.ibm.com/pseries/en_US/aixprggd/genprogc/lrg_prg_support.htm.

SunOS 4 Notes

On SunOS 4, MIT-pthreads is needed to compile MySQL, which in turn means you will need GNU make.

Some SunOS 4 systems have problems with dynamic libraries and libtool. You can use the following configure line to avoid this problem:

shell> ./configure --disable-shared --with-mysqld-ldflags=-all-static

When compiling readline, you may get warnings about duplicate defines. These may be ignored.

When compiling mysqld, there will be some implicit declaration of function warnings. These may be ignored.

Alpha-DEC-UNIX Notes (Tru64)

If you are using egcs 1.1.2 on Digital Unix, you should upgrade to gcc 2.95.2, as egcs on DEC has some serious bugs!

When compiling threaded programs under Digital Unix, the documentation recommends using the -pthread option for cc and cxx and the libraries -lmach -lexc (in addition to -lpthread). You should run configure something like this:

CC="cc -pthread" CXX="cxx -pthread -O" \
./configure --with-named-thread-libs="-lpthread -lmach -lexc -lc"

When compiling mysqld, you may see a couple of warnings like this:

mysqld.cc: In function void handle_connections()':
mysqld.cc:626: passing long unsigned int *' as argument 3 of
accept(int,sockadddr *, int *)'

You can safely ignore these warnings. They occur because configure can detect only errors, not warnings.

If you start the server directly from the command-line, you may have problems with it dying when you log out. (When you log out, your outstanding processes receive a SIGHUP signal.) If so, try starting the server like this:

shell> nohup mysqld [options] &

nohup causes the command following it to ignore any SIGHUP signal sent from the terminal. Alternatively, start the server by running safe_mysqld, which invokes mysqld using nohup for you. See section safe_mysqld, The Wrapper Around mysqld.

If you get a problem when compiling mysys/get_opt.c, just remove the line #define _NO_PROTO from the start of that file!

If you are using Compac's CC compiler, the following configure line should work:

CC="cc -pthread"
CFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed all -arch host"
CXX="cxx -pthread"
CXXFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed all -arch host \
-noexceptions -nortti"
export CC CFLAGS CXX CXXFLAGS
./configure \
--prefix=/usr/local/mysql \
--with-low-memory \
--enable-large-files \
--enable-shared=yes \
--with-named-thread-libs="-lpthread -lmach -lexc -lc"
gnumake

If you get a problem with libtool, when compiling with shared libraries as above, when linking mysql, you should be able to get around this by issuing:

cd mysql
/bin/sh ../libtool --mode=link cxx -pthread  -O3 -DDBUG_OFF \
-O4 -ansi_alias -ansi_args -fast -inline speed \
-speculate all \ -arch host  -DUNDEF_HAVE_GETHOSTBYNAME_R \
-o mysql  mysql.o readline.o sql_string.o completion_hash.o \
../readline/libreadline.a -lcurses \
../libmysql/.libs/libmysqlclient.so  -lm
cd ..
gnumake
gnumake install
scripts/mysql_install_db

Alpha-DEC-OSF/1 Notes

If you have problems compiling and have DEC CC and gcc installed, try running configure like this:

CC=cc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 \
./configure --prefix=/usr/local/mysql

If you get problems with the `c_asm.h' file, you can create and use a 'dummy' `c_asm.h' file with:

touch include/c_asm.h
CC=gcc CFLAGS=-I./include \
CXX=gcc CXXFLAGS=-O3 \
./configure --prefix=/usr/local/mysql

Note that the following problems with the ld program can be fixed by downloading the latest DEC (Compaq) patch kit from: http://ftp.support.compaq.com/public/unix/.

On OSF/1 V4.0D and compiler "DEC C V5.6-071 on Digital Unix V4.0 (Rev. 878)" the compiler had some strange behaviour (undefined asm symbols). /bin/ld also appears to be broken (problems with _exit undefined errors occuring while linking mysqld). On this system, we have managed to compile MySQL with the following configure line, after replacing /bin/ld with the version from OSF 4.0C:

CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql

With the Digital compiler "C++ V6.1-029", the following should work:

CC=cc -pthread
CFLAGS=-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all \
       -arch host
CXX=cxx -pthread
CXXFLAGS=-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all \
          -arch host -noexceptions -nortti
export CC CFLAGS CXX CXXFLAGS
./configure --prefix=/usr/mysql/mysql --with-mysqld-ldflags=-all-static \
            --disable-shared --with-named-thread-libs="-lmach -lexc -lc"

In some versions of OSF/1, the alloca() function is broken. Fix this by removing the line in `config.h' that defines 'HAVE_ALLOCA'.

The alloca() function also may have an incorrect prototype in /usr/include/alloca.h. This warning resulting from this can be ignored.

configure will use the following thread libraries automatically: --with-named-thread-libs="-lpthread -lmach -lexc -lc".

When using gcc, you can also try running configure like this:

shell> CFLAGS=-D_PTHREAD_USE_D4 CXX=gcc CXXFLAGS=-O3 ./configure ...

If you have problems with signals (MySQL dies unexpectedly under high load), you may have found an OS bug with threads and signals. In this case you can tell MySQL not to use signals by configuring with:

shell> CFLAGS=-DDONT_USE_THR_ALARM \
       CXXFLAGS=-DDONT_USE_THR_ALARM \
       ./configure ...

This doesn't affect the performance of MySQL, but has the side effect that you can't kill clients that are ``sleeping'' on a connection with mysqladmin kill or mysqladmin shutdown. Instead, the client will die when it issues its next command.

With gcc 2.95.2, you will probably run into the following compile error:

sql_acl.cc:1456: Internal compiler error in `scan_region', at except.c:2566
Please submit a full bug report.

To fix this you should change to the sql directory and do a ``cut and paste'' of the last gcc line, but change -O3 to -O0 (or add -O0 immediately after gcc if you don't have any -O option on your compile line). After this is done you can just change back to the top-level directly and run make again.

SGI Irix Notes

If you are using Irix Version 6.5.3 or newer mysqld will only be able to create threads if you run it as a user with CAP_SCHED_MGT privileges (like root) or give the mysqld server this privilege with the following shell command:

shell> chcap "CAP_SCHED_MGT+epi" /opt/mysql/libexec/mysqld

You may have to undefine some things in `config.h' after running configure and before compiling.

In some Irix implementations, the alloca() function is broken. If the mysqld server dies on some SELECT statements, remove the lines from `config.h' that define HAVE_ALLOC and HAVE_ALLOCA_H. If mysqladmin create doesn't work, remove the line from `config.h' that defines HAVE_READDIR_R. You may have to remove the HAVE_TERM_H line as well.

SGI recommends that you install all of the patches on this page as a set: http://support.sgi.com/surfzone/patches/patchset/6.2_indigo.rps.html

At the very minimum, you should install the latest kernel rollup, the latest rld rollup, and the latest libc rollup.

You definitely need all the POSIX patches on this page, for pthreads support:

http://support.sgi.com/surfzone/patches/patchset/6.2_posix.rps.html

If you get the something like the following error when compiling `mysql.cc':

"/usr/include/curses.h", line 82: error(1084): invalid combination of type

Type the following in the top-level directory of your MySQL source tree:

shell> extra/replace bool curses_bool < /usr/include/curses.h \
> include/curses.h
shell> make

There have also been reports of scheduling problems. If only one thread is running, things go slow. Avoid this by starting another client. This may lead to a 2-to-10-fold increase in execution speed thereafter for the other thread. This is a poorly understood problem with Irix threads; you may have to improvise to find solutions until this can be fixed.

If you are compiling with gcc, you can use the following configure command:

CC=gcc CXX=gcc CXXFLAGS=-O3 \
./configure --prefix=/usr/local/mysql --enable-thread-safe-client \
--with-named-thread-libs=-lpthread

On Irix 6.5.11 with native Irix C and C++ compilers ver. 7.3.1.2, the following is reported to work

CC=cc CXX=CC CFLAGS='-O3 -n32 -TARG:platform=IP22 -I/usr/local/include \
-L/usr/local/lib' CXXFLAGS='-O3 -n32 -TARG:platform=IP22 \
-I/usr/local/include -L/usr/local/lib' ./configure \
--prefix=/usr/local/mysql --with-innodb --with-berkeley-db \
--with-libwrap=/usr/local \
--with-named-curses-libs=/usr/local/lib/libncurses.a

Caldera (SCO) Notes

The current port is tested only on a ``sco3.2v5.0.4'' and ``sco3.2v5.0.5'' system. There has also been a lot of progress on a port to ``sco 3.2v4.2''.

For the moment the recommended compiler on OpenServer is gcc 2.95.2. With this you should be able to compile MySQL with just:

CC=gcc CXX=gcc ./configure ... (options)
  1. For OpenServer 5.0.X you need to use gcc-2.95.2p1 or newer from the Skunkware. http://www.caldera.com/skunkware/ and choose browser OpenServer packages or by ftp to ftp2.caldera.com in the pub/skunkware/osr5/devtools/gcc directory.
  2. You need the port of GCC 2.5.x for this product and the Development system. They are required on this version of Caldera (SCO) Unix. You cannot just use the GCC Dev system.
  3. You should get the FSU Pthreads package and install it first. This can be found at http://www.cs.wustl.edu/~schmidt/ACE_wrappers/FSU-threads.tar.gz. You can also get a precompiled package from http://www.mysql.com/Downloads/SCO/FSU-threads-3.5c.tar.gz.
  4. FSU Pthreads can be compiled with Caldera (SCO) Unix 4.2 with tcpip. Or OpenServer 3.0 or Open Desktop 3.0 (OS 3.0 ODT 3.0), with the Caldera (SCO) Development System installed using a good port of GCC 2.5.x ODT or OS 3.0 you will need a good port of GCC 2.5.x There are a lot of problems without a good port. The port for this product requires the SCO Unix Development system. Without it, you are missing the libraries and the linker that is needed.
  5. To build FSU Pthreads on your system, do the following:
    1. Run ./configure in the `threads/src' directory and select the SCO OpenServer option. This command copies `Makefile.SCO5' to `Makefile'.
    2. Run make.
    3. To install in the default `/usr/include' directory, login as root, then cd to the `thread/src' directory, and run make install.
  6. Remember to use GNU make when making MySQL.
  7. If you don't start safe_mysqld as root, you probably will get only the default 110 open files per process. mysqld will write a note about this in the log file.
  8. With SCO 3.2V5.0.5, you should use FSU Pthreads version 3.5c or newer. You should also use gcc 2.95.2 or newer! The following configure command should work:
    shell> ./configure --prefix=/usr/local/mysql --disable-shared
    
  9. With SCO 3.2V4.2, you should use FSU Pthreads version 3.5c or newer. The following configure command should work:
    shell> CFLAGS="-D_XOPEN_XPG4" CXX=gcc CXXFLAGS="-D_XOPEN_XPG4" \
           ./configure \
               --prefix=/usr/local/mysql \
               --with-named-thread-libs="-lgthreads -lsocket -lgen -lgthreads" \
               --with-named-curses-libs="-lcurses"
    
    You may get some problems with some include files. In this case, you can find new SCO-specific include files at http://www.mysql.com/Downloads/SCO/SCO-3.2v4.2-includes.tar.gz. You should unpack this file in the `include' directory of your MySQL source tree.

Caldera (SCO) development notes:

If you want to install DBI on Caldera (SCO), you have to edit the `Makefile' in DBI-xxx and each subdirectory.

Note that the following assumes gcc 2.95.2 or newer:

OLD:                                  NEW:
CC = cc                               CC = gcc
CCCDLFLAGS = -KPIC -W1,-Bexport       CCCDLFLAGS = -fpic
CCDLFLAGS = -wl,-Bexport              CCDLFLAGS =

LD = ld                               LD = gcc -G -fpic
LDDLFLAGS = -G -L/usr/local/lib       LDDLFLAGS = -L/usr/local/lib
LDFLAGS = -belf -L/usr/local/lib      LDFLAGS = -L/usr/local/lib

LD = ld                               LD = gcc -G -fpic
OPTIMISE = -Od                        OPTIMISE = -O1

OLD:
CCCFLAGS = -belf -dy -w0 -U M_XENIX -DPERL_SCO5 -I/usr/local/include

NEW:
CCFLAGS = -U M_XENIX -DPERL_SCO5 -I/usr/local/include

This is because the Perl dynaloader will not load the DBI modules if they were compiled with icc or cc.

Perl works best when compiled with cc.

Caldera (SCO) Unixware Version 7.0 Notes

You must use a version of MySQL at least as recent as Version 3.22.13 because that version fixes some portability problems under Unixware.

We have been able to compile MySQL with the following configure command on Unixware Version 7.0.1:

CC=cc CXX=CC ./configure --prefix=/usr/local/mysql

If you want to use gcc, you must use gcc 2.95.2 or newer.

Caldera provides libsocket.so.2 at ftp://stage.caldera.com/pub/security/tools for pre-OSR506 security fixes. Also, the telnetd fix at ftp://stage.caldera.com/pub/security/openserver/CSSA-2001-SCO.10/ as both libsocket.so.2 and libresolv.so.1 with instructions for installing on pre-OSR506 systems.

It's probably a good idea to install the above patches before trying to compile/use MySQL.

OS/2 Notes

MySQL uses quite a few open files. Because of this, you should add something like the following to your `CONFIG.SYS' file:

SET EMXOPT=-c -n -h1024

If you don't do this, you will probably run into the following error:

File 'xxxx' not found (Errcode: 24)

When using MySQL with OS/2 Warp 3, FixPack 29 or above is required. With OS/2 Warp 4, FixPack 4 or above is required. This is a requirement of the Pthreads library. MySQL must be installed in a partition that supports long filenames such as HPFS, FAT32, etc.

The `INSTALL.CMD' script must be run from OS/2's own `CMD.EXE' and may not work with replacement shells such as `4OS2.EXE'.

The `scripts/mysql-install-db' script has been renamed. It is now called `install.cmd' and is a REXX script, which will set up the default MySQL security settings and create the WorkPlace Shell icons for MySQL.

Dynamic module support is compiled in but not fully tested. Dynamic modules should be compiled using the Pthreads run-time library.

gcc -Zdll -Zmt -Zcrtdll=pthrdrtl -I../include -I../regex -I.. \
    -o example udf_example.cc -L../lib -lmysqlclient udf_example.def
mv example.dll example.udf

Note: Due to limitations in OS/2, UDF module name stems must not exceed 8 characters. Modules are stored in the `/mysql2/udf' directory; the safe-mysqld.cmd script will put this directory in the BEGINLIBPATH environment variable. When using UDF modules, specified extensions are ignored@-it is assumed to be `.udf'. For example, in Unix, the shared module might be named `example.so' and you would load a function from it like this:

mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example.so";

Is OS/2, the module would be named `example.udf', but you would not specify the module extension:

mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example";

BeOS Notes

We are really interested in getting MySQL to work on BeOS, but unfortunately we don't have any person who knows BeOS or has time to do a port.

We are interested in finding someone to do a port, and we will help them with any technical questions they may have while doing the port.

We have previously talked with some BeOS developers that have said that MySQL is 80% ported to BeOS, but we haven't heard from them in a while.

Novell NetWare Notes

We are really interested in getting MySQL to work on NetWare, but unfortunately we don't have any person who knows NetWare or has time to do a port.

We are interested in finding someone to do a port, and we will help them with any technical questions they may have while doing the port.

Perl Installation Comments

Installing Perl on Unix

MySQLのPerlでの使用に関するサポートは DBI/DBDクライアントインターフェスの提供で行なわれます。 See section MySQL Perl API. DBI/DBDはPerl5.004かそれ以上のバージョンが必要になります。 古いバージョンのPerlでは動きません

MySQL の Perl support にはここまでで既にインストールが済んでいる筈の MySQL のクライアントプログラミングサポートが必要となります。 もしも RPM ファイルからインストールをされているのならば クライアントプログラムはクライアントRPMにあるものの、 クライアントプログラミングサポートはデベロッパー RPM にあります。 まずデベロッパー RPM をインストールされたがどうかお確かめ下さい。

バージョン3.22.8からは Perl support がメインの MySQL 配布ファイルとは別になっています。 もし Perl support が必要であれば http://www.mysql.com/downloads/api-dbi.html. からお取りください。

Perl関係プログラムのの配布はtar形式圧縮ファイルとして行われており、 ファイル名が `MODULE-VERSION.tar.gz' の形式になっています。 ここで、MODULEはモジュール名称、VERSIONはバージョン番号を表しています。 Data-DumperDBI、及び、Msql-Mysql-modulesを入手してインストールしてください。 インストール手順は以下に示す通りです。なお、ここではData-Dumperのみの手順が示されていますが、 他のモジュールについても同様な手順でインストールできます。

  1. 以下のようにして作業ディレクトリで配布ファイルを伸長・展開してください。
    shell> gunzip < Data-Dumper-VERSION.tar.gz | tar xvf -
    
    This command creates a directory named `Data-Dumper-VERSION'.
  2. 展開先のトップディレクトリーに移動します。
    shell> cd Data-Dumper-VERSION
    
  3. コンパイル&ビルドを行います。
    shell> perl Makefile.PL
    shell> make
    shell> make test
    shell> make install
    

出来上がったモジュールの動作を確認するためにmake testのコマンドは重要になってきます。 このコマンドをMsql-Mysql-modulesをインストールしている時に使ってみてください。 MySQLサーバが動いていなければ失敗することになります。

MySQLをバージョンアップした際に DBI が core ダンプした場合は 必ず Msql-Mysql-modules を再コンパイルしてインストールしなおしてください。 そうでなくても MySQL のバージョンを変更した場合は再コンパイルしたほうが賢明です。

貴方のユーザ権限ではPerlのモジュールをインストールできない場合でも 以下の例のようにしてローカルディレクトリにモジュールをインストールできます。

http://www.iserver.com/support/contrib/perl5/modules.html

Installing New Modules that Require Locally Installed Modules. という見出しの文書をご覧下さい。

Installing ActiveState Perl on Windows

DBDモジュールとActiveState Perlをインストールするには以下の手順で行います。

以上でActiveState Perlのバージョン5.6がとりあえず動くことになります。

もしも動作しない場合は次のように MyODBC ドライバーをインストールして ODBC経由でMySQLサーバに接続する必要があります。

use DBI;
$dbh= DBI->connect("DBI:ODBC:$dsn","$user","$password") ||
  die "Got error $DBI::errstr when connecting to $dsn\n";

Installing the MySQL Perl Distribution on Windows

MySQL Perlの配布パッケージにはDBIDBD:MySQL、そして、DBD:ODBCが含まれています。

Problems Using the Perl DBI/DBD Interface

Perl が "`../mysql/mysql.so'を見つけられない" というメッセージを出した場合、 それは多分 Perl のシェアードライブラリ `libmysqlclient.so' を見つけることが出来ないのでしょう。

これは以下のような方法で解決できます。

DBD-mysql が次のようなエラーを発生する場合があります。 この原因の一つは gcc(又はgccでコンパイルされた古いバイナリ配布パッケージ)をお使いのケースです。

/usr/bin/perl: can't resolve symbol '__moddi3'
/usr/bin/perl: can't resolve symbol '__divdi3'

`mysql.so' ライブラリをビルドする時に -L/usr/lib/gcc-lib/... -lgcc を リンクコマンドに追加してください(makeコマンド実行時の出力をチェックすれば確認できます。)。 オプション-Lで指定されるのはlibgcc.aのあるディレクトリになります。

もう一つの原因はPerlとMySQLのどちからがgccでコンパイルされており、どちらかがそうでない場合です。 この場合はどちらもgccでコンパイルし、この不一致を解消すれば解決します。

Msql-Mysql-modulesがテストで次のようなエラーを出した時、

t/00base............install_driver(mysql) failed:
Can't load '../blib/arch/auto/DBD/mysql/mysql.so' for module DBD::mysql:
../blib/arch/auto/DBD/mysql/mysql.so: undefined symbol:
uncompress at /usr/lib/perl5/5.00503/i586-linux/DynaLoader.pm line 169.

これは、ファイル圧縮用ライブラリ -lz へのパスを追加すれば解決いたします。 `lib/DBD/mysql/Install.pm' に以下のような変更を行ってください。

$sysliblist .= " -lm";

to

$sysliblist .= " -lm -lz";

After this, you must run 'make realclean' and then proceed with the installation from the beginning.

このあと'make realclean'を実行し、最初からインストールをやり直す必要があります。

Caldera (SCO) のようなダイナミックリンクが使用できないシステムで Perl モジュールを使用する際は DBIDBD-mysqlをスタティックリンクしたバージョンのPerlを作成する必要があります。 DBDをスタティックにリンクするには、Perlのインストールディレクトリに DBIのプログラムを置きDBDをリンクし、インストールします。

Caldera (SCO) では以下のような環境変数をセットする必要があります。

shell> LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/progressive/lib
or
shell> LD_LIBRARY_PATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:\
/usr/progressive/lib:/usr/skunk/lib
shell> LIBPATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:\
/usr/progressive/lib:/usr/skunk/lib
shell> MANPATH=scohelp:/usr/man:/usr/local1/man:/usr/local/man:\
/usr/skunk/man:

DBI をスタティックにリンクしたPerlを作成するためには、 先ず以下のコマンドを DBI がインストールされているディレクトリで実行してください。

shell> perl Makefile.PL -static -config
shell> make
shell> make install
shell> make perl

次に新しいPerlをインストールします。 通常 make perl でインストールに必要なファイル類を作成しますが、 Caldera (SCO)の場合は make -f Makefile.aperl inst_perl MAP_TARGET=perl のように行う必要があります。

次に、ここで作成された Perl で目的の DBD::mysql をスタティックにリンクされた Perl を作成するために使います。 Msql-Mysql-modules がインストールされたディレクトリで以下のようなコマンドを実行してください。

shell> perl Makefile.PL -static -config
shell> make
shell> make install
shell> make perl

最後に、この新しいPerlプログラムをインストールしてください。 make perlで必要なコマンドを再確認することができます。

Tutorial Introduction

この章では、 mysql クライアントプログラムの使用の仕方と 単純なデータベースの作成と使用の仕方を例題としてとり上げます。 mysql (``terminal monitor'' や ``monitor'' として参照されます)は MySQL サーバーに接続できる対話モードのプログラムで、 クエリの実行や結果の表示が可能です。 mysql はバッチモードも可能です: クエリをまずファイルに書いておき、 そしてそのファイルを mysql に実行させます。 どちらの方法でも mysql はこの章の説明でカバーされます。

mysql の提供するオプションを見るには、 --help オプションを 実行します:

shell> mysql --help

この章では mysql が既にあなたのマシンにインストールされているものとし、 また MySQL サーバーに接続可能であるとします。 もしそうでないなら、 あなたの MySQL 管理者に連絡を取ってください。 (もしあなた自身が管理者なら、このマニュアルの他のセクションを参照してください。)

本章ではデータベース設定の全体のプロセス、データベースの使用について述べます。 もしあなたが既に存在しているデータベースにアクセスする事だけに興味があるなら、 この章のデータベース、テーブルの作成方法の説明を読み飛ばしてもかまいません。

この章が本質的にはチュートリアルであるので、多くの詳細は、かならず違う章にあります。 ここに書かれている事柄で、 さらに詳しい情報についてはマニュアルの適切なセクションを調べて下さい。

サーバーへの接続と切断

サーバーに mysql コマンドから接続するためには、通常、 MySQL ユーザ名、パスワードを指定する必要があるでしょう。 もしあなたがログインしている以外のマシンの上でサーバーが走っていれば、 あなたは、ホスト名を明示する必要があるでしょう。 まずあなたの管理者に問い合わせて、あなたが使うべき接続のためのパラメーターを見つけ出して下さい。 (すなわち、どのようなホスト、ユーザー名とパスワードを使うべきなのか。) 適切なパラメーターを知っていれば、あなたは、以下のようにして接続できます:

shell> mysql -h host -u user -p
Enter password: ********

******** とかかれている部分にはあなたのパスワードを入れます; mysqlEnter password: プロンプトを出したときに。

きちんと動けば、いくつかの情報と mysql> プロンプトが現れます:

shell> mysql -h host -u user -p
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 459 to server version: 3.22.20a-log

Type 'help' for help.

mysql>

このプロンプトは mysql がコマンド入力を待っている状態を示します。

いくつかの MySQL インストレーションでは、ローカルホストで 実行されているサーバーに、ユーザーに``匿名''(名前無し)の接続を許しています。 もしあなたのマシンがこの場合に当てはまるなら、mysql をオプション無しで 起動すべきです:

shell> mysql

接続が成功した後、 mysql> プロンプトで、QUIT とタイプすれば いつでも接続を切ることができます:

mysql> QUIT
Bye

Control-D で切断してもかまいません。

以下のセクションでのほとんどの例では、あなたがサーバーに接続しているものと しています。その場合は mysql> プロンプトによって、それを示しています。

Entering Queries

前のセクションで述べたように、あなたがサーバーとつながっていることを確かめて下さい。 この状態ではまだどんなデータベースも選択していない状態です。しかしそれはかまいません。 ここでは、テーブルの作成やデータの入力、取り出しよりも、 いかにクエリを発行するかに重点を置きます。 このセクションでは、あなた自身を mysql の動きに慣れさせるために、 あなたがやってみることができるであろう、いくつかのクエリを使用して、 コマンド入力の基本的な原則を述べます。

サーバーのバージョン、今日の日付をサーバーに問い合わせる、単純なコマンド がここにあります。 以下のように mysql> プロンプトの後に入力し RETURN キーを押してみてください:

mysql> SELECT VERSION(), CURRENT_DATE;
+--------------+--------------+
| VERSION()    | CURRENT_DATE |
+--------------+--------------+
| 3.22.20a-log | 1999-03-19   |
+--------------+--------------+
1 row in set (0.01 sec)
mysql>

このクエリは、mysql のいくつかの事を説明しています:

キーワードは、いかなる大文字小文字でも記述できます。 以下に示すクエリは同じです:

mysql> SELECT VERSION(), CURRENT_DATE;
mysql> select version(), current_date;
mysql> SeLeCt vErSiOn(), current_DATE;

以下のクエリは、mysql を簡単な計算機として使用した例です:

mysql> SELECT SIN(PI()/4), (4+1)*5;
+-------------+---------+
| SIN(PI()/4) | (4+1)*5 |
+-------------+---------+
|    0.707107 |      25 |
+-------------+---------+

今までは見てきたたコマンドは、比較的短い、一行のの文です。 あなたは一行に複数、文を書くことが出来ます。 それぞれの文の終わりにはセミコロンを付けます:

mysql> SELECT VERSION(); SELECT NOW();
+--------------+
| VERSION()    |
+--------------+
| 3.22.20a-log |
+--------------+

+---------------------+
| NOW()               |
+---------------------+
| 1999-03-19 00:15:33 |
+---------------------+

コマンドは一行にかく必要もありません。 複数行にわたる長いコマンドでも問題ありません。 mysql はセミコロンで、一文の終わりと見なします。 その行の最後を文の最後とは 見なしません。 (いうなれば、mysql は自由な入力を許し、セミコロンが現れるまでは それらの入力された行を実行しません)

複数行にまたがった文の例です:

mysql> SELECT
    -> USER()
    -> ,
    -> CURRENT_DATE;
+--------------------+--------------+
| USER()             | CURRENT_DATE |
+--------------------+--------------+
| joesmith@localhost | 1999-03-18   |
+--------------------+--------------+

この例では、複数にまたがるクエリにおいて、最初の行の入力のあと、 いかにプロンプトが mysql> から -> に変わるかを示しています。 これは mysql が、まだ文が終わっておらず、残りの部分の入力を待っている ことを示します。プロンプトは役立つフィードバックを提供してくれるあなたの友 人です。そのフィードバックを使用すると、mysql が何を待っているのか にいつも気が付くでしょう。

入力中にコマンドの実行を取りやめようと思った場合、 \c でこれをキャンセルできます:

mysql> SELECT
    -> USER()
    -> \c
mysql>

ここでもプロンプトに注意してください。\c のタイプ後に mysql> に戻っています。mysql が新しいコマンドの準備ができた ことを示すフィードバックを提供しています。

次のテーブルはあなたが目にするであろう各プロンプトと、それらが意味する mysql がどの状態にあるかについての要約です:

プロンプト 意味
mysql> 新しいコマンドの待状態
-> 複数行にまたがるコマンドの、次の行の入力を待っている状態。
'> シングルクオート (`'') で始められた文字の、次の行の入力を待っている状態。
"> ダブルクオート (`"') で始められた文字の、次の行の入力を待っている状態。

あなたが文をセミコロンで終わらすことを忘れて実行した場合に、 複数行の入力待ちが起こります。 この場合、 mysql は 次の入力を待ちます:

mysql> SELECT USER()
    ->

If this happens to you (you think you've entered a statement but the only response is a -> prompt), most likely mysql is waiting for the semicolon. If you don't notice what the prompt is telling you, you might sit there for a while before realising what you need to do. Enter a semicolon to complete the statement, and mysql will execute it:

mysql> SELECT USER()
    -> ;
+--------------------+
| USER()             |
+--------------------+
| joesmith@localhost |
+--------------------+

The '> and "> prompts occur during string collection. In MySQL, you can write strings surrounded by either `'' or `"' characters (for example, 'hello' or "goodbye"), and mysql lets you enter strings that span multiple lines. When you see a '> or "> prompt, it means that you've entered a line containing a string that begins with a `'' or `"' quote character, but have not yet entered the matching quote that terminates the string. That's fine if you really are entering a multiple-line string, but how likely is that? Not very. More often, the '> and "> prompts indicate that you've inadvertantly left out a quote character. For example:

mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30;
    ">

If you enter this SELECT statement, then press Enter and wait for the result, nothing will happen. Instead of wondering why this query takes so long, notice the clue provided by the "> prompt. It tells you that mysql expects to see the rest of an unterminated string. (Do you see the error in the statement? The string "Smith is missing the second quote.)

At this point, what do you do? The simplest thing is to cancel the command. However, you cannot just type \c in this case, because mysql interprets it as part of the string that it is collecting! Instead, enter the closing quote character (so mysql knows you've finished the string), then type \c:

mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30;
    "> "\c
mysql>

The prompt changes back to mysql>, indicating that mysql is ready for a new command.

It's important to know what the '> and "> prompts signify, because if you mistakenly enter an unterminated string, any further lines you type will appear to be ignored by mysql@-including a line containing QUIT! This can be quite confusing, especially if you don't know that you need to supply the terminating quote before you can cancel the current command.

Creating and Using a Database

Now that you know how to enter commands, it's time to access a database.

Suppose you have several pets in your home (your menagerie) and you'd like to keep track of various types of information about them. You can do so by creating tables to hold your data and loading them with the desired information. Then you can answer different sorts of questions about your animals by retrieving data from the tables. This section shows you how to:

The menagerie database will be simple (deliberately), but it is not difficult to think of real-world situations in which a similar type of database might be used. For example, a database like this could be used by a farmer to keep track of livestock, or by a veterinarian to keep track of patient records. A menagerie distribution containing some of the queries and sample data used in the following sections can be obtained from the MySQL web site. It's available in either compressed tar format (http://www.mysql.com/Downloads/Contrib/Examples/menagerie.tar.gz) or Zip format (http://www.mysql.com/Downloads/Contrib/Examples/menagerie.zip).

Use the SHOW statement to find out what databases currently exist on the server:

mysql> SHOW DATABASES;
+----------+
| Database |
+----------+
| mysql    |
| test     |
| tmp      |
+----------+

The list of databases is probably different on your machine, but the mysql and test databases are likely to be among them. The mysql database is required because it describes user access privileges. The test database is often provided as a workspace for users to try things out.

Note that you may not see all databases if you don't have the SHOW DATABASES privilege. See section GRANTREVOKE 構文.

If the test database exists, try to access it:

mysql> USE test
Database changed

Note that USE, like QUIT, does not require a semicolon. (You can terminate such statements with a semicolon if you like; it does no harm.) The USE statement is special in another way, too: it must be given on a single line.

You can use the test database (if you have access to it) for the examples that follow, but anything you create in that database can be removed by anyone else with access to it. For this reason, you should probably ask your MySQL administrator for permission to use a database of your own. Suppose you want to call yours menagerie. The administrator needs to execute a command like this:

mysql> GRANT ALL ON menagerie.* TO your_mysql_name;

where your_mysql_name is the MySQL user name assigned to you.

Creating and Selecting a Database

If the administrator creates your database for you when setting up your permissions, you can begin using it. Otherwise, you need to create it yourself:

mysql> CREATE DATABASE menagerie;

Under Unix, database names are case-sensitive (unlike SQL keywords), so you must always refer to your database as menagerie, not as Menagerie, MENAGERIE, or some other variant. This is also true for table names. (Under Windows, this restriction does not apply, although you must refer to databases and tables using the same lettercase throughout a given query.)

Creating a database does not select it for use; you must do that explicitly. To make menagerie the current database, use this command:

mysql> USE menagerie
Database changed

Your database needs to be created only once, but you must select it for use each time you begin a mysql session. You can do this by issuing a USE statement as shown above. Alternatively, you can select the database on the command-line when you invoke mysql. Just specify its name after any connection parameters that you might need to provide. For example:

shell> mysql -h host -u user -p menagerie
Enter password: ********

Note that menagerie is not your password on the command just shown. If you want to supply your password on the command-line after the -p option, you must do so with no intervening space (for example, as -pmypassword, not as -p mypassword). However, putting your password on the command-line is not recommended, because doing so exposes it to snooping by other users logged in on your machine.

テーブルの作成

データベースを作成することは容易ですが、作成しただけでは中身はからっぽです。 例えば SHOW TABLES を実行してみると以下のようになるでしょう:

mysql> SHOW TABLES;
Empty set (0.00 sec)

難しいのはデータベースの構造をどうするかを決定することです。 どんなテーブルが必要で、その中にどんな要素を入れるかです。

まずそれぞれのペットに関するレコードを含んだテーブルが必要でしょう。 これは pet テーブルとしましょう。 そしてその中には、最低でもそれぞれの動物の名前は入れる必要があるでしょう。 名前だけではあまり面白くないのでその他の情報も入れることにしましょう。例えば、もし家族の2人以上がペットを買っているならば、飼い主の名前も入れたくなるでしょう。 またその他にもペットの種類や性別など、いくつかの基本的な情報も入れたくなるかもしれません。

年齢はどうでしょうか? 確かにいいかもしれませんが、データベースに蓄積するにはあまり良くないものです。 年齢は時とともに変化します。つまりその都度レコードを更新する必要があるということです。 これに代わるデータとして適切なのは、例えば誕生日です。 そうしておいて年齢が必要なときは今日の日付と誕生日から計算すればよいのです。 MySQL には日付を算術演算する関数がありますので、難しいことはありません。 年齢ではなくて誕生日を記録しておくことには他のメリットもあります。

その他にも pet テーブルに加えるべき有用な情報はいろいろあるでしょう。 しかしとりあえずはこの辺で十分としましょう。名前、飼い主、種類、性別、誕生日、そして死亡日です。

CREATE TABLE 文を使ってテーブルのレイアウトを指定しましょう:

mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
    -> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);

name, owner,そしてspecies フィールドには VARCHAR を用いた方がよいでしょう。なぜならこれらの値の長さは変化するからです。 これらのフィールドの長さは全て同じである必要もなく、20文字である必要もありません。 1から255の間でもっともリーズナブルな値を選べばよいでしょう。 (長さの選択を誤ってあとで文字数が足らなくなったとしても、 MySQLは ALTER TABLE で長さを変えることができます)

動物の性別を表す値にはいくつかのタイプが考えられます。 "m""f" 、あるいは"male""female" なども考えられるでしょう。 ここでは最も簡単に、一文字の "m""f" で表すことにしましょう。

birthdeath のフィールドには、明らかに DATE データ型を用いるべきでしょう。

テーブルを作ってみると、SHOW TABLES で何らかの出力が得られるはずです:

mysql> SHOW TABLES;
+---------------------+
| Tables in menagerie |
+---------------------+
| pet                 |
+---------------------+

テーブルが期待したとおりに作成されたかどうかをチェックするために、 DESCRIBE 文を使います:

mysql> DESCRIBE pet;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

DESCRIBE 文はいつでも、 例えばテーブルの列の名前やそのタイプを忘れてしまったときにも使うことが出来ます。

ファイルからデータをテーブルへ取り込む

テーブルを作ったら、中にデータを入れる必要があります。 このとき LOAD DATA 文とINSERT 文を用いると便利です。

例えばあなたのペットに関する記録が以下のようになっていたとします。 (MySQLにおける日付の表記が 'YYYY-MM-DD' の形式になっていることに注意してください。 あなたが慣れている形式とは異なるかもしれません)

name owner species sex birth death
Fluffy Harold cat f 1993-02-04
Claws Gwen cat m 1994-03-17
Buffy Harold dog f 1989-05-13
Fang Benny dog m 1990-08-27
Bowser Diane dog m 1998-08-31 1995-07-29
Chirpy Gwen bird f 1998-09-11
Whistler Gwen bird 1997-12-09
Slim Benny snake m 1996-04-29

もし空のテーブルから作り始めるのなら、 一行に一つのペットのデータを記述したテキストファイルを作っておいて、 先に挙げた命令で中身を読み込ませると楽です。

そのファイルを `pet.txt' とします。 各レコードを一行ずつ書き、各項目はタブで区切ります。 項目の順番は CREATE TABLE 文で定義したときと同じ順番とします。 項目が空のときは(例えばペットがまだ生きている場合、死亡日欄は空白です) NULL を用いることが出来ます。ファイル中では \N を用います。 例えば鳥の Whistler のレコードは以下のようになります。(項目の間の空白はタブ1個です):

name owner species sex birth death
Whistler Gwen bird \N 1997-12-09 \N

このファイル `pet.txt' をテーブル pet に読み込むには、以下のコマンドを用います:

mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;

もし必要であれば、項目の区切りや行末の符号を LOAD DATA 文で明示的に定めることが出来ます。 デフォルトでは区切りはタブ、行末はラインフィードです。 これにより `pet.txt' を適切に読み込むことが出来ます。

また新しい複数のレコードを1個づつ追加したいときは INSERT が便利です。 それぞれの項を CREATE TABLE で定義したときと同じ順番で入力するだけで追加できます。 例えばDianeが新しくハムスターをもらってきてPuffballと名づけました。 INSERT を用いて以下のようにレコードを追加することが出来ます:

mysql> INSERT INTO pet
    -> VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);

文字列や日付を引用符号で括っていることに注意してください。 また INSERT を用いて空白の項を入力するときには NULL を直接挿入することができます。 LOAD DATA を使っているときとは違って \N は使えません。

この例から、初めにレコードを INSERT 文で入力するのは、 LOAD DATA 文を用いるよりも相当多くのタイピングを要してしまうことがわかると思います。

Retrieving Information from a Table

The SELECT statement is used to pull information from a table. The general form of the statement is:

SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy

what_to_select indicates what you want to see. This can be a list of columns, or * to indicate ``all columns.'' which_table indicates the table from which you want to retrieve data. The WHERE clause is optional. If it's present, conditions_to_satisfy specifies conditions that rows must satisfy to qualify for retrieval.

Selecting All Data

The simplest form of SELECT retrieves everything from a table:

mysql> SELECT * FROM pet;
+----------+--------+---------+------+------------+------------+
| name     | owner  | species | sex  | birth      | death      |
+----------+--------+---------+------+------------+------------+
| Fluffy   | Harold | cat     | f    | 1993-02-04 | NULL       |
| Claws    | Gwen   | cat     | m    | 1994-03-17 | NULL       |
| Buffy    | Harold | dog     | f    | 1989-05-13 | NULL       |
| Fang     | Benny  | dog     | m    | 1990-08-27 | NULL       |
| Bowser   | Diane  | dog     | m    | 1998-08-31 | 1995-07-29 |
| Chirpy   | Gwen   | bird    | f    | 1998-09-11 | NULL       |
| Whistler | Gwen   | bird    | NULL | 1997-12-09 | NULL       |
| Slim     | Benny  | snake   | m    | 1996-04-29 | NULL       |
| Puffball | Diane  | hamster | f    | 1999-03-30 | NULL       |
+----------+--------+---------+------+------------+------------+

This form of SELECT is useful if you want to review your entire table, for instance, after you've just loaded it with your initial dataset. As it happens, the output just shown reveals an error in your datafile: Bowser appears to have been born after he died! Consulting your original pedigree papers, you find that the correct birth year is 1989, not 1998.

There are least a couple of ways to fix this:

As shown above, it is easy to retrieve an entire table. But typically you don't want to do that, particularly when the table becomes large. Instead, you're usually more interested in answering a particular question, in which case you specify some constraints on the information you want. Let's look at some selection queries in terms of questions about your pets that they answer.

Selecting Particular Rows

You can select only particular rows from your table. For example, if you want to verify the change that you made to Bowser's birth date, select Bowser's record like this:

mysql> SELECT * FROM pet WHERE name = "Bowser";
+--------+-------+---------+------+------------+------------+
| name   | owner | species | sex  | birth      | death      |
+--------+-------+---------+------+------------+------------+
| Bowser | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+-------+---------+------+------------+------------+

The output confirms that the year is correctly recorded now as 1989, not 1998.

String comparisons are normally case-insensitive, so you can specify the name as "bowser", "BOWSER", etc. The query result will be the same.

You can specify conditions on any column, not just name. For example, if you want to know which animals were born after 1998, test the birth column:

mysql> SELECT * FROM pet WHERE birth >= "1998-1-1";
+----------+-------+---------+------+------------+-------+
| name     | owner | species | sex  | birth      | death |
+----------+-------+---------+------+------------+-------+
| Chirpy   | Gwen  | bird    | f    | 1998-09-11 | NULL  |
| Puffball | Diane | hamster | f    | 1999-03-30 | NULL  |
+----------+-------+---------+------+------------+-------+

You can combine conditions, for example, to locate female dogs:

mysql> SELECT * FROM pet WHERE species = "dog" AND sex = "f";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

The preceding query uses the AND logical operator. There is also an OR operator:

mysql> SELECT * FROM pet WHERE species = "snake" OR species = "bird";
+----------+-------+---------+------+------------+-------+
| name     | owner | species | sex  | birth      | death |
+----------+-------+---------+------+------------+-------+
| Chirpy   | Gwen  | bird    | f    | 1998-09-11 | NULL  |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL  |
| Slim     | Benny | snake   | m    | 1996-04-29 | NULL  |
+----------+-------+---------+------+------------+-------+

AND and OR may be intermixed. If you do that, it's a good idea to use parentheses to indicate how conditions should be grouped:

mysql> SELECT * FROM pet WHERE (species = "cat" AND sex = "m")
    -> OR (species = "dog" AND sex = "f");
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

Selecting Particular Columns

If you don't want to see entire rows from your table, just name the columns in which you're interested, separated by commas. For example, if you want to know when your animals were born, select the name and birth columns:

mysql> SELECT name, birth FROM pet;
+----------+------------+
| name     | birth      |
+----------+------------+
| Fluffy   | 1993-02-04 |
| Claws    | 1994-03-17 |
| Buffy    | 1989-05-13 |
| Fang     | 1990-08-27 |
| Bowser   | 1989-08-31 |
| Chirpy   | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim     | 1996-04-29 |
| Puffball | 1999-03-30 |
+----------+------------+

To find out who owns pets, use this query:

mysql> SELECT owner FROM pet;
+--------+
| owner  |
+--------+
| Harold |
| Gwen   |
| Harold |
| Benny  |
| Diane  |
| Gwen   |
| Gwen   |
| Benny  |
| Diane  |
+--------+

However, notice that the query simply retrieves the owner field from each record, and some of them appear more than once. To minimise the output, retrieve each unique output record just once by adding the keyword DISTINCT:

mysql> SELECT DISTINCT owner FROM pet;
+--------+
| owner  |
+--------+
| Benny  |
| Diane  |
| Gwen   |
| Harold |
+--------+

You can use a WHERE clause to combine row selection with column selection. For example, to get birth dates for dogs and cats only, use this query:

mysql> SELECT name, species, birth FROM pet
    -> WHERE species = "dog" OR species = "cat";
+--------+---------+------------+
| name   | species | birth      |
+--------+---------+------------+
| Fluffy | cat     | 1993-02-04 |
| Claws  | cat     | 1994-03-17 |
| Buffy  | dog     | 1989-05-13 |
| Fang   | dog     | 1990-08-27 |
| Bowser | dog     | 1989-08-31 |
+--------+---------+------------+

Sorting Rows

You may have noticed in the preceding examples that the result rows are displayed in no particular order. However, it's often easier to examine query output when the rows are sorted in some meaningful way. To sort a result, use an ORDER BY clause.

Here are animal birthdays, sorted by date:

mysql> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name     | birth      |
+----------+------------+
| Buffy    | 1989-05-13 |
| Bowser   | 1989-08-31 |
| Fang     | 1990-08-27 |
| Fluffy   | 1993-02-04 |
| Claws    | 1994-03-17 |
| Slim     | 1996-04-29 |
| Whistler | 1997-12-09 |
| Chirpy   | 1998-09-11 |
| Puffball | 1999-03-30 |
+----------+------------+

On character type columns, sorting@-like all other comparison operations@-is normally performed in a case-insensitive fashion. This means that the order will be undefined for columns that are identical except for their case. You can force a case-sensitive sort by using the BINARY cast: ORDER BY BINARY(field).

To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by:

mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
+----------+------------+
| name     | birth      |
+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy   | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim     | 1996-04-29 |
| Claws    | 1994-03-17 |
| Fluffy   | 1993-02-04 |
| Fang     | 1990-08-27 |
| Bowser   | 1989-08-31 |
| Buffy    | 1989-05-13 |
+----------+------------+

You can sort on multiple columns. For example, to sort by type of animal, then by birth date within animal type with youngest animals first, use the following query:

mysql> SELECT name, species, birth FROM pet ORDER BY species, birth DESC;
+----------+---------+------------+
| name     | species | birth      |
+----------+---------+------------+
| Chirpy   | bird    | 1998-09-11 |
| Whistler | bird    | 1997-12-09 |
| Claws    | cat     | 1994-03-17 |
| Fluffy   | cat     | 1993-02-04 |
| Fang     | dog     | 1990-08-27 |
| Bowser   | dog     | 1989-08-31 |
| Buffy    | dog     | 1989-05-13 |
| Puffball | hamster | 1999-03-30 |
| Slim     | snake   | 1996-04-29 |
+----------+---------+------------+

Note that the DESC keyword applies only to the column name immediately preceding it (birth); species values are still sorted in ascending order.

日付の計算

MySQL はいくつかの日付の計算を行う関数を提供します。 例えば、年の計算や日付の部分を取り出したり。

To determine how many years old each of your pets is, compute the difference in the year part of the current date and the birth date, then subtract one if the current date occurs earlier in the calendar year than the birth date. The following query shows, for each pet, the birth date, the current date, and the age in years.

mysql> SELECT name, birth, CURRENT_DATE,
    -> (YEAR(CURRENT_DATE)-YEAR(birth))
    -> - (RIGHT(CURRENT_DATE,5)<RIGHT(birth,5))
    -> AS age
    -> FROM pet;
+----------+------------+--------------+------+
| name     | birth      | CURRENT_DATE | age  |
+----------+------------+--------------+------+
| Fluffy   | 1993-02-04 | 2001-08-29   |    8 |
| Claws    | 1994-03-17 | 2001-08-29   |    7 |
| Buffy    | 1989-05-13 | 2001-08-29   |   12 |
| Fang     | 1990-08-27 | 2001-08-29   |   11 |
| Bowser   | 1989-08-31 | 2001-08-29   |   11 |
| Chirpy   | 1998-09-11 | 2001-08-29   |    2 |
| Whistler | 1997-12-09 | 2001-08-29   |    3 |
| Slim     | 1996-04-29 | 2001-08-29   |    5 |
| Puffball | 1999-03-30 | 2001-08-29   |    2 |
+----------+------------+--------------+------+

Here, YEAR() pulls out the year part of a date and RIGHT() pulls off the rightmost five characters that represent the MM-DD (calendar year) part of the date. The part of the expression that compares the MM-DD values evaluates to 1 or 0, which adjusts the year difference down a year if CURRENT_DATE occurs earlier in the year than birth. The full expression is somewhat ungainly, so an alias (age) is used to make the output column label more meaningful.

The query works, but the result could be scanned more easily if the rows were presented in some order. This can be done by adding an ORDER BY name clause to sort the output by name:

mysql> SELECT name, birth, CURRENT_DATE,
    -> (YEAR(CURRENT_DATE)-YEAR(birth))
    -> - (RIGHT(CURRENT_DATE,5)<RIGHT(birth,5))
    -> AS age
    -> FROM pet ORDER BY name;
+----------+------------+--------------+------+
| name     | birth      | CURRENT_DATE | age  |
+----------+------------+--------------+------+
| Bowser   | 1989-08-31 | 2001-08-29   |   11 |
| Buffy    | 1989-05-13 | 2001-08-29   |   12 |
| Chirpy   | 1998-09-11 | 2001-08-29   |    2 |
| Claws    | 1994-03-17 | 2001-08-29   |    7 |
| Fang     | 1990-08-27 | 2001-08-29   |   11 |
| Fluffy   | 1993-02-04 | 2001-08-29   |    8 |
| Puffball | 1999-03-30 | 2001-08-29   |    2 |
| Slim     | 1996-04-29 | 2001-08-29   |    5 |
| Whistler | 1997-12-09 | 2001-08-29   |    3 |
+----------+------------+--------------+------+

To sort the output by age rather than name, just use a different ORDER BY clause:

mysql> SELECT name, birth, CURRENT_DATE,
    -> (YEAR(CURRENT_DATE)-YEAR(birth))
    -> - (RIGHT(CURRENT_DATE,5)<RIGHT(birth,5))
    -> AS age
    -> FROM pet ORDER BY age;
+----------+------------+--------------+------+
| name     | birth      | CURRENT_DATE | age  |
+----------+------------+--------------+------+
| Chirpy   | 1998-09-11 | 2001-08-29   |    2 |
| Puffball | 1999-03-30 | 2001-08-29   |    2 |
| Whistler | 1997-12-09 | 2001-08-29   |    3 |
| Slim     | 1996-04-29 | 2001-08-29   |    5 |
| Claws    | 1994-03-17 | 2001-08-29   |    7 |
| Fluffy   | 1993-02-04 | 2001-08-29   |    8 |
| Fang     | 1990-08-27 | 2001-08-29   |   11 |
| Bowser   | 1989-08-31 | 2001-08-29   |   11 |
| Buffy    | 1989-05-13 | 2001-08-29   |   12 |
+----------+------------+--------------+------+

似たクエリが、既に死んでしまった動物の、死んだ時点の年齢を調べるのにも 使用できます。 どの動物が死んでいるかどうかは、death 値が NULL か どうかで判断します。 これらの値が 非NULL ならば、 deathbirth の差の計算を行います:

mysql> SELECT name, birth, death,
    -> (YEAR(death)-YEAR(birth)) - (RIGHT(death,5)<RIGHT(birth,5))
    -> AS age
    -> FROM pet WHERE death IS NOT NULL ORDER BY age;
+--------+------------+------------+------+
| name   | birth      | death      | age  |
+--------+------------+------------+------+
| Bowser | 1989-08-31 | 1995-07-29 |    5 |
+--------+------------+------------+------+

このクエリでは、 death <> NULL ではなく death IS NOT NULL を 使用します。 なぜなら、 NULL は特別な値だからです。 これは後で解説します。 See section NULL 値の振る舞い.

もしあなたが翌月誕生日の動物を知りたいとします。 この種の計算では、 年と日が関係ありません。 birth フィールドの月だけを単に 取り出したくなるでしょう。 MySQL は日付の部分を取り出すいくつかの関数を 提供します。 YEAR(), MONTH(), DAYOFMONTH() など。 ここでは MONTH() がいいでしょう。 これがどのように動くか確かめるには、 birthMONTH(birth) の両方を表示させるクエリを実行してみます:

mysql> SELECT name, birth, MONTH(birth) FROM pet;
+----------+------------+--------------+
| name     | birth      | MONTH(birth) |
+----------+------------+--------------+
| Fluffy   | 1993-02-04 |            2 |
| Claws    | 1994-03-17 |            3 |
| Buffy    | 1989-05-13 |            5 |
| Fang     | 1990-08-27 |            8 |
| Bowser   | 1989-08-31 |            8 |
| Chirpy   | 1998-09-11 |            9 |
| Whistler | 1997-12-09 |           12 |
| Slim     | 1996-04-29 |            4 |
| Puffball | 1999-03-30 |            3 |
+----------+------------+--------------+

来月誕生日を迎える動物を見つけるのは簡単です。 現在4月だとします。 すると、5月生まれの動物を探します:

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = 5;
+-------+------------+
| name  | birth      |
+-------+------------+
| Buffy | 1989-05-13 |
+-------+------------+

もし現在が12月なら、ちょっと困るかもしれません。 月の数字 (12) に 1 を足して 13 月生まれの動物を探すわけにはいきません。 かわりに1月生まれの 動物を探します。

現在が何月なのかを気にすることなく、動作するクエリを書くことが可能です。 この方法では、あなたは月の数字をクエリに使用することがありません。 DATE_ADD() 関数は与えた日付からある時間を足すことが可能です。 もし現時点 NOW() の値に 1ヶ月 足し、 MONTH() で月の 部分を取り出し、その結果を、誕生月を調べるために使用します:

mysql> SELECT name, birth FROM pet
    -> WHERE MONTH(birth) = MONTH(DATE_ADD(NOW(), INTERVAL 1 MONTH));

同じことができる別の方法として、剰余関数 を使用した結果に 1 を足す方法があります。 (もし今月が12月なら、剰余関数 (MOD) を使用した結果は 0 になります):

mysql> SELECT name, birth FROM pet
    -> WHERE MONTH(birth) = MOD(MONTH(NOW()), 12) + 1;

Note that MONTH returns a number between 1 and 12. And MOD(something,12) returns a number between 0 and 11. So the addition has to be after the MOD(), otherwise we would go from November (11) to January (1).

NULL 値の振る舞い

あなたがそれに慣れるまでは、NULL 値には驚くかもしれません。 概念的に、NULL 値は ``値無し'' か ``未知な値'' を意味し、 他の値よりもいくぶん異なって扱われます。 NULL の評価の際には、数値の比較演算子 =, <, <> を 使用することは出来ません。 あなた自身これをデモするために、以下のようにしてみてください:

mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
+----------+-----------+----------+----------+
| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |
+----------+-----------+----------+----------+
|     NULL |      NULL |     NULL |     NULL |
+----------+-----------+----------+----------+

確実にこれらの比較からいかなる意味がある結果も受け取りません。 この代わりに、 IS NULL , IS NOT NULL 演算子を使用します:

mysql> SELECT 1 IS NULL, 1 IS NOT NULL;
+-----------+---------------+
| 1 IS NULL | 1 IS NOT NULL |
+-----------+---------------+
|         0 |             1 |
+-----------+---------------+

MySQL では, 0 や NULL は false(偽) で、それ以外全てが true(真)です。 The default truth value from a boolean operation is 1.

この NULL の特別な扱いはなぜなのか。 前のセクションを見てください。 どの動物がもはや生きていないことを決定づけるためには、 death <> NULL ではなく death IS NOT NULL の使用が 必要とされるのです。

Two NULL values are regarded as equal in a GROUP BY.

When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC.

Note that between MySQL 4.0.2 - 4.0.10, NULL values incorrectly were always sorted first regardless of the sort direction.

パターン・マッチ

MySQL は標準SQLのパターン・マッチを提供します。 また、拡張された正規表現を基にした形式のパターン・マッチ、 これは vi, grep , sed など UNIX のユーティリティに 使用されている物と似ていますが、これも提供します。

SQL パターン・マッチは、 `_' でいかなる1文字とも一致し、 `%' であらゆる0こ以上の文字列に一致します。 MySQL では、デフォルトで SQL パターンはケース非依存です。 いくつか例を以下に示します。 SQLパターンを使用する場合、 =!= を使用しないように注意してください。 LIKENOT LIKE を代わりに使用します。

`b' から始まる名前を見つけるには:

mysql> SELECT * FROM pet WHERE name LIKE "b%";
+--------+--------+---------+------+------------+------------+
| name   | owner  | species | sex  | birth      | death      |
+--------+--------+---------+------+------------+------------+
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       |
| Bowser | Diane  | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+

`fy' で終わる名前を見つけるには:

mysql> SELECT * FROM pet WHERE name LIKE "%fy";
+--------+--------+---------+------+------------+-------+
| name   | owner  | species | sex  | birth      | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL  |
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL  |
+--------+--------+---------+------+------------+-------+

`w' を含む名前を見つけるには:

mysql> SELECT * FROM pet WHERE name LIKE "%w%";
+----------+-------+---------+------+------------+------------+
| name     | owner | species | sex  | birth      | death      |
+----------+-------+---------+------+------------+------------+
| Claws    | Gwen  | cat     | m    | 1994-03-17 | NULL       |
| Bowser   | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL       |
+----------+-------+---------+------+------------+------------+

5文字の名前を見つけるには, `_' パターン文字を使用して:

mysql> SELECT * FROM pet WHERE name LIKE "_____";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

MySQL では他のパターン・マッチの形も提供されます。正規表現の拡張を使用して。 これらのパターン・マッチをテストする際には、REGEXPNOT REGEXP 演算子(あるいはRLIKE, NOT RLIKE 演算子。これらは同義です) を使用します。

拡張正規表現のいくつかの特徴:

以下は拡張された正規表現がどう動くかの例です。 上に示した LIKE のクエリは REGEXP で以下のように書き換えれます:

`b' で始まる名前をみつけるには、`^' で名前の頭にマッチさせ、 かつ `[bB]' として、大文字小文字にもマッチさせます:

mysql> SELECT * FROM pet WHERE name REGEXP "^b";
+--------+--------+---------+------+------------+------------+
| name   | owner  | species | sex  | birth      | death      |
+--------+--------+---------+------+------------+------------+
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       |
| Bowser | Diane  | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+

Prior to MySQL Version 3.23.4, REGEXP is case-sensitive, and the previous query will return no rows. To match either lowercase or uppercase `b', use this query instead:

mysql> SELECT * FROM pet WHERE name REGEXP "^[bB]";

From MySQL 3.23.4 on, to force a REGEXP comparison to be case-sensitive, use the BINARY keyword to make one of the strings a binary string. This query will match only lowercase `b' at the beginning of a name:

mysql> SELECT * FROM pet WHERE name REGEXP BINARY "^b";

To find names ending with `fy', use `$' to match the end of the name:

mysql> SELECT * FROM pet WHERE name REGEXP "fy$";
+--------+--------+---------+------+------------+-------+
| name   | owner  | species | sex  | birth      | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL  |
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL  |
+--------+--------+---------+------+------------+-------+

To find names containing a lowercase or uppercase `w', use this query:

mysql> SELECT * FROM pet WHERE name REGEXP "w";
+----------+-------+---------+------+------------+------------+
| name     | owner | species | sex  | birth      | death      |
+----------+-------+---------+------+------------+------------+
| Claws    | Gwen  | cat     | m    | 1994-03-17 | NULL       |
| Bowser   | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL       |
+----------+-------+---------+------+------------+------------+

正規表現はもし値中のどこかにでもあればマッチするため、 SQL パターンのように、パターンの前後にワイルドカードを書く必要はありません。

5文字の名前を見つけるには、`^'`$' を使用して名前の初めと終わりに マッチさせ、その間に `.' を5個入れます:

mysql> SELECT * FROM pet WHERE name REGEXP "^.....$";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

前のクエリは `{n}' ``n回繰り返し'' オペレーターで 書換え可能です。

mysql> SELECT * FROM pet WHERE name REGEXP "^.{5}$";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

Counting Rows

Databases are often used to answer the question, ``How often does a certain type of data occur in a table?'' For example, you might want to know how many pets you have, or how many pets each owner has, or you might want to perform various kinds of censuses on your animals.

Counting the total number of animals you have is the same question as ``How many rows are in the pet table?'' because there is one record per pet. The COUNT() function counts the number of non-NULL results, so the query to count your animals looks like this:

mysql> SELECT COUNT(*) FROM pet;
+----------+
| COUNT(*) |
+----------+
|        9 |
+----------+

Earlier, you retrieved the names of the people who owned pets. You can use COUNT() if you want to find out how many pets each owner has:

mysql> SELECT owner, COUNT(*) FROM pet GROUP BY owner;
+--------+----------+
| owner  | COUNT(*) |
+--------+----------+
| Benny  |        2 |
| Diane  |        2 |
| Gwen   |        3 |
| Harold |        2 |
+--------+----------+

Note the use of GROUP BY to group together all records for each owner. Without it, all you get is an error message:

mysql> SELECT owner, COUNT(owner) FROM pet;
ERROR 1140 at line 1: Mixing of GROUP columns (MIN(),MAX(),COUNT()...)
with no GROUP columns is illegal if there is no GROUP BY clause

COUNT() and GROUP BY are useful for characterising your data in various ways. The following examples show different ways to perform animal census operations.

Number of animals per species:

mysql> SELECT species, COUNT(*) FROM pet GROUP BY species;
+---------+----------+
| species | COUNT(*) |
+---------+----------+
| bird    |        2 |
| cat     |        2 |
| dog     |        3 |
| hamster |        1 |
| snake   |        1 |
+---------+----------+

Number of animals per sex:

mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex;
+------+----------+
| sex  | COUNT(*) |
+------+----------+
| NULL |        1 |
| f    |        4 |
| m    |        4 |
+------+----------+

(In this output, NULL indicates sex unknown.)

Number of animals per combination of species and sex:

mysql> SELECT species, sex, COUNT(*) FROM pet GROUP BY species, sex;
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| bird    | NULL |        1 |
| bird    | f    |        1 |
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
| hamster | f    |        1 |
| snake   | m    |        1 |
+---------+------+----------+

You need not retrieve an entire table when you use COUNT(). For example, the previous query, when performed just on dogs and cats, looks like this:

mysql> SELECT species, sex, COUNT(*) FROM pet
    -> WHERE species = "dog" OR species = "cat"
    -> GROUP BY species, sex;
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
+---------+------+----------+

Or, if you wanted the number of animals per sex only for known-sex animals:

mysql> SELECT species, sex, COUNT(*) FROM pet
    -> WHERE sex IS NOT NULL
    -> GROUP BY species, sex;
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| bird    | f    |        1 |
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
| hamster | f    |        1 |
| snake   | m    |        1 |
+---------+------+----------+

Using More Than one Table

The pet table keeps track of which pets you have. If you want to record other information about them, such as events in their lives like visits to the vet or when litters are born, you need another table. What should this table look like? It needs:

Given these considerations, the CREATE TABLE statement for the event table might look like this:

mysql> CREATE TABLE event (name VARCHAR(20), date DATE,
    -> type VARCHAR(15), remark VARCHAR(255));

As with the pet table, it's easiest to load the initial records by creating a tab-delimited text file containing the information:

name date type remark
Fluffy 1995-05-15 litter 4 kittens, 3 female, 1 male
Buffy 1993-06-23 litter 5 puppies, 2 female, 3 male
Buffy 1994-06-19 litter 3 puppies, 3 female
Chirpy 1999-03-21 vet needed beak straightened
Slim 1997-08-03 vet broken rib
Bowser 1991-10-12 kennel
Fang 1991-10-12 kennel
Fang 1998-08-28 birthday Gave him a new chew toy
Claws 1998-03-17 birthday Gave him a new flea collar
Whistler 1998-12-09 birthday First birthday

Load the records like this:

mysql> LOAD DATA LOCAL INFILE "event.txt" INTO TABLE event;

Based on what you've learned from the queries you've run on the pet table, you should be able to perform retrievals on the records in the event table; the principles are the same. But when is the event table by itself insufficient to answer questions you might ask?

Suppose you want to find out the ages of each pet when they had their litters. The event table indicates when this occurred, but to calculate the age of the mother, you need her birth date. Because that is stored in the pet table, you need both tables for the query:

mysql> SELECT pet.name,
    -> (TO_DAYS(date) - TO_DAYS(birth))/365 AS age,
    -> remark
    -> FROM pet, event
    -> WHERE pet.name = event.name AND type = "litter";
+--------+------+-----------------------------+
| name   | age  | remark                      |
+--------+------+-----------------------------+
| Fluffy | 2.27 | 4 kittens, 3 female, 1 male |
| Buffy  | 4.12 | 5 puppies, 2 female, 3 male |
| Buffy  | 5.10 | 3 puppies, 3 female         |
+--------+------+-----------------------------+

There are several things to note about this query:

You need not have two different tables to perform a join. Sometimes it is useful to join a table to itself, if you want to compare records in a table to other records in that same table. For example, to find breeding pairs among your pets, you can join the pet table with itself to pair up males and females of like species:

mysql> SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species
    -> FROM pet AS p1, pet AS p2
    -> WHERE p1.species = p2.species AND p1.sex = "f" AND p2.sex = "m";
+--------+------+--------+------+---------+
| name   | sex  | name   | sex  | species |
+--------+------+--------+------+---------+
| Fluffy | f    | Claws  | m    | cat     |
| Buffy  | f    | Fang   | m    | dog     |
| Buffy  | f    | Bowser | m    | dog     |
+--------+------+--------+------+---------+

In this query, we specify aliases for the table name in order to refer to the columns and keep straight which instance of the table each column reference is associated with.

データベースとテーブルの情報を得る

データベースやテーブルの名前が何であったか、あるいはテーブルの構造はどうであったか、 (なんというフィールドがあったのか)忘れてしまった場合。 MySQL ではいくつかのデータベースとテーブルの情報を提供する文を通じて この問題を処理します。

あなたは既に SHOW DATABASES を知っているはずで, これはサーバーが 管理するデーターベースの一覧を表示します。 現在選択しているデータベースが 何であるかを知るには、DATABASE() 関数を使用します:

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| menagerie  |
+------------+

もしデータベースをまだ何も選択していなければ、結果はブランクです。

データベースに含まれるテーブルを見つけるには(たとえば、あなたがテーブル名を 知らない場合)、このコマンドを使用します:

mysql> SHOW TABLES;
+---------------------+
| Tables in menagerie |
+---------------------+
| event               |
| pet                 |
+---------------------+

もしテーブルの構造を知りたいなら、DESCRIBE コマンドが便利です; これはテーブルのそれぞれのフィールドについての情報を表示します。

mysql> DESCRIBE pet;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

Field はフィールド名を示し、Type はフィールドのデータ型、 Null はこのフィールドが Null 値を含むかを示し、 Key はこのフィールドがインデックス化されているかを示し、 Default はフィールドのデフォルトの値を示します。

もしテーブルにインデックスを持っているなら、 SHOW INDEX FROM tbl_name がそれらの情報を示します。

Examples of Common Queries

Here are examples of how to solve some common problems with MySQL.

Some of the examples use the table shop to hold the price of each article (item number) for certain traders (dealers). Supposing that each trader has a single fixed price per article, then (article, dealer) is a primary key for the records.

Start the command-line tool mysql and select a database:

mysql your-database-name

(In most MySQL installations, you can use the database-name 'test').

You can create the example table as:

CREATE TABLE shop (
 article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
 dealer  CHAR(20)                 DEFAULT ''     NOT NULL,
 price   DOUBLE(16,2)             DEFAULT '0.00' NOT NULL,
 PRIMARY KEY(article, dealer));

INSERT INTO shop VALUES
(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),(3,'C',1.69),
(3,'D',1.25),(4,'D',19.95);

Okay, so the example data is:

mysql> SELECT * FROM shop;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0001 | A      |  3.45 |
|    0001 | B      |  3.99 |
|    0002 | A      | 10.99 |
|    0003 | B      |  1.45 |
|    0003 | C      |  1.69 |
|    0003 | D      |  1.25 |
|    0004 | D      | 19.95 |
+---------+--------+-------+

The Maximum Value for a Column

``What's the highest item number?''

SELECT MAX(article) AS article FROM shop

+---------+
| article |
+---------+
|       4 |
+---------+

The Row Holding the Maximum of a Certain Column

``Find number, dealer, and price of the most expensive article.''

In ANSI SQL (and MySQL Version 4.1) this is easily done with a subquery:

SELECT article, dealer, price
FROM   shop
WHERE  price=(SELECT MAX(price) FROM shop)

In MySQL versions prior to 4.1, just do it in two steps:

  1. Get the maximum price value from the table with a SELECT statement.
  2. Using this value compile the actual query:
    SELECT article, dealer, price
    FROM   shop
    WHERE  price=19.95
    

Another solution is to sort all rows descending by price and only get the first row using the MySQL-specific LIMIT clause:

SELECT article, dealer, price
FROM   shop
ORDER BY price DESC
LIMIT 1

NOTE: If there are several most expensive articles (for example, each 19.95) the LIMIT solution shows only one of them!

Maximum of Column per Group

``What's the highest price per article?''

SELECT article, MAX(price) AS price
FROM   shop
GROUP BY article

+---------+-------+
| article | price |
+---------+-------+
|    0001 |  3.99 |
|    0002 | 10.99 |
|    0003 |  1.69 |
|    0004 | 19.95 |
+---------+-------+

The Rows Holding the Group-wise Maximum of a Certain Field

``For each article, find the dealer(s) with the most expensive price.''

In ANSI SQL (and MySQL Version 4.1 or greater), I'd do it with a subquery like this:

SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article);

In MySQL versions prior to 4.1 it's best do it in several steps:

  1. Get the list of (article,maxprice).
  2. For each article get the corresponding rows that have the stored maximum price.

This can easily be done with a temporary table:

CREATE TEMPORARY TABLE tmp (
        article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
        price   DOUBLE(16,2)             DEFAULT '0.00' NOT NULL);

LOCK TABLES shop read;

INSERT INTO tmp SELECT article, MAX(price) FROM shop GROUP BY article;

SELECT shop.article, dealer, shop.price FROM shop, tmp
WHERE shop.article=tmp.article AND shop.price=tmp.price;

UNLOCK TABLES;

DROP TABLE tmp;

If you don't use a TEMPORARY table, you must also lock the 'tmp' table.

``Can it be done with a single query?''

Yes, but only by using a quite inefficient trick that I call the ``MAX-CONCAT trick'':

SELECT article,
       SUBSTRING( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 7) AS dealer,
  0.00+LEFT(      MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 6) AS price
FROM   shop
GROUP BY article;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0001 | B      |  3.99 |
|    0002 | A      | 10.99 |
|    0003 | C      |  1.69 |
|    0004 | D      | 19.95 |
+---------+--------+-------+

The last example can, of course, be made a bit more efficient by doing the splitting of the concatenated column in the client.

Using user variables

You can use MySQL user variables to remember results without having to store them in temporary variables in the client. See section ユーザー変数.

For example, to find the articles with the highest and lowest price you can do:

mysql> SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;
mysql> SELECT * FROM shop WHERE price=@min_price OR price=@max_price;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0003 | D      |  1.25 |
|    0004 | D      | 19.95 |
+---------+--------+-------+

Using Foreign Keys

In MySQL 3.23.44 and up, InnoDB tables supports checking of foreign key constraints. See section InnoDB テーブル (3.23.6以上). See also section 外部キー.

You don't actually need foreign keys to join 2 tables. The only thing MySQL currently doesn't do (in table types other than InnoDB), is CHECK to make sure that the keys you use really exist in the table(s) you're referencing and it doesn't automatically delete rows from a table with a foreign key definition. If you use your keys like normal, it'll work just fine:

CREATE TABLE person (
    id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name CHAR(60) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE shirt (
    id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
    color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
    owner SMALLINT UNSIGNED NOT NULL REFERENCES person(id),
    PRIMARY KEY (id)
);

INSERT INTO person VALUES (NULL, 'Antonio Paz');

INSERT INTO shirt VALUES
(NULL, 'polo', 'blue', LAST_INSERT_ID()),
(NULL, 'dress', 'white', LAST_INSERT_ID()),
(NULL, 't-shirt', 'blue', LAST_INSERT_ID());

INSERT INTO person VALUES (NULL, 'Lilliana Angelovska');

INSERT INTO shirt VALUES
(NULL, 'dress', 'orange', LAST_INSERT_ID()),
(NULL, 'polo', 'red', LAST_INSERT_ID()),
(NULL, 'dress', 'blue', LAST_INSERT_ID()),
(NULL, 't-shirt', 'white', LAST_INSERT_ID());

SELECT * FROM person;
+----+---------------------+
| id | name                |
+----+---------------------+
|  1 | Antonio Paz         |
|  2 | Lilliana Angelovska |
+----+---------------------+

SELECT * FROM shirt;
+----+---------+--------+-------+
| id | style   | color  | owner |
+----+---------+--------+-------+
|  1 | polo    | blue   |     1 |
|  2 | dress   | white  |     1 |
|  3 | t-shirt | blue   |     1 |
|  4 | dress   | orange |     2 |
|  5 | polo    | red    |     2 |
|  6 | dress   | blue   |     2 |
|  7 | t-shirt | white  |     2 |
+----+---------+--------+-------+

SELECT s.* FROM person p, shirt s
 WHERE p.name LIKE 'Lilliana%'
   AND s.owner = p.id
   AND s.color <> 'white';

+----+-------+--------+-------+
| id | style | color  | owner |
+----+-------+--------+-------+
|  4 | dress | orange |     2 |
|  5 | polo  | red    |     2 |
|  6 | dress | blue   |     2 |
+----+-------+--------+-------+

Searching on Two Keys

MySQL doesn't yet optimize when you search on two different keys combined with OR (searching on one key with different OR parts is optimized quite well):

SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1'
OR  field2_index = '1'

The reason is that we haven't yet had time to come up with an efficient way to handle this in the general case. (The AND handling is, in comparison, now completely general and works very well.)

For the moment you can solve this very efficiently by using a TEMPORARY table. This type of optimization is also very good if you are using very complicated queries where the SQL server does the optimizations in the wrong order.

CREATE TEMPORARY TABLE tmp
SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1';
INSERT INTO tmp
SELECT field1_index, field2_index FROM test_table WHERE field2_index = '1';
SELECT * from tmp;
DROP TABLE tmp;

The above way to solve this query is in effect a UNION of two queries. See section UNION Syntax.

Calculating Visits Per Day

The following shows an idea of how you can use the bit group functions to calculate the number of days per month a user has visited a web page.

CREATE TABLE t1 (year YEAR(4), month INT(2) UNSIGNED ZEROFILL,
             day INT(2) UNSIGNED ZEROFILL);
INSERT INTO t1 VALUES(2000,1,1),(2000,1,20),(2000,1,30),(2000,2,2),
            (2000,2,23),(2000,2,23);
SELECT year,month,BIT_COUNT(BIT_OR(1<<day)) AS days FROM t1
       GROUP BY year,month;

Which returns:

+------+-------+------+
| year | month | days |
+------+-------+------+
| 2000 |    01 |    3 |
| 2000 |    02 |    2 |
+------+-------+------+

The above calculates how many different days was used for a given year/month combination, with automatic removal of duplicate entries.

Using AUTO_INCREMENT

The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:

CREATE TABLE animals (
             id MEDIUMINT NOT NULL AUTO_INCREMENT,
             name CHAR(30) NOT NULL,
             PRIMARY KEY (id)
             );
INSERT INTO animals (name) VALUES ("dog"),("cat"),("penguin"),
                                  ("lax"),("whale");
SELECT * FROM animals;

Which returns:

+----+---------+
| id | name    |
+----+---------+
|  1 | dog     |
|  2 | cat     |
|  3 | penguin |
|  4 | lax     |
|  5 | whale   |
+----+---------+

You can retrieve the used AUTO_INCREMENT key with the LAST_INSERT_ID() SQL function or the mysql_insert_id() API function. Note: for a multi-row insert, LAST_INSERT_ID()/mysql_insert_id() will actually return the AUTO_INCREMENT key from the first inserted row. This allows multi-row inserts to be reproduced on other servers.

For MyISAM and BDB tables you can specify AUTO_INCREMENT on secondary column in a multi-column key. In this case the generated value for the autoincrement column is calculated as MAX(auto_increment_column)+1) WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups.

CREATE TABLE animals (
             grp ENUM('fish','mammal','bird') NOT NULL,
             id MEDIUMINT NOT NULL AUTO_INCREMENT,
             name CHAR(30) NOT NULL,
             PRIMARY KEY (grp,id)
             );
INSERT INTO animals (grp,name) VALUES("mammal","dog"),("mammal","cat"),
                  ("bird","penguin"),("fish","lax"),("mammal","whale");
SELECT * FROM animals ORDER BY grp,id;

Which returns:

+--------+----+---------+
| grp    | id | name    |
+--------+----+---------+
| fish   |  1 | lax     |
| mammal |  1 | dog     |
| mammal |  2 | cat     |
| mammal |  3 | whale   |
| bird   |  1 | penguin |
+--------+----+---------+

Note that in this case, the AUTO_INCREMENT value will be reused if you delete the row with the biggest AUTO_INCREMENT value in any group.

mysql のバッチモードでの使用

前のセクションでは、mysql を対話モードで使用し、クエリの入力と 結果を表示しました。 mysql はバッチモードでも実行可能です。 これを行うには、あなたが実行したいコマンドをファイルに書いておき、 そのファイルから入力を読み込むようにして mysql を実行します:

shell> mysql < batch-file

If you are running mysql under windows and have some special characters in the file that causes problems, you can do:

dos> mysql -e "source batch-file"

もし接続パラメターを指定する必要がある場合は、以下のようになるでしょう:

shell> mysql -h host -u user -p < batch-file
Enter password: ********

この方法で mysql を使用するとき、あなたはスクリプトファイルを 作成し、それを実行することになるでしょう。

If you want the script to continue even if you have errors, you should use the --force command-line option.

なぜスクリプトを使用するのか? それには以下の理由があります:

mysql をバッチモードで使用するか、対話モードで使用するかで、 デフォルトの出力形式が変わります。 例えば、 SELECT DISTINCT species FROM pet の 出力は対話モードでは次のようになります:

+---------+
| species |
+---------+
| bird    |
| cat     |
| dog     |
| hamster |
| snake   |
+---------+

しかし、バッチモードでは:

species
bird
cat
dog
hamster
snake

もしバッチモードでも対話モードのような出力を得たい場合には、mysql -t とします。 出力中に、実行したコマンドを表示させるならば、mysql -vvv とします。

You can also use scripts in the mysql command-line prompt by using the source command:

mysql> source filename;

Queries from Twin Project

At Analytikerna and Lentus, we have been doing the systems and field work for a big research project. This project is a collaboration between the Institute of Environmental Medicine at Karolinska Institutet Stockholm and the Section on Clinical Research in Aging and Psychology at the University of Southern California.

The project involves a screening part where all twins in Sweden older than 65 years are interviewed by telephone. Twins who meet certain criteria are passed on to the next stage. In this latter stage, twins who want to participate are visited by a doctor/nurse team. Some of the examinations include physical and neuropsychological examination, laboratory testing, neuroimaging, psychological status assessment, and family history collection. In addition, data are collected on medical and environmental risk factors.

More information about Twin studies can be found at: http://www.imm.ki.se/TWIN/TWINUKW.HTM

The latter part of the project is administered with a web interface written using Perl and MySQL.

Each night all data from the interviews are moved into a MySQL database.

Find all Non-distributed Twins

The following query is used to determine who goes into the second part of the project:

SELECT
        CONCAT(p1.id, p1.tvab) + 0 AS tvid,
        CONCAT(p1.christian_name, " ", p1.surname) AS Name,
        p1.postal_code AS Code,
        p1.city AS City,
        pg.abrev AS Area,
        IF(td.participation = "Aborted", "A", " ") AS A,
        p1.dead AS dead1,
        l.event AS event1,
        td.suspect AS tsuspect1,
        id.suspect AS isuspect1,
        td.severe AS tsevere1,
        id.severe AS isevere1,
        p2.dead AS dead2,
        l2.event AS event2,
        h2.nurse AS nurse2,
        h2.doctor AS doctor2,
        td2.suspect AS tsuspect2,
        id2.suspect AS isuspect2,
        td2.severe AS tsevere2,
        id2.severe AS isevere2,
        l.finish_date
FROM
        twin_project AS tp
        /* For Twin 1 */
        LEFT JOIN twin_data AS td ON tp.id = td.id
                  AND tp.tvab = td.tvab
        LEFT JOIN informant_data AS id ON tp.id = id.id
                  AND tp.tvab = id.tvab
        LEFT JOIN harmony AS h ON tp.id = h.id
                  AND tp.tvab = h.tvab
        LEFT JOIN lentus AS l ON tp.id = l.id
                  AND tp.tvab = l.tvab
        /* For Twin 2 */
        LEFT JOIN twin_data AS td2 ON p2.id = td2.id
                  AND p2.tvab = td2.tvab
        LEFT JOIN informant_data AS id2 ON p2.id = id2.id
                  AND p2.tvab = id2.tvab
        LEFT JOIN harmony AS h2 ON p2.id = h2.id
                  AND p2.tvab = h2.tvab
        LEFT JOIN lentus AS l2 ON p2.id = l2.id
                  AND p2.tvab = l2.tvab,
        person_data AS p1,
        person_data AS p2,
        postal_groups AS pg
WHERE
        /* p1 gets main twin and p2 gets his/her twin. */
        /* ptvab is a field inverted from tvab */
        p1.id = tp.id AND p1.tvab = tp.tvab AND
        p2.id = p1.id AND p2.ptvab = p1.tvab AND
        /* Just the sceening survey */
        tp.survey_no = 5 AND
        /* Skip if partner died before 65 but allow emigration (dead=9) */
        (p2.dead = 0 OR p2.dead = 9 OR
         (p2.dead = 1 AND
          (p2.death_date = 0 OR
           (((TO_DAYS(p2.death_date) - TO_DAYS(p2.birthday)) / 365)
            >= 65))))
        AND
        (
        /* Twin is suspect */
        (td.future_contact = 'Yes' AND td.suspect = 2) OR
        /* Twin is suspect - Informant is Blessed */
        (td.future_contact = 'Yes' AND td.suspect = 1
                                   AND id.suspect = 1) OR
        /* No twin - Informant is Blessed */
        (ISNULL(td.suspect) AND id.suspect = 1
                            AND id.future_contact = 'Yes') OR
        /* Twin broken off - Informant is Blessed */
        (td.participation = 'Aborted'
         AND id.suspect = 1 AND id.future_contact = 'Yes') OR
        /* Twin broken off - No inform - Have partner */
        (td.participation = 'Aborted' AND ISNULL(id.suspect)
                                      AND p2.dead = 0))
        AND
        l.event = 'Finished'
        /* Get at area code */
        AND SUBSTRING(p1.postal_code, 1, 2) = pg.code
        /* Not already distributed */
        AND (h.nurse IS NULL OR h.nurse=00 OR h.doctor=00)
        /* Has not refused or been aborted */
        AND NOT (h.status = 'Refused' OR h.status = 'Aborted'
        OR h.status = 'Died' OR h.status = 'Other')
ORDER BY
        tvid;

Some explanations:

CONCAT(p1.id, p1.tvab) + 0 AS tvid
We want to sort on the concatenated id and tvab in numerical order. Adding 0 to the result causes MySQL to treat the result as a number.
column id
This identifies a pair of twins. It is a key in all tables.
column tvab
This identifies a twin in a pair. It has a value of 1 or 2.
column ptvab
This is an inverse of tvab. When tvab is 1 this is 2, and vice versa. It exists to save typing and to make it easier for MySQL to optimize the query.

This query demonstrates, among other things, how to do lookups on a table from the same table with a join (p1 and p2). In the example, this is used to check whether a twin's partner died before the age of 65. If so, the row is not returned.

All of the above exist in all tables with twin-related information. We have a key on both id,tvab (all tables), and id,ptvab (person_data) to make queries faster.

On our production machine (A 200MHz UltraSPARC), this query returns about 150-200 rows and takes less than one second.

The current number of records in the tables used above:
Table Rows
person_data 71074
lentus 5291
twin_project 5286
twin_data 2012
informant_data 663
harmony 381
postal_groups 100

Show a Table on Twin Pair Status

Each interview ends with a status code called event. The query shown here is used to display a table over all twin pairs combined by event. This indicates in how many pairs both twins are finished, in how many pairs one twin is finished and the other refused, and so on.

SELECT
        t1.event,
        t2.event,
        COUNT(*)
FROM
        lentus AS t1,
        lentus AS t2,
        twin_project AS tp
WHERE
        /* We are looking at one pair at a time */
        t1.id = tp.id
        AND t1.tvab=tp.tvab
        AND t1.id = t2.id
        /* Just the sceening survey */
        AND tp.survey_no = 5
        /* This makes each pair only appear once */
        AND t1.tvab='1' AND t2.tvab='2'
GROUP BY
        t1.event, t2.event;

Using MySQL with Apache

There are programs that let you authenticate your users from a MySQL database and also let you log your log files into a MySQL table.

You can change the Apache logging format to be easily readable by MySQL by putting the following into the Apache configuration file:

LogFormat \
        "\"%h\",%{%Y%m%d%H%M%S}t,%>s,\"%b\",\"%{Content-Type}o\",  \
        \"%U\",\"%{Referer}i\",\"%{User-Agent}i\""

In MySQL you can do something like this:

LOAD DATA INFILE '/local/access_log' INTO TABLE table_name
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\'

データベース管理

Configuring MySQL

mysqld コマンド行オプション

多くの場合、オプションファイルを通じて mysqld オプションを管理すべきです。 See section `my.cnf' オプションファイル.

mysqldmysqld.servermysqldserver グループからオプションを読み込みます。mysqld_safemysqld, server, mysqld_safe, safe_mysqld グ ループからオプションを読み込みます。組み込み MySQL サーバは通常 server, embedded, xxxxx_SERVER からオプションを読み 込みます。xxxxx はアプリケーション名です。

mysqld は次のコマンド行オプションを受け付けます。 完全なリストについては mysqld --help を実行してください。

--ansi
MySQL 構文の代わりに ANSI SQL 構文を使用します。 See section Running MySQL in ANSI Mode.
-b, --basedir=path
インストール先ディレクトリのパス。すべてのパスは通常ここからの相対パスで決 定されます。
--big-tables
ファイルにすべての一時セットを保存することにより、大きな結果セットを許しま す。これは、多くの 'table full' エラーを解決します。しかし、メモリ内テーブ ルでも十分なクエリは遅くなります。バージョン 3.23.2 からは、 MySQL は自動的にメモリを使用し、必要なときにディスクテーブルにス イッチすることによって、これを解決します。
--bind-address=IP
bind する IP アドレス。
--console
--log-error が指定されていても、エラーログメッセージを stderr/stdout に書き出します。Windows mysqld はこのオプションが使用され た場合はコンソールスクリーンをクローズしません。
--character-sets-dir=path
キャラクタ・セット ディレクトリ。 See section データとソートに使用されるキャラクター・セット.
--chroot=path
起動時に mysqld デーモンを chroot 下に置きます。 MySQL 4.0 からの推奨されるセキュリティ手法です。 (MySQL 3.23 は 100% クローズな chroot jail を提供できません)。 これは LOAD DATA INFILESELECT ... INTO OUTFILE を制限します。
--core-file
mysqld が死んだ場合 core ファイルを書き出します。いくつかのシステム では、--core-file-sizesafe_mysqld に記述する必要がありま す。 See section safe_mysqld, The Wrapper Around mysqld. 注意: Solaris のようないくつかのシステムでは、--user オプションも 使用すると core ファイルを得られません。
-h, --datadir=path
データベースルートのパス。
--debug[...]=
MySQL が --with-debug つきで configure された場合、このオ プション使用して、mysqld が何を行なっているかのトレースファイルを得 ることができます See section Creating Trace Files.
--default-character-set=charset
デフォルト のキャラクタ・セットの設定。 See section データとソートに使用されるキャラクター・セット.
--default-table-type=type
テーブルのデフォルトテーブル型を設定する。 See section MySQL テーブル型.
--delay-key-write[= OFF | ON | ALL]
MyISAM DELAYED KEYS が使用される方法。See section サーバーパラメーターのチューニング
--delay-key-write-for-all-tables; MySQL 4.0.3 では代わりに --delay-key-write=ALL を使用。
任意の MyISAM テーブルについて書き込み間でキーバッファをフラッシュ しません。 See section サーバーパラメーターのチューニング.
--des-key-file=filename
このファイルから DES_ENCRYPT()DES_DECRYPT() で使用され るデフォルトキーを読み込みます。
--enable-external-locking (4.0.3 から. それ以前のバージョンでは --enable-locking)
システムロックを有効にします。注意: lockd() が完全に働かない(Linux のよう な)システムでこのオプションを使用した場合、mysqld が簡単にデッドロックしま す。
--enable-named-pipe
名前付きパイプのサポートを有効にします (NT/Win2000/XP のみ)。
-T, --exit-info
mysqld サーバをデバッグするために使用できる、様々なフラグのビットマスクで す; 何が行なわれるのか正確に知らない場合は、このオプションを使用すべきでは ありません!
--flush
各 SQL コマンド後にすべての変更をディスクにフラッシュします。通常 MySQL は各 SQL コマンドにすべての変更をディスクに書き出すだけで、 OS がディスクへの sync を処理します。 See section What To Do If MySQL Keeps Crashing.
-?, --help
短いへルプを表示して終了します。
--init-file=file
起動時にファイルから SQL コマンドを読み込みます。
-L, --language=...
与えられた言語のクライアントエラーメッセージ。フルパスで与えることもできます。 See section Non-English Error Messages.
-l, --log[=file]
接続とクエリをファイルに記録します。 See section The General Query Log.
--log-bin=[file]
データを変更するすべてのクエリをファイルに記録します。バックアップとレプ リケーションのために使用されます。See section The Binary Update Log バイナリ更新ログ (3.23.15以上)
--log-bin-index[=file]
バイナリログファイル名のためのインデックスファイル。See section The Binary Update Log バイナリ更新ログ (3.23.15以上)
--log-error[=file]
エラーと起動メッセージをこのファイルに記録します。See section The Error Log
--log-isam[=file]
すべての ISAM/MyISAM 変更をファイルに記録します(ISAM/MyISAM のデバッグ時に のみ使用できます)。
--log-slow-queries[=file]
実行に long_query_time 秒以上掛かるすべてのクエリをファイルに記録し ます。 See section The Slow Query Log (3.23.28以上).
--log-update[=file]
更新を file.# に記録します。# は与えられなければ一意な番号で す。 See section 更新ログ.
--log-long-format
更新ログに拡張情報を記録します。--log-slow-queries を使用すると、イ ンデックスを使用しないクエリが slow query ログに記録されます。
--low-priority-updates
テーブル変更操作 (INSERT/DELETE/UPDATE) は SELECT よ りも低い優先度になります。あるクエリだけ優先度を低くするには、 {INSERT | REPLACE | UPDATE | DELETE} LOW_PRIORITY ... によって行 なわれます。また、ひとつのスレッドの優先度を変更するには、 SET LOW_PRIORITY_UPDATES=1 で行なわれます。 See section テーブル・ロッキングの問題.
--memlock
メモリに mysqld プロセスをロックします。これはシステムが mlockall() システムコールをサポートしている時(Solaris のように)にだけ動作します。 これは、OS が mysqld をディスク上にスワップさせる問題がある場合の助けに なります。
--myisam-recover [=option[,option...]]]
ここで option は DEFAULTBACKUPFORCEQUICK の組み合わせ. 3.23.26以上で有効. このオプションを使用すると、mysqld はオープン時にテーブルがクラッシュ したとマークされているかどうか、テーブルが適切にクローズされていないかどう かチェックします。(最後のオプションは --skip-external-locking (4.0.3より前のバージョンでは --skip-locking) で起動している 場合にだけ働きます)。この場合、mysqld はテーブル上でチェックを実 行します。テーブルが壊れている場合、mysqld はその修復を試みます。 次のオプションは修復の動作に影響します:
Option Description
DEFAULT --myisam-recover にオプションを与えないのと同じです。
BACKUP データテーブルが修復中に変更された場合、 `table_name.MYD' データファイルのバックアップを `table_name-datetime.BAK' に保存します。
FORCE .MYD ファイルからひとつより多くのレコードが失われている 場合でも修復を実行します。
QUICK 削除ブロックがない場合にテーブル内のレコードをチェック しません。
テーブルが自動的に修復される前に、MySQL はエラーログにこれについ てのメモを追加します。ユーザの介入なしで多くのことを修復したい場合は、オプ ション BACKUP,FORCE を使用すべきです。いくつかのレコードが削除され る場合でも、テーブルを強制的に修復しますが、古いデータファイルをバックアッ プとして保存するため、あとで何が起こったか検証できます。
--pid-file=path
safe_mysqld によって使用される pid ファイルのパス。
-P, --port=...
TCP/IP 接続で listen するポート番号。
-o, --old-protocol
とても古いクライアントとの互換のために、3.20 プロトコルを使用します。 See section バージョン 3.20 から バージョン 3.21 へのアップグレード.
--one-thread
一つのスレッドだけを使用します(Linux 下でデバックするため)。 See section MySQL server のデバッグ.
-O, --set-variable var=option
変数に値を与えます。--help は変数をリストします。すべての変数の完全 な詳細はこのマニュアルの SHOW VARIABLES 節で見られます。 See section SHOW VARIABLES。サーバパラメータの調整についての節はこれらの最適化 方法の情報を含んでいます。 MySQL 4.0 からは --set-variable は推奨されないことに注意してください。 --var=option を使用してください。 See section サーバーパラメーターのチューニング。 MySQL 4.0.2 では、--variable-name=option で直接変数を設定できます。 set-variable はオプションファイル中ではもはや必要ありません。 SET で設定できる起動オプションの最大値を制限したい場合は、 --maximum-variable-name コマンドラインオプションを使用することで 定義できます。See section SET 構文。 注意: 変数に値を設定する時、MySQL は自動的に与えられた範囲に収まるように 補正し、使用されるアルゴリズム用に合うように値を少し調整します。
--safe-mode
いくつかの最適化ステージをスキップします。
--safe-show-database
このオプションをつけると、SHOW DATABASES コマンドは、ユーザが何か の権限を持つデータベースだけを返します。 バージョン 4.0.2 からはこのオプションは推奨されず何もしません(デフォルト でこのオプションは有効です)。現在は SHOW DATABASES 権限を持つため です。See section GRANTREVOKE 構文
--safe-user-create
これが有効な場合、ユーザが mysql.user テーブルやこのテーブル内の 任意のフィールドについて INSERT 権限を持っていない場合、そのユー ザは GRANT コマンドで新しいユーザを作成できません。
--skip-bdb
BDB テーブルの使用を無効にします。これはメモリを節約し、いくつかのことを 高速化します。
--skip-concurrent-insert
同時に MyISAM テーブルに select と insert を行なう機能をオフにしま す。(この機能にバグを見つけたと考える場合にだけ使用します)。
--skip-delay-key-write; MySQL 4.0.3 では代わりに --delay-key-write=OFF を使用
すべてのテーブルに対し DELAY_KEY_WRITE オプションを無視します。 See section サーバーパラメーターのチューニング.
--skip-grant-tables
このオプションは、サーバをすべての権限システムを使用しないようにします。これ は全員にすべてのデータベースへの完全アクセスを与えます! (mysqladmin flush-privilegesmysqladmin reload を実行する ことで、権限テーブルを使用して起動するように実行中のサーバに伝えることがで きます。)
--skip-host-cache
より速いホスト名-IP解決のためのホスト名キャッシュを使用しません。代わりに すべての接続で DNS サーバへクエリします。 See section How MySQL uses DNS.
--skip-innodb
Innodb テーブルの使用を無効にします。これはメモリとディスク領域の節約と いくつかのことを高速化します。
--skip-external-locking (4.0.3から. 4.0.3より前では --skip-locking)
システムロックを使用しません。isamchk または myisamchk を使 用するためには、サーバをシャットダウンする必要があります。 See section MySQL はどれくらい安定か?。注意: MySQL バージョン 3.23 では、 REPAIRCHECKMyISAM テーブルの修復/チェックに 使用できます。
--skip-name-resolve
ホスト名を解決しません。権限テーブルのすべての Host フィールド値は IP 番号か localhost でなければなりません。 See section How MySQL uses DNS.
--skip-networking
TCP/IP 接続の listen をまったく行ないません。mysqld との接続には Unix ソケット経由で行なう必要があります。このオプションはローカル要求だけ を許可するシステムでは、高く推奨されます。 See section How MySQL uses DNS.
--skip-new
Don't use new, possible wrong routines.
--skip-symlink
データディレクトリ中のシンボリックリンクファイルが指すファイルを削除、リ ネームしません。
--skip-safemalloc
MySQL が --with-debug=full で configure されている場合、す べてのプログラムがすべてのメモリ割り当てとメモリ解放をオーバーラン用にチェッ クします。このチェックはとても遅いので、メモリチェックが不要な場合、このオ プションを使用することでこれを無効にできます。
--skip-show-database
SHOW DATABASES 権限を持っていないユーザに SHOW DATABASES コマンドを 許しません。 バージョン 4.0.2 からは、このオプションは必要ありません。現在、アクセス は SHOW DATABASES 権限で特別に与えられるためです。
--skip-stack-trace
スタックトレースを書き出しません。このオプションは、mysqld をデバッ ガ下で実行している時に有用です。 いくつかのシステムでは、core ファイルを得るためにこのオプションも使用す る必要があります。See section MySQL server のデバッグ
--skip-thread-priority
より速いレスポンスタイム用のスレッド優先度の使用を無効にします。
--socket=path
デフォルト /tmp/mysql.sock の代わりに、ローカル接続用に使用されるソ ケットファイル。
--sql-mode=option[,option[,option...]]
オプションは次の任意の組合わせです: REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, SERIALIZE, ONLY_FULL_GROUP_BY。リセットしたい場合は、空 ("") も指定できます。 上記オプションの全てを指定することで、--ansi の使用と同じになります。 このオプションで、必要とされる SQL モードだけを有効にできます。 See section Running MySQL in ANSI Mode
--temp-pool
Using this option will cause most temporary files created to use a small set of names, rather than a unique name for each new file. This is to work around a problem in the Linux kernel dealing with creating a bunch of new files with different names. With the old behaviour, Linux seems to 'leak' memory, as it's being allocated to the directory entry cache instead of the disk cache.
--transaction-isolation= { READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE }
トランザクション分離レベルのデフォルトを設定します。See section SET TRANSACTION 構文
-t, --tmpdir=path
一時ファイル用のパス。デフォルトの /tmp ディレクトリが一時テーブル を保持するのに小さすぎるパーティション上にある場合に有用です。 MySQL 4.1 からは、このオプションはコロン :(Windows ではセミコロン ;)で区切られたいくつかのパスを受け付けます。これらはラウンドロビ ン方法で使用されます。
-u, --user= [user_name | userid]
ユーザ user_nameuserid (数値) で mysqld デーモンを実行します。 このオプションは、mysqld を root で起動した時に 強制されます。 Starting from MySQL 3.23.56 and 4.0.12: To avoid a possible security hole where a user adds an --user=root option to some `my.cnf' file, mysqld will only use the first --user option specified and give a warning if there are multiple options. Note that `/etc/my.cnf' and `datadir/my.cnf' may override a command line option - therefore it is recommended to put this option in `/etc/my.cnf'.
-V, --version
バージョン情報を出力して終了します
-W, --log-warnings (4.0.3 より前では --warnings)
Aborted connection... のような警告を .err ファイルに出力します。 See section Communication Errors / Aborted Connection.

SET コマンドで実行中のサーバの多くの値を変更できます。 See section SET 構文

`my.cnf' オプションファイル

MySQL バージョン 3.22 のサーバー、クライアントともに、 オプションファイルからデフォルトの起動オプションを読み込むことができます。

Unix では MySQL は以下のファイルからデフォルトオプションを読みます:

ファイル名 意味
/etc/my.cnf グローバルなオプション
DATADIR/my.cnf サーバ固有オプション
defaults-extra-file --defaults-extra-file=# で指定されたファイル
~/.my.cnf ユーザ固有オプション

DATADIR は MySQL データディレクトリです (普通 バイナリディストリビューションでは `/usr/local/mysql/data' 、ソースディストリビューションでは `/usr/local/var'). このディレクトリはconfigure時に決定されており、 --datadirmysqld 起動時に指定しても変更されません。 (サーバーはコマンドラインの引数を処理する前にオプションファイルを探します。 よって、--datadir 引数を指定してもオプションファイルを探す場所を指定することにはなりません。)

Windows では MySQL は以下のファイルからデフォルトオプションを読みます:

ファイル名 意味
windows-system-directory\my.ini グローバルオプション
C:\my.cnf グローバルオプション

注意: Windows では \ の代わりに / で全てのパスを記述すべきで す。\ を使用する場合、\ は MySQL のエスケープ文字 なので、これを二重に記述する必要があります。

MySQL は上記の表にかかれている順にオプションファイルを読みます。 もし複数オプションファイルがあった場合、後から読まれた設定が有効になります。 全てのオプションはコマンドラインの引数に上書きされます。 いくつかのオプションは環境変数に定義できます。 オプションファイルとコマンドラインの引数は環境変数を上書きします。 See section Environment Variables.

次のプログラムはオプションファイルをサポートします: mysql, mysqladmin, mysqld, mysqld_safe, mysql.server, mysqldump, mysqlimport, mysqlshow, mysqlcheck, myisamchk, myisampack.

オプションファイルには、プログラムがサポートしているコマンドラインの long オプション(例えば、-u ではなくて --user の方)を書くことができます。 プログラムを --help で起動すれば、設定可能な変数名が得られます。

オプションファイルの書式は以下です:

#comment
コメントは `#'`;' 文字で始めます。空の行は無視します。
[group]
グループ宣言。 group はオプションを定義するプログラムかグループの名前です。 この宣言の後、オプションset-variable 行で、このグループにオプションを与えます。 このセクションの範囲は、他のグループ宣言の行が来るか、ファイルの最後に来るまでです。
option
これはコマンドラインの --option と等価です。
option=value
これはコマンドラインの --option=value と等価です。
set-variable = variable=value
これはコマンドラインの --set-variable variable=value と等価です。 これは mysqld 変数で使用される形式です。 MySQL 4.0 からは --set-variable は推奨されないことに注意してくだ さい。--variable=value を使用してください。

client グループは、全ての MySQL クライアント(mysqldは除)に対してオプションを定義します。 これはサーバーに接続する際に使用するパスワードを指定できるグループです。 (この場合、オプションファイルは自分だけが読み書きできるようにしてください)

オプションや値の善後にある全てのブランク文字は自動で取り除かれます。 値として、`\b',`\t', `\n', `\r', `\\', `\s' のエスケープシーケンスが使用できます。 (`\s' == blank).

オプションファイル例:

[client]
port=3306
socket=/tmp/mysql.sock

[mysqld]
port=3306
socket=/tmp/mysql.sock
set-variable = key_buffer_size=16M
set-variable = max_allowed_packet=1M

[mysqldump]
quick

ユーザーオプションファイル例:

[client]
# The following password will be sent to all standard MySQL clients
password=my_password

[mysql]
no-auto-rehash
set-variable = connect_timeout=2

[mysqlhotcopy]
interactive-timeout

もしソース配布を持っているなら、 `my-xxxx.cnf' という名前のサンプルファイルを `support-files' ディレクトリに見ることができます。 もしバイナリ配布を使用しているなら、 `DIR/support-files' ディレクトリを探してください (ここで DIR は MySQL がインストールされたディレクトリのパス名で、 普通は `/usr/local/mysql')。 この `my-xxxx.cnf' ファイルを自分のディレクトリに `.my.cnf' という名前でコピーして使用できます。

オプションファイルをサポートするすべての MySQL クライアントは次 のオプションをサポートします:

Option Description
--no-defaults オプションファイルを読み込まない。
--print-defaults プログラム名と得られる全てのオプションを出力する。
--defaults-file=full-path-to-default-file 与えられたコンフィグレーションファイルだけを使用する。
--defaults-extra-file=full-path-to-default-file グローバルコンフィグレーションファイルの後、ユーザコンフィグレーションファイルの前にこのコンフィグレーションファイルを読み込む。

注意: 上記のオプションはコマンドラインの先頭になければ働きません! ただ し、--print-defualts--defaults-xxx-file コマンドの直後 にも置けます。

開発者向け情報: オプションファイルの操作は全てのオプションをコマンドラインの 引数より先に処理するように簡単に埋め込まれています。 これはオプションを最後に処理するプログラムを複数立ちあげる場合に都合よく動きます。 もしオプションファイルを読み込む機能のない古いプログラムを使用しているなら、 たった二行だけ注意して書けばいいだけです。 この動作については MySQL クライアントプログラムのコードを参考にしてください。

シェルスクリプト内では、`my_print_defaults' コマンドを使用して、コ ンフィグファイルを解析することができます:


shell> my_print_defaults client mysql
--port=3306
--socket=/tmp/mysql.sock
--no-auto-rehash

上記は、'client' と 'mysql' グループ用の全オプションを出力します。

同じマシンに多くのサーバをインストールする

同じマシン上で多くの異なる mysqld デーモン(サーバ)を動作させたい場 合があります。例えば、テスト用に MySQL の新しいバージョンを使用中の 古いバージョンと共に実行したい場合や、異なる mysqld サーバにそれを管理する 異なるユーザアクセスを与えたい場合などです。

一つの方法は、新しいサーバを次のように異なるソケットとポートで起動すること です:

shell> MYSQL_UNIX_PORT=/tmp/mysqld-new.sock
shell> MYSQL_TCP_PORT=3307
shell> export MYSQL_UNIX_PORT MYSQL_TCP_PORT
shell> scripts/mysql_install_db
shell> bin/safe_mysqld &

The environment variables appendix は mysqld に影響する他の環境変数の 一覧を含んでいます。 See section Environment Variables.

The above is the quick and dirty way that one commonly uses for testing. The nice thing with this is that all connections you do in the above shell will automatically be directed to the new running server!

If you need to do this more permanently, you should create an option file for each server. See section `my.cnf' オプションファイル. In your startup script that is executed at boot time you should specify for both servers:

safe_mysqld --defaults-file=path-to-option-file

少なくとも、次のオプションはサーバごとに異なるようにすべきです:

次のオプションが使用される場合、異なるようにすべきです:

さらに性能を求める場合、次も異なるように記述できます:

See section mysqld コマンド行オプション. Starting from MySQL 4.1, tmpdir can be set to a list of paths separated by colon : (semicolon ; on Windows). They will be used in round-robin fashion. This feature can be used to spread load between several physical disks.

バイナリの MySQL バージョン (.tar ファイル) をインストールして、 ./bin/safe_mysqld で起動する場合、多くの場合では、追加/変更する必要 のあるオプションは safe_mysqld への socketport 引 数だけです。

See section 同一マシン上に複数の MySQL サーバーを走らせる.

同一マシン上に複数の MySQL サーバーを走らせる

同じマシン上で複数のサーバーを走らせたい場合があります。 例えば、すでに存在しているサーバーはそのままにしておいて、新しい MySQL をテストしたい場合や、 あるいは、インターネットプロバイダーを営んでいて、MySQL をそれぞれの顧客用に提供したい場合など。

複数のサーバーをたちあげる場合、簡単な方法として、 TCP/IP ポート、ソケットファイルを変えて、サーバーをコンパイルする方法があります。 See section mysqld_multi, 複数の MySQL サーバーを管理するプログラム.

そでに走っているサーバーがデフォルトのポート番号とソケットファイルで動作しているとします。 新しくサーバーを作るには、以下のように configure します:

shell> ./configure  --with-tcp-port=port_number \
             --with-unix-socket-path=file_name \
             --prefix=/usr/local/mysql-3.22.9

port_numberfile_name には、デフォルトのポート番号、 ソケットファイルとは違うものを指定します。 そして --prefix を、すでに走っている MySQL の インストール先とは違うディレクトリーに指定します。

現在走っている MySQL サーバーが使用している ソケットとポートをチェックするには、以下のようにします:

shell> mysqladmin -h hostname --port=port_number variables

Note that if you specify ``localhost'' as a hostname, mysqladmin will default to using Unix sockets instead of TCP/IP.

In MySQL 4.1 you can also specify the protocol to use by using the --protocol=(TCP | SOCKET | PIPE | MEMORY) option.

あなたが使用しているポートに MySQL サーバーが走っていれば、 これは変更可能な MySQL 変数を(ソケットファイルの名前も含んで)出力します。

この場合、MySQL サーバーを再コンパイルする必要はありません。 safe_mysqld のオプションを指定してサーバーを起動すれば、 ポートとソケットを変更できます:

shell> /path/to/safe_mysqld --socket=file_name --port=port_number

mysqld_multi can also take safe_mysqld (or mysqld) as an argument and pass the options from a configuration file to safe_mysqld and further to mysqld.

もし、他のサーバーがロギングを行っているディレクトリと同じデータベースディレクトリを、 新しいサーバーで使用するのであれば、ログファイルの名前を指定すべきです。 ( safe_mysqld--log , --log-update , --log-slow-queries を指定する) そうしないと、両方のサーバーが同じログファイルに書き込もうとするからです。

Warning: 通常、二つサーバーに同じデータベースを操作させてはいけません! もし使用している OS が fault-free system locking をサポートしていないと、 これは悲惨なことになるでしょう!

もし二つ目のサーバーに違うデータベースディレクトリを使用させたい場合、 safe_mysqld--datadir=path オプションを指定します。

Note also that starting several MySQL servers (mysqlds) in different machines and letting them access one data directory over NFS is generally a bad idea! The problem is that the NFS will become the bottleneck with the speed. It is not meant for such use. And last but not least, you would still have to come up with a solution how to make sure that two or more mysqlds are not interfering with each other. At the moment there is no platform that would 100% reliable do the file locking (lockd daemon usually) in every situation. Yet there would be one more possible risk with NFS; it would make the work even more complicated for lockd daemon to handle. So make it easy for your self and forget about the idea. The working solution is to have one computer with an operating system that efficiently handles threads and have several CPUs in it.

もし違うポートで走っている MySQL サーバーに、 これまた違うポートを使用するように作られたクライアントから接続したい場合、 以下のようにします:

General Security Issues and the MySQL Access Privilege System

MySQL has an advanced but non-standard security/privilege system. This section describes how it works.

General Security Guidelines

よくあるセキュリティの間違いを避けるために、インターネットに接続されたコン ピュータ上で MySQL を使用する誰もが、このセクションを読むべきです。

``セキュリティ'' の議論において、我々は、すべての該当するアタックタイプ (eavesdropping, altering, playback, Denial of Service) に対して、すべてのサー バホスト(MySQL サーバだけではなく)の完全な保護の必要性を強調しま す。We do not cover all aspects of availability and fault tolerance here.

MySQL は、ユーザが実行しようとするすべての接続、クエリ、その他の オペレーションに対して、アクセス制御リスト(ACLs: Access Control Lists)セキュ リティを使用します。MySQL クライアントとサーバの間で SSL 暗号化接 続のサポートもいくつかあります。ここで議論されるコンセプトの多くは、 MySQL に特有のものではありません; 同じ一般的なアイデアはほとんど すべてのアプリケーションに適用します。

MySQL 実行時、可能な限りいつでもこれらのガイドラインに従ってくだ さい:

MySQL をクラッカーに対して安全にする方法

MySQL サーバーに接続するときは、パスワードを使用すべきです。 パスワードはコネクション間で、べたテキストでは流れません。 しかし、暗号化アルゴリズムはそんなに強力なわけではありません。クライアント とサーバ間のトラフィックを sniff できれば、いくつかの試みで、賢いアタッカー はパスワードをクラックできます。クライアントとサーバ間の接続が信頼できない ネットワークを通るなら、通信を暗号化するために SSH トンネルを使用 すべきです。

その他の全ての情報はテキストで転送され、 これは接続を覗くことが出来る人に読まれます。 もしこれを心配するなら、圧縮プロトコル(MySQL バージョン 3.22 以上)を 使用することが出来ます。より安全にしたい場合、 ssh をインストールすべきです。 オープンソースの ssh クライアントは http://www.openssh.org/ に、 商用の ssh クライアントは http://www.ssh.com/ に見ることができます。 これを使用すれば、MySQL サーバーと MySQL クライアント 間の TCP/IP コネクションは全て暗号化されます。

If you are using MySQL 4.0, you can also use internal OpenSSL support. See section Using Secure Connections.

MySQL システムを安全にするためには、次のことを考えるべきです:

セキュリティに関する mysqld の起動オプション

mysqld の次のオプションはセキュリティに影響します:

--local-infile[=(0|1)]
If one uses --local-infile=0 then one can't use LOAD DATA LOCAL INFILE.
--safe-show-database
With this option, the SHOW DATABASES command returns only those databases for which the user has some kind of privilege. From version 4.0.2 this option is deprecated and doesn't do anything (the option is enabled by default) as we now have the SHOW DATABASES privilege. See section GRANTREVOKE 構文.
--safe-user-create
If this is enabled, an user can't create new users with the GRANT command, if the user doesn't have the INSERT privilege for the mysql.user table. If you want to give a user access to just create new users with those privileges that the user has right to grant, you should give the user the following privilege:
mysql> GRANT INSERT(user) ON mysql.user TO 'user'@'hostname';
This will ensure that the user can't change any privilege columns directly, but has to use the GRANT command to give privileges to other users.
--skip-grant-tables
特権システムを全く使用しません。これは全員に全てのデータベースへの 完全なアクセス を与えます! (mysqladmin flush-privilegesmysqladmin reload を実行することで、 起動しているサーバーは特権システムを使用するようになります。)
--skip-name-resolve
ホスト名を解析しません。権限テーブル中の全ての Hostフィールドは IP アドレスか localhost でなければなりません。
--skip-networking
ネットワーク (TCP/IP) 経由の接続を許可しません。mysqld への全ての接続は、 Unix ソケットで行われます。MIT-pthreads は Unix ソケットをサポートしない ため、このオプションは MIT-pthreads を使用するシステム上で MySQL 3.23.27 以前のバージョンを使用する場合は、うまく動きません。
--skip-show-database
Don't allow SHOW DATABASES command, unless the user has the SHOW DATABASES privilege. From version 4.0.2 you should no longer need this option, since access can now be granted specifically with the SHOW DATABASES privilege.

Security issues with LOAD DATA LOCAL

In MySQL 3.23.49 and MySQL 4.0.2, we added some new options to deal with possible security issues when it comes to LOAD DATA LOCAL.

There are two possible problems with supporting this command:

As the reading of the file is initiated from the server, one could theoretically create a patched MySQL server that could read any file on the client machine that the current user has read access to, when the client issues a query against the table.

In a web environment where the clients are connecting from a web server, a user could use LOAD DATA LOCAL to read any files that the web server process has read access to (assuming a user could run any command against the SQL server).

There are two separate fixes for this:

If you don't configure MySQL with --enable-local-infile, then LOAD DATA LOCAL will be disabled by all clients, unless one calls mysql_options(... MYSQL_OPT_LOCAL_INFILE, 0) in the client. See section mysql_options().

For the mysql command-line client, LOAD DATA LOCAL can be enabled by specifying the option --local-infile[=1], or disabled with --local-infile=0.

By default, all MySQL clients and libraries are compiled with --enable-local-infile, to be compatible with MySQL 3.23.48 and before.

One can disable all LOAD DATA LOCAL commands in the MySQL server by starting mysqld with --local-infile=0.

In the case that LOAD DATA LOCAL INFILE is disabled in the server or the client, you will get the error message (1148):

The used command is not allowed with this MySQL version

特権システムの行うこと

MySQL 特権システムの基本機能は、与えられたホストから接続する ユーザを認証すること、そしてデータベースに対する SELECT, INSERT, UPDATE, DELETE 等の権限を与えることです。

拡張機能は匿名ユーザをもつ能力を含み、LOAD DATA INFILE のような MySQL 固有の機能を使用する許可を与えます。

特権システムはどのように動くか?

MySQL の特権システムは、全てのユーザーが与えられた許可の範囲内で動く事を保証します。 MySQL サーバーに接続するとき、本人の身元は、接続元のホスト接続に使用するユーザー名 によって確認されます。 このシステムは、あなたの身元とあなたが要求することが何か によって、権限を与えます。

MySQL はあなたのホスト名とユーザー名の両方をあわせてチェックします。 これはインターネット上に同じ名前のユーザーがどこかにいるかもしれないということからそうしています。 例えば、office.com から接続してきた joe と、 elsewhere.com から接続してきた joe は同一人物である必要はありません。 MySQL はこの違うホストから接続してきた同名のユーザーを以下のようにして扱います: office.com から接続した joe にある許可をあたえ、 それとは違う許可を elsewhere.com から接続してきた joe に与えます。

MySQL のアクセスコントロールは以下の二つからなります:

サーバーは mysql データベースの user, db, host 3つのテーブルから、 この2つのアクセス制限を決定します。 このテーブルのフィールドは以下のようになっています:

Table name user db host
Scope fields Host Host Host
User Db Db
Password User
Privilege fields Select_priv Select_priv Select_priv
Insert_priv Insert_priv Insert_priv
Update_priv Update_priv Update_priv
Delete_priv Delete_priv Delete_priv
Index_priv Index_priv Index_priv
Alter_priv Alter_priv Alter_priv
Create_priv Create_priv Create_priv
Drop_priv Drop_priv Drop_priv
Grant_priv Grant_priv Grant_priv
References_priv
Reload_priv
Shutdown_priv
Process_priv
File_priv

 アクセスコントロールの第2段階(要求承認)のために、サーバーはこれら 3 つの テーブルによって決められた許可を基本としますが、もしテーブルに対する要求で あるならば、tables_privcolumns_priv テーブルを さらに調べます。これらのテーブルのフィールドは以下のようになっています:

Table name tables_priv columns_priv
Scope fields Host Host
Db Db
User User
Table_name Table_name
Column_name
Privilege fields Table_priv Column_priv
Column_priv
Other fields Timestamp Timestamp
Grantor

 テーブルの各フィールドを分類すると、2種類にわかれます: 適用範囲を指定するフィールド(以下 スコープフィールド)と許可を定義するフィールド(以下 権限フィールド)です。

 スコープフィールドは、権限テーブルの登録ごとに、その適用範囲を決めます。 例えば、 user テーブルの HostUser'thomas.loc.gov''bob' が登録されている場合、 サーバーへの接続は ホスト thomas.loc.gov から来た 'bob' に許可されます。 同様に、db テーブルの Host, User, Db'thomas.loc.gov', 'bob', 'reports' が登録されていると、 ホスト thomas.loc.gov から来た bob に対し reports データベースへの接続が許されます。 tables_privcolumns_priv テーブルは、 テーブルか、テーブルとフィールドを対にしたスコープフィールドを含みます。

 アクセスのチェックは、Host の値はケース非依存で比較されます。 User, Password, Db, Table_name の値はケース依存で比較されます。 Column_name の値は MySQL バージョン 3.22.12 以上ではケース非依存で比較されます。 (バージョン 3.22.11 までは ケース依存です)

権限フィールドは、どのような操作が実行できるか、許可されているかを示します。 サーバーは権限テーブルの情報を、ユーザーの権限を得るために使用します。 このユーザーの権限を割り出す方法は section Access Control, Stage 2: Request Verification に述べておきます。

スコープフィールドは文字で定義され、デフォルト値は空文字になっています:

Field name Type Notes
Host CHAR(60)
User CHAR(16)
Password CHAR(16)
Db CHAR(64) (CHAR(60) for the tables_priv and columns_priv tables)
Table_name CHAR(60)
Column_name CHAR(60)

user, db, host テーブルでは、 全ての権限フィールドは ENUM('N','Y') で定義されます。 この値は 'N''Y' のどちらかで、デフォルト値は 'N' です。

tables_privcolumns_priv テーブルでは、 権限フィールドは SET フィールドとして定義されます:

Table name Field name Possible set elements
tables_priv Table_priv 'Select', 'Insert', 'Update', 'Delete', 'Create', 'Drop', 'Grant', 'References', 'Index', 'Alter'
tables_priv Column_priv 'Select', 'Insert', 'Update', 'References'
columns_priv Column_priv 'Select', 'Insert', 'Update', 'References'

サーバーは以下のように権限テーブルを使用します:

管理者権限 (RELOAD, SHUTDOWN,など) は user テーブルにだけ定義するように。 これは、管理者操作はデータベースではなくサーバーへの操作であり、 他の許可テーブルにある必要がないからです。 またこうしておくと、管理者操作の許可は、user テーブルの定義だけを 見ればわかるようになります。

FILE 操作の権限は user テーブルにだけ定義するように。 これは管理者操作ではありませんが、アクセスしているデータベースにかかわらず、 サーバー内のファイルを読み書きできるのです。

mysqld サーバーは起動時にこれらのテーブルを読み込みます。 許可テーブルの変更を反映させる方法はこちらを参照のこと → section いつ権限の変更が反映されるか

これらのテーブルの登録を変更した場合、思ったとおりの権限状態になっている事を確認することはいいことです。 問題の解決には, section 何故 Access denied エラーになるのか. セキュリティに関するアドバイスは section MySQL をクラッカーに対して安全にする方法.

便利なツールとして mysqlaccess スクリプト( Yves Carlier 作)が MySQL の配布に含まれています。 mysqlaccess--help オプションで起動するとヘルプが表示されます。 mysqlaccessuser,db and host テーブルだけしか 検査しません。テーブルレベルの権限、フィールドレベルの権限は調べません。

MySQL が提供する権限

権限の設定は mysql データベースの user, db, host, tables_priv, columns_priv で行います。 (mysql はデータベースの名前です) MySQL サーバーは、サーバーの起動時か section いつ権限の変更が反映されるか で説明されている方法により、 これらのテーブルから権限の設定を読み込みます。

MySQL 4.0.2 が提供する権限の名称は, 本マニュアルでは以下の表の名称を用います。 この表の項目名がそれぞれの許可される権限とその説明に対応しています:

Privilege Column Context
ALTER Alter_priv tables
DELETE Delete_priv tables
INDEX Index_priv tables
INSERT Insert_priv tables
SELECT Select_priv tables
UPDATE Update_priv tables
CREATE Create_priv databases, tables, or indexes
DROP Drop_priv databases or tables
GRANT Grant_priv databases or tables
REFERENCES References_priv databases or tables
CREATE TEMPORARY TABLES Create_tmp_table_priv server administration
EXECUTE Execute_priv server administration
FILE File_priv file access on server
LOCK TABLES Lock_tables_priv server administration
PROCESS Process_priv server administration
RELOAD Reload_priv server administration
REPLICATION CLIENT Repl_client_priv server administration
REPLICATION SLAVE Repl_slave_priv server administration
SHOW DATABASES Show_db_priv server administration
SHUTDOWN Shutdown_priv server administration
SUPER Super_priv server administration

SELECT, INSERT, UPDATE, DELETE の権限は、 存在しているデータベースのテーブルに対して許可されます。

もしテーブルから行を取り出すだけなら、SELECT 構文を実行するためには SELECT 権限だけあればかまいません。 ただし、サーバーのどのデータベースにアクセスを許可されていない場合でも、 ある種の SELECT は実行することができます。 例えば、簡単な計算を mysql クライアントで行う場合です:

mysql> SELECT 1+1;
mysql> SELECT PI()*2;

INDEX 権限はインデックスの作成と破棄(削除)を許可します。

ALTER 権限は ALTER TABLE の実行を許可します。

CREATEDROP 権限は、新しいデータベースやテーブルの作成、 あるいは既に存在するデータベース、テーブルの破棄(削除)を許可します。

注意: mysql データベースに登録されているユーザーに DROP 権限を与えると、 そのユーザーは MySQL のアクセス権限が格納されているデータベースを破棄できます!

GRANT 権限は、あなたが他のユーザーに対して自分の権限を持たせる事を許可します。

FILE 権限を与えると、LOAD DATA INFILESELECT ... INTO OUTFILE 構文を 使用して、サーバーのファイルを読み書きする事ができます。 この権限が与えられたユーザーは、MySQL サーバーを使用していかなるファイルも 読むことが出来ますし、MySQL サーバーが書き込めるディレクトリに誰もが読める 新しいファイルを作成することも出来ます。 そのユーザーはカレントのデータベースのディレクトリにあるいかなるファイルも 読むことができます。 しかし、既に存在しているファイルを変更することはできません。

残りの権限はアドミン操作に関する許可で、mysqladmin コマンドを使用して実行します。 次の表に mysqladmin コマンドのどれが、どの権限に対応しているかを示します:

Privilege Commands permitted to privilege holders
RELOAD reload, refresh, flush-privileges, flush-hosts, flush-logs, and flush-tables
SHUTDOWN shutdown
PROCESS processlist
SUPER kill

reload コマンドはサーバーに権限の設定を再読込させるように伝えます。 refresh コマンドは全てのテーブルをフラッシュし、ログファイルを開き直します。 flush-privilegesreload と同義です。 その他の flush-* コマンドは refresh の動作とよく似ていますが、 適用範囲を絞っており、ちょっとした場合に有効です。 例えば、ログファイルだけをフラッシュしたい場合、 refresh を行うよりも flush-logs がいいです。

shutdown コマンドは、サーバーをシャットダウンします。

processlist コマンドはサーバーが実行しているスレッドの情報を表示します。 kill コマンドはサーバーのスレッドをkillします。 自分のスレッドは常に表示、killできますが、他人のスレッドを見るには PROCESS 権限が必要で、他人のスレッドをkillするには SUPER 権限が必要です。See section KILL 構文. (SUPER 権限は 4.0.2で追加されました)

ある権限を欲しがるユーザーだけにその権限を許可するのはよい考えですが、 権限を与えるときには、特定の事項を熟知していなければなりません:

以下は MySQL の特権システムで行うものではありません:

MySQL サーバーに接続

MySQL クライアントプログラムは、共通の決まった引数を持ちます: 接続したいホスト名、接続ユーザー名、そしてパスワードです。 例えば、mysql コマンドは以下のような引数を持ちます (オプションの引数は `['`]' で囲まれている部分です)

shell> mysql [-h host_name] [-u user_name] [-pyour_pass]

-h, -u, -p オプションは以下と等価です。 --host=host_name, --user=user_name, --password=your_pass -p とパスワードの間にはスペースがないことに注意

注意: コマンドラインにパスワードを与えるのは安全ではありません! システムに入っている如何なるユーザーも ps auxww のようなコマンドを 使用する事でパスワードを見付ける事ができます. See section `my.cnf' オプションファイル.

mysql コマンドはコマンドラインに引数がなければ接続にデフォルト値を用います。

Unix のログインユーザーが joe の場合、以下のコマンドは等価です:

shell> mysql -h localhost -u joe
shell> mysql -h localhost
shell> mysql -u joe
shell> mysql

他の MySQL クライアントも同じように動作します。

Unix システムでは、ある値をデフォルト値にして接続に使用することができます。 そうすることにより、毎回毎回コマンドラインに引数を与えなくてすむようになります:

Access Control, Stage 1: 接続の承認

MySQL サーバーに接続すると、あなたがパスワード認証して接続していようがいまいが、 サーバーはあなたの身元により接続の許可拒否を行います。 もし身元が一致しない場合接続を拒否し、接続許可した場合、 サーバーは Stage 2 へと進み、要求を待ちます。

身元は二つのものに基づいて確認されます:

身元の確認は user テーブルのスコープフィールド (Host, User, Password) を使用して行います。 サーバーは user テーブルの登録に一致しているホスト名と ユーザー名に限り接続を許可し、その後、パスワードを要求します。

user テーブルのスコープフィールドの登録は以下のようになります:

非ブランクの Password 値はパスワードを暗号化したものです。 MySQL はだれもが見れるようにパスワードを平文では保存しません。 接続を試みようとしているユーザーのパスワードも、(PASSWORD() 関数で) 暗号化されます。 それから、暗号化パスワードは、クライアント/サーバがパスワードが正しいかチェッ クする時に使用されます(This is done without the encrypted password ever traveling over the connection)。注意: MySQL では、暗号化パスワー ドが本当のパスワードです。そのため、それへのアクセスを誰にも与えるべきでは ありません! 特に、一般ユーザにはmysql データベース内のテーブルの読 み取り権を与えないでください! From version 4.1, MySQL employs a different password and login mechanism that is secure even if TCP/IP packets are sniffed and/or the mysql database is captured.

以下の表は、接続要求に対して与える、 user テーブルの HostUser の設定例です:

Host value User value Connections matched by entry
'thomas.loc.gov' 'fred' fred, thomas.loc.gov から接続
'thomas.loc.gov' '' thomas.loc.gov から接続してくる全てのユーザー
'%' 'fred' fred, 全てのホストから接続
'%' '' 全てのホストから接続してくる全ユーザー
'%.loc.gov' 'fred' fred, loc.gov ドメイン内の全てのホストからの接続
'x.y.%' 'fred' fred, x.y.net, x.y.com,x.y.edu, などからの接続. (あまり有効な使い方ではないです)
'144.155.166.177' 'fred' fred, IP address が 144.155.166.177 のホストからの接続
'144.155.166.%' 'fred' fred, 144.155.166 class C subnet 内の全てのホストからの接続
'144.155.166.0/255.255.255.0' 'fred' 上の例と同じ

Host に IP のワイルドカード(例えば '144.155.166.%' は サブネットの全てのホストにマッチ) を使用することができます。 が、この場合、 144.155.166.somewhere.com というホスト名で だれかが接続しようとしてくるかもしれません。 このような攻撃に対し、MySQL は数字やドットで始まるホスト名を拒否しています。 もし 1.2.foo.com のような名前のホストを持っている場合、 許可テーブルの Host には絶対にマッチしません。 IPアドレスのみ、IP のワイルドカードにマッチする事になります。

サーバーに来る接続は、user テーブル内の登録に1つ以上 マッチするかもしれません。 例えば, thomas.loc.govfred からの接続は、上に示された 登録のうちのいくつかにマッチするでしょう。 サーバーは、複数の登録にマッチした場合、どのようにしてその中から 使用する登録を選ぶのでしょう? サーバーは起動後に user テーブルをソートし、並び換えられた順に 登録を検索することにより、この問題を解決します。 最初にマッチした登録が使用されます。

user テーブルが以下のようにソートされていた場合:

+-----------+----------+-
| Host      | User     | ...
+-----------+----------+-
| %         | root     | ...
| %         | jeffrey  | ...
| localhost | root     | ...
| localhost |          | ...
+-----------+----------+-

サーバーがこのテーブルを読むと、Host に値が最も確実に特定できる ホストを指定しているエントリを、最初に参照します。 (Host 項の '%' は ``すべてのホスト'' を意味し、 ホスト名をはっきりと特定しているものではありません) Host の値が同じエントリがあった場合、もっとも明確に User の値が ユーザーを指定しているエントリを最初に参照します。 (User の値が空の場合、``だれでも'' を意味します) この結果、user テーブルは以下のようにソートされます:

+-----------+----------+-
| Host      | User     | ...
+-----------+----------+-
| localhost | root     | ...
| localhost |          | ...
| %         | jeffrey  | ...
| %         | root     | ...
+-----------+----------+-

接続が試みられた場合、サーバーは並び換えられた登録を探し、最初に見つけたものを 使用します。 'localhost'jeffrey からの接続は、まず最初に Hostlocalhost を設定しているエントリにマッチします。 ユーザー名が空のエントリは、ホスト名とユーザー名の両方を指定した接続にもマッチします。 ( '%'/'jeffrey' エントリもマッチします。が、これは最初にはマッチしません。)

もう一例。user が以下の設定と仮定します:

+----------------+----------+-
| Host           | User     | ...
+----------------+----------+-
| %              | jeffrey  | ...
| thomas.loc.gov |          | ...
+----------------+----------+-

これは次のようにソートされます:

+----------------+----------+-
| Host           | User     | ...
+----------------+----------+-
| thomas.loc.gov |          | ...
| %              | jeffrey  | ...
+----------------+----------+-

thomas.loc.govjeffrey からの接続は、最初のエントリにマッチし、 whitehouse.govjeffrey からの接続は、二つ目のエントリにマッチします。

よくある考え違いは、ユーザー名を与えて接続した場合、 サーバーが接続にマッチするものを探す際に、 そのユーザー名が指定されているルールが 最初に使用されるだろうと考えることです。これは正しくありません。 前の例でこれを示しましたが、thomas.loc.govjeffrey からの接続が 最初にマッチするのは、 User フィールドの値が 'jeffrey' に なっているエントリではなく、ユーザー名なし(=だれでも) のエントリの方が 先にマッチします!

もしサーバーへの接続がうまく行かない場合、 user テーブルを表示し、 マニュアルでソートしてみて、どのエントリに最初にマッチするか探してください。

If connection was successful, but your privileges are not what you expected you may use CURRENT_USER() function (new in version 4.0.6) to see what user/host combination your connection actually matched. See section その他の関数.

Access Control, Stage 2: Request Verification

一度接続か確立されると、サーバーはステージ2に移ります。 このステージでは、サーバーはこの接続から来るそれぞれの要求が許可されて いるかどうかをチェックします。 チェックは実行しようとしている操作のタイプにより行います。 その操作が許可テーブルのどの権限フィールドに当てはまるかを見ます。 これら権限は user, db,host, tables_privcolumns_priv テーブルより導出されます。 権限テーブルは GRANT, REVOKE コマンドで操作します。 See section GRANTREVOKE 構文. (You may find it helpful to refer to section 特権システムはどのように動くか?, which lists the fields present in each of the grant tables.)

user テーブルは全てに対して基本となる権限をユーザーに割り当てます。 たとえカレントのデータベースに許可を与えていなくても、user テーブルの設定方が有効になります。 例えば、user テーブルで DELETE を許可した場合、 サーバーにあるどんなデータベースの行も削除できるのです! いうならば、user テーブルの権限はスーパーユーザーの権限と言ってもいいでしょう。 この権限はスーパーユーザー(サーバーやデーターベース管理者)のみに与えておく事が賢明です。 他のユーザーは、user テーブルの権限の設定を 'N' のままにしておくべきですし、 また、db テーブルと host テーブルを利用して、 データベースを指定した上でユーザーに権限を許可すべきです。

db テーブルと host テーブルは特定のデータベースに対する権限許可を行います。 スコープフィールドの値は次のように記述されます:

サーバー起動時に、db テーブルと host テーブルはサーバーに読み込まれます。 (user テーブルもこの時に同時に読まれます) db テーブルは Host, Db, User のフィールドでソートされ、 host テーブルは Host, Db フィールドでソートされます。 user テーブルは、一番特定できるエントリを最初に、一番特定できないものを最後にソートします。 サーバーはソートされたものの中から、最初にマッチしたものを使用します。

tables_privcolumns_priv テーブルは、 特定のテーブルとフィールドに対する権限を許可します。 スコープフィールドの値は、いかにそって記述されます:

tables_privcolumns_priv テーブルは Host, Db, User フィールドで並び換えられます。 これは db テーブルのソートに似ていますが、 Host フィールドだけが ワイルドカードを含むので、ソートはより単純なものになります。

この要求の承認は次のようにして行います。 もしアクセス承認を決定する部分のソースコードを理解できるなら、 ちょっと変わったアルゴリズムで承認の決定を行っている事に気づくでしょう。

管理者の要求(SHUTDOWN, RELOAD, etc.)については、サーバーは user テーブルだけを参照します。(user テーブルだけが管理者権限のフィールドを持つ)。 エントリに許可登録されている操作は受け入れられ、それ以外は拒否されます。 例えば、mysqladmin shutdown を実行しようとしても、 user テーブルの SHUTDOWN 権限が許されていなければ実行できません。 この時、dbhost テーブルはチェックされません。 (これらのテーブルには Shutdown_priv フィールドが無いからです)

データベースへの要求 (INSERT, UPDATE, etc.) において、 サーバーはまず最初に、ユーザーのグローバルな権限(スーパーユーザー)を user の中から探しだします。 もし許可が与えられていれば、アクセスは成功します。

user テーブルのグローバルな権限の設定が不十分であるなら、 サーバーはユーザーのデータベースに対する権限を db テーブルと host テーブルから決定します:

  1. サーバーは db テーブルの Host,Db,Userフィールドを参照します。 HostUser フィールドはユーザーの接続時のホスト名と MySQL ユーザー名にマッチします。 Db フィールドはユーザーがアクセスしたいデータベース名にマッチします。 HostUser にマッチするものが無かった場合、アクセスは拒否されます。
  2. db テーブル内の Host フィールドが空でないエントリにマッチした場合、 ユーザーの指定されているデータベースに対する権限が定義されます。
  3. Host フィールドが空値の db テーブルのエントリにマッチした場合、 どのホストがそのデータベースへアクセスできるかを host テーブルから探し出します。 この場合、host テーブル の Host, Db フィールドとマッチするものを探し出します。 host テーブルにエントリがなかった場合、アクセスは拒否されます。 もしマッチすると、ユーザーの特定データベースに対する権限は、 host テーブルと db テーブル両方にまたがった権限から割り出されます。 いうならば両方とも 'Y' である権限。 (この方法を使用すると、まず db テーブルのエントリに大まかな権限を設定しておき、 それから host テーブルのエントリを使用して、ホスト情報もとに権限を限定していくという事ができます)

特定データベースに対する権限が db テーブルと host テーブルのエントリから決定された後、 サーバーはその割り出された権限に対し、user テーブルて設定されている権限を加えます。 この結果から得られた権限にマッチした要求は受け入れられます。 そうでなければ、サーバーはユーザーのテーブル、フィールドに対する許可を、 tables_privcolumns_priv 内に探します。 アクセスはこの結果により、許可、拒否されます。

先のユーザーの権限が計算される方法の記述は、boolean 表記で示すならば、 以下のようになるでしょう:

global privileges
OR (database privileges AND host privileges)
OR table privileges
OR column privileges

これは少し分かりにくいかもしれません。もしグローバルの user エントリ 権限許可が、リクエストされたオペレーションには不十分だと最初に分かった際、 サーバーがこれらの権限を database-, table-, column-固有の権限の 後に、なぜ、追加してしまうのか。 その理由は、リクエストが1個以上の権限を要求するだろうということです。 例えば、もしあなたが INSERT ... SELECT 構文を実行するなら、 あなたには INSERTSELECT 権限が必要です。 あなたの権限が、 user テーブルエントリで一つの権限が許可され、 db テーブルで、そのほかの権限が許可されていたとします。 この場合、あなたは、そのリクエストを実行するために、必要な権限を持っています。 しかし、サーバーはどちらのテーブル、それ単体からでは、権限を得ることが出来ません。 権限は、両方のエントリーを合わせなくてはならないのです。

host テーブルは ``安全な'' ホストのリストを維持するために使用できます。

TcX では、host テーブルにはローカルネット上の全てのホストが登録されています。 これらのホストは全ての権限が許可されています。

逆に host table で安全ではないホストを指定することもできます。 public.your.domain というマシンが安全ではない、公開されている場所にあるとします。 その場合以下のようにして、その公開マシン以外のネットワーク上のホストに対して、 アクセスを許可することができます:

+--------------------+----+-
| Host               | Db | ...
+--------------------+----+-
| public.your.domain | %  | ... (all privileges set to 'N')
| %.your.domain      | %  | ... (all privileges set to 'Y')
+--------------------+----+-

権限のテーブル設定は、あなたの思い通りに許可が得られるのか、 常に(mysqlaccess等を使用して)チェックすべきです。

何故 Access denied エラーになるのか

もし、MySQL サーバーに接続しようとして Access denied エラーに 遭遇してしまったら、以下に記すことが問題の解決のための指標となるでしょう:

MySQL User Account Management

GRANTREVOKE 構文

GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON {tbl_name | * | *.* | db_name.*}
    TO user_name [IDENTIFIED BY [PASSWORD] 'password']
        [, user_name [IDENTIFIED BY 'password'] ...]
    [REQUIRE
        NONE |
    	[{SSL| X509}]
	[CIPHER cipher [AND]]
	[ISSUER issuer [AND]]
	[SUBJECT subject]]
    [WITH [GRANT OPTION | MAX_QUERIES_PER_HOUR # |
                          MAX_UPDATES_PER_HOUR # |
                          MAX_CONNECTIONS_PER_HOUR #]]

REVOKE priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON {tbl_name | * | *.* | db_name.*}
    FROM user_name [, user_name ...]

バージョン 4.0 以上:
    REQUIRE
    	[{SSL| X509}]
	[CIPHER cipher [AND]]
	[ISSUER issuer [AND]]
	[SUBJECT subject]

バージョン 4.0.2以上:
    MAX_QUERIES_PER_HOUR=# | MAX_UPDATES_PER_HOUR=# | MAX_CONNECTIONS_PER_HOUR=#

GRANT は MySQL 3.22.11 以上で実装されています; 前の MySQL バージョンでは、GRANT ステートメントは何も行ないません。

GRANTREVOKE コマンドセットの主な目的は、システム管理者 がユーザを生成すること、MySQL ユーザに次の4つの権限レベルの権 利を与えたり取り消すことをできるようにすることです:

Global レベル
Global 権限は与えられたサーバ上の全てのデータベースに適用します。これらの権限は mysql.user テーブル内に格納されます。
Database レベル
Database 権限は与えられたデータベース内の全てのテーブルに適用します。こ れらの権限は mysql.db テーブルと mysql.host テーブル内に格納されます。
Table レベル
Table 権限は与えられたテーブル内の全てのフィールドに適用します。これらの権限は mysql.tables_priv テーブル内に格納されます。
Column レベル
Column 権限は与えられたテーブル内の一つのフィールドに適用します。これらの権限は mysql.columns_priv テーブル内に格納されます。

If you give a grant for a users that doesn't exists, that user is created. For examples of how GRANT works, see section 新しいユーザを MySQL へ追加.

GRANTREVOKE ステートメントにおいて priv_type には 以下が指定できます:

ALL [PRIVILEGES] Sets all simple privileges except WITH GRANT OPTION
ALTER Allows usage of ALTER TABLE
CREATE Allows usage of CREATE TABLE
CREATE TEMPORARY TABLES Allows usage of CREATE TEMPORARY TABLE
DELETE Allows usage of DELETE
DROP Allows usage of DROP TABLE.
EXECUTE Allows the user to run stored procedures (for MySQL 5.0)
FILE Allows usage of SELECT ... INTO OUTFILE and LOAD DATA INFILE.
INDEX Allows usage of CREATE INDEX and DROP INDEX
INSERT Allows usage of INSERT
LOCK TABLES Allows usage of LOCK TABLES on tables for which one has the SELECT privilege.
PROCESS Allows usage of SHOW FULL PROCESSLIST
REFERENCES For the future
RELOAD Allows usage of FLUSH
REPLICATION CLIENT Gives the right to the user to ask where the slaves/masters are.
REPLICATION SLAVE Needed for the replication slaves (to read binlogs from master).
SELECT Allows usage of SELECT
SHOW DATABASES SHOW DATABASES shows all databases.
SHUTDOWN Allows usage of mysqladmin shutdown
SUPER Allows one connect (once) even if max_connections is reached and execute commands CHANGE MASTER, KILL thread, mysqladmin debug, PURGE MASTER LOGS and SET GLOBAL
UPDATE Allows usage of UPDATE
USAGE Synonym for ``no privileges.''
GRANT OPTION Synonym for WITH GRANT OPTION

USAGE は ``no privileges'' と同義です. これはなんの権限も持たないユーザーを作る場合に使用します.

The privileges CREATE TEMPORARY TABLES, EXECUTE, LOCK TABLES, REPLICATION ..., SHOW DATABASES and SUPER are new for in version 4.0.2. To use these new privileges after upgrading to 4.0.2, you have to run the mysql_fix_privilege_tables script.

In older MySQL versions(4.0.2未満), the PROCESS privilege gives the same rights as the new SUPER privilege.

ユーザーから GRANT 権限を取り除くには、GRANT OPTION オプションの値に priv_type を指定します:

mysql> REVOKE GRANT OPTION ON ... FROM ...;

テーブルに対する許可のために指定できる priv_type は次のフィールドだけです: SELECT,INSERT, UPDATE, DELETE, CREATE, DROP, GRANT OPTION, INDEX, ALTER.

フィールドに対する許可のために指定できる priv_type は次のフィールドだけです (これは column_list 節を使用する場合に適用されます): SELECT, INSERT, UPDATE.

ON *.* を使用してグローバル権限を設定できます。 ON db_name.* を使用してデータベース権限を設定できます。ON * を 指定すると、現在のデータベースの権限を設定できます。 (警告: 現在のデータベースを持たない状態で ON * を指定した場合、 global 権限に影響します!)

Please note: the `_' and `%' wildcards are allowed when specifying database names in GRANT commands. This means that if you wish to use for instance a `_' character as part of a database name, you should specify it as `\_' in the GRANT command, to prevent the user from being able to access additional databases matching the wildcard pattern, e.g., GRANT ... ON `foo\_bar`.* TO ....

ユーザへの権利の供与を他のホストから適応するために、MySQL は user_name の値を user@host の形で書けるようにしています。 特殊文字(`%' のような)で user_name の値を指定したい場合、 ユーザやホスト名をクォートできます; (例えば 'test-user'@'test-hostname')。

ホスト名にワイルドカードを使用できます。例えば、user@'%.loc.gov'loc.gov ドメインの全てのホストの user を与え、 user@'144.155.166.%'144.155.166 クラスCサブネットの あらゆるホストの user となります。

単に user と書くと user@"%" と同じです.

MySQL doesn't support wildcards in user names. Anonymous users are defined by inserting entries with User='' into the mysql.user table or creating an user with an empty name with the GRANT command.

注意: もし匿名ユーザーからの MySQL サーバーへの接続を 許す場合(デフォルトです)、全てのローカルユーザー username@localhost を加えるべきです。 なぜなら、匿名ユーザーは同じマシンから MySQL サーバーに入ろうとした場合に 使用されるからです! (匿名ユーザーは mysql.user ユーザーテーブルに、 User='' として登録されています。)

これを確認するには、以下のようにします:

mysql> SELECT Host,User FROM mysql.user WHERE User='';

さしあたり, GRANT はホスト名、テーブル名、データベース名、フィールド名に 最大60文字まで使用できます。ユーザー名は最大16文字までです。

テーブル/フィールドの権限は global(ユーザとデータベース)権限と GRANT 権限と OR されます。例えば、ユーザが mysql.user テーブル内の global SELECT 権限を持っている場合、 これはデータベースやテーブル/フィールドレベル内のエントリでは拒否できません。

フィールドに対する権限は次のように計算できます:

global privileges
OR (database privileges AND host privileges)
OR table privileges
OR column privileges

多くの場合、異なる権限レベルの一つでユーザに権利を与えるので、人生は通常 上述のようには複雑ではありません。 アクセス権限のチェックの詳細は→section General Security Issues and the MySQL Access Privilege System.

ユーザとホスト名の組が存在しない場合、エントリは mysql.user テー ブルに追加され、DELETE コマンドで削除されるまでそこに残ります。 いうならば GRANTuser テーブルの登録を作りますが、 REVOKE はそれらを削除できません; そうするには DELETE を使用しなくてはなりません。

MySQL バージョン 3.22.12 以上では、 新しいユーザーが作成された場合、あるいは、あなたがグローバルな権限を許可されている場合、 ユーザーのパスワードは IDENTIFIED BY 節を使用して設定できます。 すでにユーザーにパスワードがある場合、新しく設定されたパスワードに置き換えられます。

If you don't want to send the password in clear text you can use the PASSWORD option followed by a scrambled password from SQL function PASSWORD() or the C API function make_scrambled_password(char *to, const char *password).

警告: もし新しいユーザーを作っても IDENTIFIED BY 節を指定しなければ、 そのユーザーはノーパスワードです。 これは危険です。

パスワードは SET PASSWORD コマンドでも設定できます。 See section SET 構文.

データベースに権限を付与 する場合、mysql.db テーブル内の エントリは必要な場合に生成されます。全てのデータベース権限が REVOKE で削除された時、このエントリは削除されます。

ユーザがテーブルに何も権限を持っていない場合、テーブルの一覧要求時(例え ば、SHOW TABLES ステートメントで)には、テーブルは現れません。

WITH GRANT OPTION 節は、他のユーザーに、自分が持っている権限を与えることができます。 GRANT 権限を他に与える場合は注意してください。 あなたと許可を与えるユーザーが違う権限を持っている場合、 与えられる権限の許可は、二つを合わせた物になります!

MAX_QUERIES_PER_HOUR #, MAX_UPDATES_PER_HOUR # and MAX_CONNECTIONS_PER_HOUR # are new in MySQL version 4.0.2. These options limit the number of queries/updates and logins the user can do during one hour. If # is 0 (default), then this means that there are no limitations for that user. See section Limiting user resources. Note: to specify any of these options for an existing user without adding other additional privileges, use GRANT USAGE ... WITH MAX_....

自分自身が持っていない権限を他のユーザーに与えることはできません; GRANT 権限はあなたが所有する権限の許可だけを与えることができます。

Be aware that when you grant a user the GRANT privilege at a particular privilege level, any privileges the user already possesses (or is given in the future!) at that level are also grantable by that user. あなたがデータベースに対する INSERT 許可をあるユーザーに与えたと仮定します。 もし、データベースに対する SELECT 権限を与えたり、 WITH GRANT OPTION を行うと、ユーザーは SELECT 権限だけでなく INSERT も得ることになります。 もし UPDATE 権限をユーザーに与えると、そのユーザーは INSERT, SELECT, UPDATE が可能です。

ALTER 権限を一般ユーザに与えるべきではありません。この場合 ユーザはテーブルをリネームでき、この方法で権限を回ることを試みることがで きます!

注意:もし table/column 権限を一人のユーザーにだけ与えた場合、 MySQL は全てのユーザーに対してテーブルとフィールドの承認権限を検討します。 これは MySQL を少し遅くします。

mysqld 開始時、全ての権限はメモリに読み込まれます。データベース、 テーブル、フィールド権限は一度効果を得ます。ユーザレベル権限はユーザ再接続時に 効果を得ます。 これらの許可テーブルを GRANTREVOKE を使って変更しても サーバーにはすぐに反映されません。 もしこれらの許可テーブルを手動で変更した場合(INSERT, UPDATE, 等で変更した場合)、 FLUSH PRIVILEGES 構文を実行するか、mysqladmin flush-privileges を実行して サーバーに許可テーブルの再読み込みを行わせなくてはなりません。 See section いつ権限の変更が反映されるか.

The biggest differences between the ANSI SQL and MySQL versions of GRANT are:

For a description of using REQUIRE, see section Using Secure Connections.

MySQL ユーザ名とパスワード

MySQL によって使用されるユーザー名とパスワードの使用のされ方と、 Unix, Windows で使用される方法とは、いくつか異なる点があります。

MySQL ユーザーと彼らの権限は通常 GRANT コマンドで作成されます。 See section GRANTREVOKE 構文.

MySQL サーバにコマンドラインクライアントでログインする時、 --password=your-password でパスワードを指定すべきです。 See section MySQL サーバーに接続.

mysql --user=monty --password=guess database_name

クライアントにパスワードをプロンプトして欲しければ、引数なしで --password を使用すべきです。

mysql --user=monty --password database_name

または次の短い形式:

mysql -u monty -p database_name

注意: 最後の例でのパスワードは 'database_name' では ありません

パスワードを供給するために -p オプションを使用したい場合、次のようなことを 行なうべきです:

mysql -u monty -pguess database_name

いくつかのシステムでは、MySQL がパスワードをプロンプトするために 使用するライブラリ呼び出しは、自動的にパスワードを 8文字にカットします。内 部的に MySQL はパスワード長に何の制限もありません。

いつ権限の変更が反映されるか

mysqld の起動時、全ての許可テーブルはメモリーに読み込まれ、 この時点で有効になります。

GRANT, REVOKE, SET PASSWORD を使用して許可テーブルを 変更した場合、直にサーバに通知されます。

もし手動で許可テーブルを変更した場合(INSERT, UPDATE などで)、 FLUSH PRIVILEGES 構文か mysqladmin flush-privileges コマンド か mysqladmin reload コマンドを実行して、 サーバーに許可テーブルの読み込みを指示しなければなりません。 そうしなければ、サーバーを再起動させるまで、変更は反映されません。 権限テーブルを手で変更して、権限のリロードを忘れた場合、変更が何も行なわれ ないように見えるのがなぜかと不思議に思うでしょう!

サーバーが許可テーブルの変更を通知した場合、既に接続している クライアントは、以下のような影響を受けます:

MySQL 権限許可の初期設定

MySQL インストール後、scripts/mysql_install_db を 実行して権限のアクセス許可を初期化します。 See section 素早いインストールの概要. mysql_install_db スクリプトは mysqld サーバーを起動し、 以下のように権限を初期化してテーブルに登録します:

注意: デフォルトの権限は Windows では違います。 See section Windows 上で MySQL を実行.

初期インストールの状態ではかなりアクセスが解放されているので、 インストール後最初にすることは、MySQL root ユーザーにパスワードを設定することです。 以下のようにします(パスワードは PASSWORD() 関数を使用することをお忘れなく):

shell> mysql -u root mysql
mysql> SET PASSWORD FOR root@localhost=PASSWORD('new_password');

If you know what you are doing, you can also directly manipulate the privilege tables:

shell> mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('new_password')
    ->     WHERE user='root';
mysql> FLUSH PRIVILEGES;

password をセットする他の方法として、mysqladmin コマンドも使用できます:

shell> mysqladmin -u root password new_password

mysql データベースに書き込み/更新アクセスのあるユーザだけが他のユーザのパ スワードを変更できます。すべての通常のユーザ(匿名ユーザ以外)は、上記のコマ ンドか、または SET PASSWORD=PASSWORD('new password') で、自分のパス ワードだけを変更できます。

もし最初の方法で user テーブルのパスワードを直接更新したなら、 サーバーに許可テーブルの再読み込みを行わせなければなりません(FLUSH PRIVILEGES を使用して)。

一度 root のパスワードを設定したなら、root でサーバーに接続する場合は 常にパスワードを与えなければなりません。

追加設定やテストをしているためパスワードを入れたくない場合、 root パスワードをブランクのままにしておこうと考えるかも知れませんが、 実稼働させる前には必ず設定してください。

どのようにデフォルトの権限を設定しているか、scripts/mysql_install_db 見てみてください。 これは他のユーザーを設定するときに使えるでしょう。

もし権限の初期状態を違うものにして初期化したいなら、 mysql_install_db を実行する前に編集してもよいでしょう。

もしテーブルを完全に作り直したいなら、mysql データベースのディレクトリに存在する 全ての `*.frm', `*.MYI', `*.MYD' ファイルを削除します。 (このディレクトリーはデータベースディレクトリーの下に mysql という名前で存在します。 mysqld --help とすればデータベースのディレクトリーが表示されます。) そして好みの許可状態に mysql_install_db を編集してから実行します。

注意: MySQL 3.22.10 以前のバージョンでは, `*.frm' ファイルを消してはいけません. もしうっかり消してしまった場合、 mysql_install_db を実行する前に、 MySQL 配布からコピーしなおさ なくてはなりません。

新しいユーザを MySQL へ追加

ユーザーは2つの違った方法で追加できます: GRANT 構文を使用して行う方法と、 MySQL の許可テーブルを直接操作する方法とです。 The preferred method is to use GRANT statements, because they are more concise and less error-prone. See section GRANTREVOKE 構文.

phpmyadmin のような、ユーザの作成と管理に使用できる contribute され たプログラムも多くあります。

以下の例では、いかにして mysql クライアントを使用して新規にユーザーを登録するかを示します。 以下の例では、権限は前節で述べたデフォルト値になっているとします。 よって変更を行うためには、あなたは mysqld が走っているマシン上にログインしていなくてはなりませんし、 かつ、MySQL root ユーザーで接続していなければなりません。 さらに MySQL root ユーザーには mysql データベースに対して INSERT 権限を持ち、 RELOAD, PROCESS のアドミニストレーター権限を持っていなければなりません。 もし root ユーザーのパスワードを変えていたならば、 mysql コマンドにパスワード指定を与えなくてはなりません。

You can add new users by issuing GRANT statements:

shell> mysql --user=root mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO monty@localhost
    ->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql> GRANT ALL PRIVILEGES ON *.* TO monty@"%"
    ->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql> GRANT RELOAD,PROCESS ON *.* TO admin@localhost;
mysql> GRANT USAGE ON *.* TO dummy@localhost;

これら GRANT 構文では3つの新しいユーザを作ります:

monty
どこからでもサーバーに接続できる完全なスーパーユーザ。 しかし、MySQL を使用する時にはパスワード 'some_pass' を 使用する必要があります。 monty@localhostmonty@"%" の両方に GRANT 構文を 発行しなくてはならない事に注意してください。 もし localhost からの許可をした登録がないと、localhost から接続した時、 mysql_install_db が自動で作成した localhost への匿名ユーザーが優先されます。 なぜなら、 Host フィールドの値が(ブランクやワールドカード以外に)明記されており、 許可登録が MySQL 内部でソートされる時に順番が上にソートされるからです。
admin
localhost からパスワードなしで接続できますが、reload, process の使用だけが許されます。 これは、mysqladmin reload, mysqladmin refresh, mysqladmin flush-* そして mysqladmin processlist コマンドの実行がこのユーザーに許可されます。 データベースへのアクセスは許可されていません。 しかしこれは後でテーブル GRANT 構文を発行すれば、 個々のデータベースへのアクセス権限が設定できます。
dummy
パスワードなしで localhost からのみ、接続できるユーザー。 グローバルな権限は全て 'N' に設定されます。 USAGE 権限は権限無しユーザーの設定を許可する事になります。 これは、特定データーベースに対しての許可を後から与える事を想定しています。

同じアクセス許可を INSERT 構文を使用して直接設定できます。 サーバーに許可テーブルの再読み込みを指示します:

shell> mysql --user=root mysql
mysql> INSERT INTO user VALUES('localhost','monty',PASSWORD('some_pass'),
    ->          'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user VALUES('%','monty',PASSWORD('some_pass'),
    ->          'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user SET Host='localhost',User='admin',
    ->           Reload_priv='Y', Process_priv='Y';
mysql> INSERT INTO user (Host,User,Password)
    ->                  VALUES('localhost','dummy','');
mysql> FLUSH PRIVILEGES;

MySQL のバージョンにより、上の 'Y' の数が違う事に注意してください。 (3.22.11 以前のバージョンでは項目数が少なくなります). admin ユーザーの登録で使用している INSERT の拡張は バージョン 3.22.11 以上で可能です。 (訳注: version 4.0 以上で openssl を使用する場合、この数が変わります)

スーパーユーザーを定義するためには、user テーブルの許可フィールドを 'Y' にするだけでかまいません。 dbhost テーブルに登録は必要無いのです。

user テーブルの許可フィールドは最後の INSERT 文で(dummy ユーザーのために) は設定されていません。これらのフィールドはデフォルト値の 'N' になります。 これは GRANT USAGE が行うのと同じものです。

以下は、localhost, server.domain, whitehouse.gov から接続が可能な custom ユーザーの追加例です。 custom ユーザーは bankaccount データーベースには localhost からの接続のみを許可され、 expenses データベースには whitehouse.gov からのみ接続が許可され、 customer データベースには全てのホストから接続できます。 custom ユーザーは、 stupid というパスワードを全てのホストで使用したいとします。

このユーザーの許可を GRANT 構文で定義するには、以下のようにします:

shell> mysql --user=root mysql
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON bankaccount.*
    ->     TO custom@localhost
    ->     IDENTIFIED BY 'stupid';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON expenses.*
    ->     TO custom@whitehouse.gov
    ->     IDENTIFIED BY 'stupid';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON customer.*
    ->     TO custom@'%'
    ->     IDENTIFIED BY 'stupid';

The reason that we do to grant statements for the user 'custom' is that we want the give the user access to MySQL both from the local machine with Unix sockets and from the remote machine 'whitehouse.gov' over TCP/IP.

許可テーブルを直接変更してこのユーザーの権限を設定するにはいかのようにします (FLUSH PRIVILEGES を最後に実行している事に注意):

shell> mysql --user=root mysql
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('localhost','custom',PASSWORD('stupid'));
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('server.domain','custom',PASSWORD('stupid'));
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('whitehouse.gov','custom',PASSWORD('stupid'));
mysql> INSERT INTO db
    -> (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
    ->  Create_priv,Drop_priv)
    -> VALUES
    -> ('localhost','bankaccount','custom','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
    -> (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
    ->  Create_priv,Drop_priv)
    -> VALUES
    -> ('whitehouse.gov','expenses','custom','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
    -> (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
    ->  Create_priv,Drop_priv)
    -> VALUES('%','customer','custom','Y','Y','Y','Y','Y','Y');
mysql> FLUSH PRIVILEGES;

最初の3つの INSERT 文は、 custom ユーザーがそれぞれのホストから パスワードつきで接続できるように user テーブルに追加しています。 しかしここでは権限は1つも与えられていません(権限のデフォルト値は 'N' です)。 次の三つの INSERT 文は、bankaccount, expenses, customer データベースに対する該当ホストからのアクセス許可を custom ユーザーに与えるように、 db テーブルに追加しています。 許可テーブルが直接変更された場合、これらをサーバーに反映させるために、許可テーブルの 再読み込みを(FLUSH PRIVILEGESで) サーバーにつげなければなりません。

もし、あるドメインの全てのマシンに接続を許可したい場合、 以下のように GRANT 構文を発行します:

mysql> GRANT ...
    ->     ON *.*
    ->     TO myusername@"%.mydomainname.com"
    ->     IDENTIFIED BY 'mypassword';

許可テーブルを直接変更するには以下のようにします:

mysql> INSERT INTO user VALUES ('%.mydomainname.com', 'myusername',
    ->             PASSWORD('mypassword'),...);
mysql> FLUSH PRIVILEGES;

Limiting user resources

Starting from MySQL 4.0.2 one can limit certain resources per user.

So far, the only available method of limiting usage of MySQL server resources has been setting the max_user_connections startup variable to a non-zero value. But this method is strictly global and does not allow for management of individual users, which could be of particular interest to Internet Service Providers.

Therefore, management of three resources is introduced on the individual user level:

A user in the aforementioned context is a single entry in the user table, which is uniquely identified by its user and host columns.

All users are by default not limited in using the above resources, unless the limits are granted to them. These limits can be granted only via global GRANT (*.*), using this syntax:

GRANT ... WITH MAX_QUERIES_PER_HOUR N1
               MAX_UPDATES_PER_HOUR N2
               MAX_CONNECTIONS_PER_HOUR N3;

One can specify any combination of the above resources. N1, N2 and N3 are integers and stands for count / hour.

If user reaches any of the above limits withing one hour, his connection will be terminated or refused and the appropriate error message shall be issued.

Current usage values for a particular user can be flushed (set to zero) by issuing a GRANT statement with any of the above clauses, including a GRANT statement with the current values.

Also, current values for all users will be flushed if privileges are reloaded (in the server or using mysqladmin reload) or if the FLUSH USER_RESOURCES command is issued.

The feature is enabled as soon as a single user is granted with any of the limiting GRANT clauses.

As a prerequisite for enabling this feature, the user table in the mysql database must contain the additional columns, as defined in the table creation scripts mysql_install_db and mysql_install_db.sh in `scripts' subdirectory.

パスワードの設定法

多くの場合、ユーザ/パスワードを設定するために、GRANT を使用すべき です。以下は上級ユーザのためにだけあてはまります。 See section GRANTREVOKE 構文.

前節の例で述べた、とても重要な基本原則: INSERTUPDATE で空ではないパスワードを設定する場合、 暗号化するために PASSWORD() 関数を使用しなくてはなりません。 これは user テーブルはプレーンテキストでなく、暗号化されたパスワードであることを要求しているからです。 この原則を忘れてしまった場合、以下のようにしてパスワードをセットしてしまうかもしれません:

shell> mysql -u root mysql
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('%','jeffrey','biscuit');
mysql> FLUSH PRIVILEGES;

これは user テーブルにプレーンテキストの 'biscuit' をパスワードとして登録してしまいます。 jeffrey ユーザーでこのパスワードを使用してサーバーに接続しようとすると、 mysql クライアントは暗号化したパスワードをサーバーに送ります。 サーバーは暗号化されたパスワード('biscuit' ではありません) と user テーブルに登録された値('biscuit') を比較します。 その結果、比較は失敗し、サーバーは接続を拒否します:

shell> mysql -u jeffrey -pbiscuit test
Access denied

user テーブルに登録されるパスワードは暗号化されたものでなくてはなりません。 INSERT 構文は以下のようにして使用しなくてはなりません:

mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('%','jeffrey',PASSWORD('biscuit'));

SET PASSWORD 構文を使用する場合は、以下のように PASSWORD() 関数を使用しなくてはなりません:

mysql> SET PASSWORD FOR jeffrey@"%" = PASSWORD('biscuit');

もし GRANT ... IDENTIFIED BY 構文や mysqladmin password コマンド でパスワードを設定した場合、PASSWORD() 関数は必要ありません。 両方とも、パスワードを暗号化してくれますので、 以下のように'biscuit'と与えます:

mysql> GRANT USAGE ON *.* TO jeffrey@"%" IDENTIFIED BY 'biscuit';

or

shell> mysqladmin -u jeffrey password biscuit

注意PASSWORD() は UNIX のパスワードで使用されている暗号化と 違うことにも留意してください。 See section MySQL ユーザ名とパスワード.

パスワードを安全にする

自分のパスワードを他人にさらけ出すのは勧められることではありません。 それぞれの方法に於ける危険度に応じ、以下に示す方法でクライアントプログラムに あなたのパスワードをあたえて走らせることができます:

まとめると、より安全な方法は、 パスワードプロンプトを返すクライアントプログラムを実行するか、 適切なパーミッションをかけた `.my.cnf' ファイルにパスワードを書くか です。

Using Secure Connections

Basics

Beginning with version 4.0.0, MySQL has support for SSL encrypted connections. To understand how MySQL uses SSL, it's necessary to explain some basic SSL and X509 concepts. People who are already familiar with them can skip this part.

By default, MySQL uses unencrypted connections between the client and the server. This means that someone could watch all your traffic and look at the data being sent or received. They could even change the data while it is in transit between client and server. Sometimes you need to move information over public networks in a secure fashion; in such cases, using an unencrypted connection is unacceptable.

SSL is a protocol that uses different encryption algorithms to ensure that data received over a public network can be trusted. It has mechanisms to detect any change, loss or replay of data. SSL also incorporates algorithms to recognise and provide identity verification using the X509 standard.

Encryption is the way to make any kind of data unreadable. In fact, today's practice requires many additional security elements from encryption algorithms. They should resist many kind of known attacks like just messing with the order of encrypted messages or replaying data twice.

X509 is a standard that makes it possible to identify someone on the Internet. It is most commonly used in e-commerce applications. In basic terms, there should be some company (called a ``Certificate Authority'') that assigns electronic certificates to anyone who needs them. Certificates rely on asymmetric encryption algorithms that have two encryption keys (a public key and a secret key). A certificate owner can prove his identity by showing his certificate to other party. A certificate consists of its owner's public key. Any data encrypted with this public key can be decrypted only using the corresponding secret key, which is held by the owner of the certificate.

MySQL doesn't use encrypted connections by default, because doing so would make the client/server protocol much slower. Any kind of additional functionality requires the computer to do additional work and encrypting data is a CPU-intensive operation that requires time and can delay MySQL main tasks. By default MySQL is tuned to be fast as possible.

If you need more information about SSL, X509, or encryption, you should use your favourite Internet search engine and search for keywords in which you are interested.

Requirements

To get secure connections to work with MySQL you must do the following:

  1. OpenSSL ライブラリをインストール。 我々は openssl 0.9.6 でテストしました。 http://www.openssl.org/.
  2. --with-vio --with-openssl で MySQL をコンフィギャ.
  3. もしあなたが古い MySQL (4.0未満)をインストールしているなら、 mysql.user テーブルを update するべきです。 これは mysql_fix_privilege_tables スクリプトで可能です。 MySQL 4.0.0 以上ではこの作業が必要です。 ( 訳注: このスクリプトは、前のバージョンが 3.23 の場合、 mysql.user テーブル に ssl_type, ssl_cipher, x509_issuer, x509_subject フィールドを追加し、 mysql.* の全てのテーブルを ALTER TABLE .. TYPE=MyISAM で作成し直します。 実行前には、念のため、mysql データベースを mysqldump か 他の方法でバックアップしておきましょう。 )
  4. 実行中の mysqld が OpenSSL をサポートしている場合は、 SHOW VARIABLES LIKE 'have_openssl'YES を返します。

Setting Up SSL Certificates for MySQL

Here is an example for setting up SSL certificates for MySQL:

DIR=`pwd`/openssl
PRIV=$DIR/private

mkdir $DIR $PRIV $DIR/newcerts
cp /usr/share/ssl/openssl.cnf $DIR
replace ./demoCA $DIR -- $DIR/openssl.cnf

# Create necessary files: $database, $serial and $new_certs_dir 
# directory (optional)

touch $DIR/index.txt
echo "01" > $DIR/serial

#
# Generation of Certificate Authority(CA)
#

openssl req -new -x509 -keyout $PRIV/cakey.pem -out $DIR/cacert.pem \
    -config $DIR/openssl.cnf

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Generating a 1024 bit RSA private key
# ................++++++
# .........++++++
# writing new private key to '/home/monty/openssl/private/cakey.pem'
# Enter PEM pass phrase:
# Verifying password - Enter PEM pass phrase:
# -----
# You are about to be asked to enter information that will be incorporated
# into your certificate request.
# What you are about to enter is what is called a Distinguished Name or a DN.
# There are quite a few fields but you can leave some blank
# For some fields there will be a default value,
# If you enter '.', the field will be left blank.
# -----
# Country Name (2 letter code) [AU]:FI
# State or Province Name (full name) [Some-State]:.
# Locality Name (eg, city) []:
# Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB
# Organizational Unit Name (eg, section) []:
# Common Name (eg, YOUR name) []:MySQL admin
# Email Address []:

#
# Create server request and key
#
openssl req -new -keyout $DIR/server-key.pem -out \
    $DIR/server-req.pem -days 3600 -config $DIR/openssl.cnf

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Generating a 1024 bit RSA private key
# ..++++++
# ..........++++++
# writing new private key to '/home/monty/openssl/server-key.pem'
# Enter PEM pass phrase:
# Verifying password - Enter PEM pass phrase:
# -----
# You are about to be asked to enter information that will be incorporated
# into your certificate request.
# What you are about to enter is what is called a Distinguished Name or a DN.
# There are quite a few fields but you can leave some blank
# For some fields there will be a default value,
# If you enter '.', the field will be left blank.
# -----
# Country Name (2 letter code) [AU]:FI
# State or Province Name (full name) [Some-State]:.
# Locality Name (eg, city) []:
# Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB
# Organizational Unit Name (eg, section) []:
# Common Name (eg, YOUR name) []:MySQL server
# Email Address []:
# 
# Please enter the following 'extra' attributes
# to be sent with your certificate request
# A challenge password []:
# An optional company name []:

#
# Remove the passphrase from the key (optional)
#

openssl rsa -in $DIR/server-key.pem -out $DIR/server-key.pem

#
# Sign server cert
#
openssl ca  -policy policy_anything -out $DIR/server-cert.pem \
    -config $DIR/openssl.cnf -infiles $DIR/server-req.pem

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Enter PEM pass phrase:
# Check that the request matches the signature
# Signature ok
# The Subjects Distinguished Name is as follows
# countryName           :PRINTABLE:'FI'
# organizationName      :PRINTABLE:'MySQL AB'
# commonName            :PRINTABLE:'MySQL admin'
# Certificate is to be certified until Sep 13 14:22:46 2003 GMT (365 days)
# Sign the certificate? [y/n]:y
# 
# 
# 1 out of 1 certificate requests certified, commit? [y/n]y
# Write out database with 1 new entries
# Data Base Updated

#
# Create client request and key
#
openssl req -new -keyout $DIR/client-key.pem -out \
    $DIR/client-req.pem -days 3600 -config $DIR/openssl.cnf

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Generating a 1024 bit RSA private key
# .....................................++++++
# .............................................++++++
# writing new private key to '/home/monty/openssl/client-key.pem'
# Enter PEM pass phrase:
# Verifying password - Enter PEM pass phrase:
# -----
# You are about to be asked to enter information that will be incorporated
# into your certificate request.
# What you are about to enter is what is called a Distinguished Name or a DN.
# There are quite a few fields but you can leave some blank
# For some fields there will be a default value,
# If you enter '.', the field will be left blank.
# -----
# Country Name (2 letter code) [AU]:FI
# State or Province Name (full name) [Some-State]:.
# Locality Name (eg, city) []:
# Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB
# Organizational Unit Name (eg, section) []:
# Common Name (eg, YOUR name) []:MySQL user
# Email Address []:
# 
# Please enter the following 'extra' attributes
# to be sent with your certificate request
# A challenge password []:
# An optional company name []:

#
# Remove a passphrase from the key (optional)
#
openssl rsa -in $DIR/client-key.pem -out $DIR/client-key.pem

#
# Sign client cert
#

openssl ca  -policy policy_anything -out $DIR/client-cert.pem \
    -config $DIR/openssl.cnf -infiles $DIR/client-req.pem

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Enter PEM pass phrase:
# Check that the request matches the signature
# Signature ok
# The Subjects Distinguished Name is as follows
# countryName           :PRINTABLE:'FI'
# organizationName      :PRINTABLE:'MySQL AB'
# commonName            :PRINTABLE:'MySQL user'
# Certificate is to be certified until Sep 13 16:45:17 2003 GMT (365 days)
# Sign the certificate? [y/n]:y
# 
# 
# 1 out of 1 certificate requests certified, commit? [y/n]y
# Write out database with 1 new entries
# Data Base Updated

#
# Create a my.cnf file that you can use to test the certificates
#

cnf=""
cnf="$cnf [client]"
cnf="$cnf ssl-ca=$DIR/cacert.pem"
cnf="$cnf ssl-cert=$DIR/client-cert.pem"
cnf="$cnf ssl-key=$DIR/client-key.pem"
cnf="$cnf [mysqld]"
cnf="$cnf ssl-ca=$DIR/cacert.pem"
cnf="$cnf ssl-cert=$DIR/server-cert.pem"
cnf="$cnf ssl-key=$DIR/server-key.pem"
echo $cnf | replace " " '
' > $DIR/my.cnf

#
# To test MySQL

mysqld --defaults-file=$DIR/my.cnf &

mysql --defaults-file=$DIR/my.cnf

You can also test your setup by modifying the above `my.cnf' file to refer to the demo certificates in the mysql-source-dist/SSL direcory.

GRANT オプション

MySQL can check X509 certificate attributes in addition to the normal username/password scheme. All the usual options are still required (username, password, IP address mask, database/table name).

There are different possibilities to limit connections:

Disaster Prevention and Recovery

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

MySQL テーブルはファイルとして格納されるため、バックアップを行 うのは簡単です。矛盾のないバックアップを得るためには、 FLUSH TABLES をおこなって、LOCK TABLES を関連するテーブルで行ってください。See section LOCK TABLES/UNLOCK TABLES 構文. See section FLUSH 構文. 読み込みロックだ けが必要なので、そのテーブルでデータベースディレクトリのファイルのコピー が行われている間も、他のスレッドはクエリを継続できます。 The FLUSH TABLE is needed to ensure that the all active index pages is written to disk before you start the backup.

Starting from 3.23.56 and 4.0.12 BACKUP TABLE will not allow you to overwrite existing files as this would be a security risk.

もし、テーブルを SQL レベルでバックアップしたいのであれば、SELECT INTO OUTFILEBACKUP TABLE を使用できます。 See section BACKUP TABLE 構文 (3.23.25以上).

他の方法は mysqldump プログラムか mysqlhotcopy スクリプト を使用することです。 See section mysqldump, データベースとテーブルから、構造とデータをダンプ. See section mysqlhotcopy, Copying MySQL Databases and Tables.

  1. フルバックアップをとるには:
    shell> mysqldump --tab=/path/to/some/dir --opt --all
    
    or
    
    shell> mysqlhotcopy database /path/to/some/dir
    
    You can also simply copy all table files (`*.frm', `*.MYD', and `*.MYI' files) as long as the server isn't updating anything. The script mysqlhotcopy does use this method.
  2. mysqld を止め、そして --log-update[=file_name] オプションをつけて起動します。 See section 更新ログ. ログファイルは、 mysqldump 実行後に行われたデータベースの変更を 複製するための情報を与えてくれます。

もしリストアをしなければならない場合、まず最初に REPAIR TABLEmyisamchk -r を実行してテーブルの修復を試みてください。 ほとんどの場合、99.9% 修復はできるはずです。 もし myisamchk が失敗した場合、以下のようにします: (this will only work if you have started MySQL with --log-update, see section 更新ログ):

  1. オリジナルの mysqldump バックアップデータをリストアします。
  2. 次のコマンドを実行して、バイナリログ内の更新を再実行します。
    shell> mysqlbinlog hostname-bin.[0-9]* | mysql
    
    更新ログを使用する場合は、次のようにできます:
    shell> ls -1 -t -r hostname.[0-9]* | xargs cat | mysql
    

ls は、全ての更新ログファイルを正しい順で得るために行われます。

SELECT * INTO OUTFILE 'file_name' FROM tbl_name での選択的バックアップと LOAD DATA FROM INFILE 'file_name' REPLACE ... でのリストアを行う こともできます。重複レコードを避けるためには、テーブル内に PRIMARY KEYUNIQUE が必要です。REPLACE は、'重複インデックス' 衝突があった場合、 新しいレコードを挿入する時に古いレコードが新しいものに置き換えられることを意味します。

If you get performance problems in making backups on your system, you can solve this by setting up replication and do the backups on the slave instead of on the master. See section Introduction.

If you are using a Veritas filesystem, you can do:

  1. From a client (or Perl), execute: FLUSH TABLES WITH READ LOCK.
  2. From another shell, execute: mount vxfs snapshot.
  3. From the first client, execute: UNLOCK TABLES.
  4. Copy files from snapshot.
  5. Unmount snapshot.

BACKUP TABLE 構文 (3.23.25以上)

BACKUP TABLE tbl_name[,tbl_name...] TO '/path/to/backup/directory'

Copies to the backup directory the minimum number of table files needed to restore the table, after flushing any buffered changes to disk. Currently works only for MyISAM tables. For MyISAM tables, copies `.frm' (definition) and `.MYD' (data) files. The index file can be rebuilt from those two.

Before using this command, please see section データベースのバックアップ.

During the backup, a read lock will be held for each table, one at time, as they are being backed up. If you want to back up several tables as a snapshot, you must first issue LOCK TABLES obtaining a read lock for each table in the group.

The command returns a table with the following columns:

Column Value
Table Table name
Op Always ``backup''
Msg_type One of status, error, info or warning.
Msg_text The message.

Note that BACKUP TABLE is only available in MySQL version 3.23.25 and later.

RESTORE TABLE 構文 (3.23.25以上)

RESTORE TABLE tbl_name[,tbl_name...] FROM '/path/to/backup/directory'

Restores the table(s) from the backup that was made with BACKUP TABLE. Existing tables will not be overwritten; if you try to restore over an existing table, you will get an error. Restoring will take longer than backing up due to the need to rebuild the index. The more keys you have, the longer it will take. Just as BACKUP TABLE, RESTORE TABLE currently works only for MyISAM tables.

The command returns a table with the following columns:

Column Value
Table Table name
Op Always ``restore''
Msg_type One of status, error, info or warning.
Msg_text The message.

CHECK TABLE 構文 (3.23.13以上)

CHECK TABLE tbl_name[,tbl_name...] [option [option...]]

option = QUICK | FAST | MEDIUM | EXTENDED | CHANGED

CHECK TABLEMyISAM テーブル と InnoDB テーブルだけで動作します。 MyISAM テーブルでは、テーブル上で myisamchk -m table_name を 実行するのと同じことです。

オプションを何も指定しない場合は MEDIUM が使用されます。

テーブルのエラーチェックを行ないます。MyISAM テーブルではキー統計が 更新されます。 このコマンドは次のフィールドを持つテーブルを返します:

Column Value
Table テーブル名
Op 常に ``check''
Msg_type status, error, info, warning のうちの一つ。
Msg_text メッセージ。

注意: チェックされた各テーブルに対する情報の多くのレコードが得られます。 最後の1レコードは Msg_type status になり、通常は OK で あるべきです。OKTable is already up to date が得られない場合は、 テーブルの修復を通常通り実行すべきです。 See section テーブルのメンテナンス、クラッシュからの修復のための myisamchk 使用. Table is already up to date means that the table the given TYPE told MySQL that there wasn't any need to check the table.

様々なチェックタイプは次の意味です:

Type Meaning
QUICK 間違ったリンクをチェックするレコードを走査しません。
FAST 正しくクローズされなかったテーブルだけをチェックします。
CHANGED 最後にチェックしてから変更されたテーブルと、正しくクローズされなかったテーブルだけをチェックします。
MEDIUM 削除されたリンクが OK であることを確かめるためにレコードを走査します。これはレコードのキーチェックサムも計算し、キーの計算されたチェックサムをで、これを確かめます。
EXTENDED 各レコードのすべてのキーを完全キー検索を行ないます。テーブルが 100% 正当なことを確実にしますが、長い時間が掛かります!

動的なサイズの MyISAM テーブルについて、開始されたチェックは常に MEDIUM チェックを行ないます。清適サイズレコードでは、レコードはめっ たに壊れないので、QUICKFAST ではレコードスキャンをスキッ プします。

チェックオプションは次のように組み合わせられます:

CHECK TABLE test_table FAST QUICK;

これは、テーブルが正しくクローズされなかったかどうかだけを素早くチェックし ます。

Note: いくつかのケースでは CHECK TABLE はテーブルを変更し ます! これはテーブルが '汚れている' か '正しくクローズされなかった' とマー クされているのに、CHECK TABLE がテーブル内に何も問題を発見しなかっ た場合に発生します。この場合、CHECK TABLE はテーブルを OK とマーク します。

If a table is corrupted, then it's most likely that the problem is in the indexes and not in the data part. All of the above check types checks the indexes thoroughly and should thus find most errors.

If you just want to check a table that you assume is okay, you should use no check options or the QUICK option. The latter should be used when you are in a hurry and can take the very small risk that QUICK didn't find an error in the datafile. (In most cases MySQL should find, under normal usage, any error in the data file. If this happens then the table will be marked as 'corrupted', in which case the table can't be used until it's repaired.)

FAST and CHANGED are mostly intended to be used from a script (for example to be executed from cron) if you want to check your table from time to time. In most cases you FAST is to be prefered over CHANGED. (The only case when it isn't is when you suspect a bug you have found a bug in the MyISAM code.)

EXTENDED is only to be used after you have run a normal check but still get strange errors from a table when MySQL tries to update a row or find a row by key (this is very unlikely if a normal check has succeeded!).

Some things reported by check table, can't be corrected automatically:

REPAIR TABLE 構文 (3.23.14以上)

REPAIR TABLE tbl_name[,tbl_name...] [QUICK] [EXTENDED] [USE_FRM]

REPAIR TABLEMyISAM テーブルだけで動作します。テーブルに myisamchk -r table_name を実行することと同じです。

Normally you should never have to run this command, but if disaster strikes you are very likely to get back all your data from a MyISAM table with REPAIR TABLE. If your tables get corrupted a lot you should try to find the reason for this! See section What To Do If MySQL Keeps Crashing. See section MyISAM table problems..

REPAIR TABLE はなんとかなる壊れたテーブルを修復します。コマンドは次 のフィールドを含む表を返します:

Column Value
Table テーブル名
Op Always ``repair''
Msg_type status, error, info, warning のどれか.
Msg_text メッセージ

注意: 修復された各テーブルの情報の多くのレコードを得ることがあります。最後 の1レコードは Msg_type status になり、通常は OK であるべき です。OK が得られなければ、myisamchk -o でテーブルの修復を試 みるべきです。REPAIR TABLE はまだ、myisamchk のオプションの 全てを持っていないからです。 In the near future, we will make it more flexible.

QUICK が与えられた場合は、MySQL はインデックスツリー の REPAIR だけを試みます。

If you use EXTENDED then MySQL will create the index row by row instead of creating one index at a time with sorting; this may be better than sorting on fixed-length keys if you have long CHAR keys that compress very well. This type of repair is like that done by myisamchk --safe-recover.

As of MySQL 4.0.2, there is a USE_FRM mode for REPAIR. Use it if the `.MYI' file is missing or if its header is corrupted. In this mode MySQL will recreate the table, using information from the `.frm' file. This kind of repair cannot be done with myisamchk.

テーブルのメンテナンス、クラッシュからの修復のための myisamchk 使用

Starting with MySQL Version 3.23.13, you can check MyISAM tables with the CHECK TABLE command. See section CHECK TABLE 構文 (3.23.13以上). You can repair tables with the REPAIR TABLE command. See section REPAIR TABLE 構文 (3.23.14以上).

MyISAM テーブル (.MYI and .MYD) の検査・修復には myisamchk を 使用します。 ISAM テーブル (.ISM and .ISD) の検査・修復には isamchk を 使用します。 See section MySQL テーブル型.

以下の文は myisamchk について述べていますが、isamchk にもすべて 当てはまります。

myisamchk ユーティリティは、データベースのテーブルの情報を得たり、 チェックしたり、テーブルの修復や最適化に使用します。 以下のセクションでは、 myisamchk の起動方法(オプションの説明も含む)、 テーブルの保守スケジュールのたて方、 myisamchk の色々な機能の使い方を述べます。

テーブルの修復と最適化のために、ほとんどの場合、 OPTIMIZE TABLES コマンドが使用できます。しかしこれは myisamchk に比べて、 遅くて確実でもありません。(fatal error発生時の場合)。これは その反面、使用方法が簡単でテーブルのフラッシュを気にかける必要がありません。 See section OPTIMIZE TABLE 構文.

Even that the repair in myisamchk is quite secure, it's always a good idea to make a backup before doing a repair (or anything that could make a lot of changes to a table)

myisamchk 起動構文

myisamchk は以下のようにして起動します:

shell> myisamchk [options] tbl_name

options に、あなたが myisamchk にさせたいことを指定します。 その説明は後述します。(myisamchk --help と実行すれば、オプションの一覧が取れます)。 オプションがなければ、 myisamchk は単にテーブルを検査するだけです。 より多くの情報を得たい、あるいは、 myisamchk に誤り訂正の行動を 取らせる事については、後述します。

tbl_name は検査/修復したいテーブル名です。 もしどこか違うディレクトリにあるデータベースに対して myisamchk を走らせたいなら、 myisamchk にはファイルがどこにあるかわからないので、 ファイルのパスを指定しなければなりません。 実際、 myisamchk はあなたが使用しているファイルがデータベースのディレクトリにある かどうかは考慮しません; ほかの場所にデータベーステーブルのファイルをコピーし、そのコピーしたファイルに対して 回復操作を実行することができます。

myisamchk コマンドラインには、複数のテーブル名が指定できます。 また、インデックスファイル名(`.MYI' 接尾語のついたファイル)も指定でき、 さらに `*.MYI' とすれば、ディレクトリ内の全てのテーブルが指定できます。 例えば、現在のカレントディレクトリがデーターベースディレクトリならば、 そのディレクトリ内の全てのテーブルは、以下のようにして検査できます:

shell> myisamchk *.MYI

データベースディレクトリに入っていない場合、 パスを指定することにより全てのテーブルが検査できます:

shell> myisamchk /path/to/database_dir/*.MYI

MySQL データディレクトリのパスにワイルドカードを使用することにより、 データベースの全てのテーブルも検査できます:

shell> myisamchk /path/to/datadir/*/*.MYI

The recommended way to quickly check all tables is:

myisamchk --silent --fast /path/to/datadir/*/*.MYI
isamchk --silent /path/to/datadir/*/*.ISM

If you want to check all tables and repair all tables that are corrupted, you can use the following line:

myisamchk --silent --force --fast --update-state -O key_buffer=64M \
          -O sort_buffer=64M -O read_buffer=1M -O write_buffer=1M \
          /path/to/datadir/*/*.MYI
isamchk --silent --force -O key_buffer=64M -O sort_buffer=64M \
        -O read_buffer=1M -O write_buffer=1M /path/to/datadir/*/*.ISM

The above assumes that you have more than 64 M free.

Note that if you get an error like:

myisamchk: warning: 1 clients is using or hasn't closed the table properly

This means that you are trying to check a table that has been updated by the another program (like the mysqld server) that hasn't yet closed the file or that has died without closing the file properly.

If you mysqld is running, you must force a sync/close of all tables with FLUSH TABLES and ensure that no one is using the tables while you are running myisamchk. In MySQL Version 3.23 the easiest way to avoid this problem is to use CHECK TABLE instead of myisamchk to check tables.

myisamchk の一般オプション

myisamchk supports the following options.

-# or --debug=debug_options
デバッグログの出力。 debug_options はよく 'd:t:o,filename' とされます。
-? or --help
ヘルプを表示して終了。
-O var=option, --set-variable var=option
変数に値を入れます。 Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own. 可能な変数とデフォルトの値は myisamchk --help で確認できます:
Variable Value
key_buffer_size 523264
read_buffer_size 262136
write_buffer_size 262136
sort_buffer_size 2097144
sort_key_blocks 16
decode_bits 9
sort_buffer_size is used when the keys are repaired by sorting keys, which is the normal case when you use --recover. key_buffer_size is used when you are checking the table with --extended-check or when the keys are repaired by inserting key row by row in to the table (like when doing normal inserts). Repairing through the key buffer is used in the following cases: Reparing through the key buffer takes much less disk space than using sorting, but is also much slower. もし速い修復を望むなら、メモリの 1/4 を上記の変数にセットします。 You can set both variables to big values, as only one of the above buffers will be used at a time.
-s or --silent
静粛モード。 エラーのみを出力します。 二度 -s を指定すると(-ss)、myisamchk は ほとんど出力をしなくなります。
-v or --verbose
冗長モード。より多く情報を出力します。 -d-e オプションと共に使用できます。 -v を複数指定すると(-vv, -vvv)、もっと出力が多くなります!
-V or --version
myisamchk バージョンを表示して終了。
-w or, --wait
Instead of giving an error if the table is locked, wait until the table is unlocked before continuing. Note that if you are running mysqld on the table with --skip-external-locking, the table can only be locked by another myisamchk command.

myisamchk の検査オプション

-c or --check
テーブルのエラーをチェック。 これは myisamchk にオプションを 与えていない時のデフォルトです。
-e or --extend-check
テーブルを非常に徹底的に検査します。 (ただし多くのインデックスがある場合、 とても遅くなります。). 極端な場合にだけで必要とされます。 通常 myisamchkmyisamchk --medium-check は、 このオプションなしで全てのエラーを見つけるはずです。 多くのメモリがマシンにあるなら、--extended-check を使用する際には key_buffer_size の値を多く増やします。
-F or --fast
Check only tables that haven't been closed properly.
-C or --check-only-changed
Check only tables that have changed since the last check.
-f or --force
Restart myisamchk with -r (repair) on the table, if myisamchk finds any errors in the table.
-i or --information
検査されたテーブルの統計情報を表示。
-m or --medium-check
Faster than extended-check, but only finds 99.99% of all errors. Should, however, be good enough for most cases.
-U or --update-state
Store in the `.MYI' file when the table was checked and if the table crashed. This should be used to get full benefit of the --check-only-changed option, but you shouldn't use this option if the mysqld server is using the table and you are running mysqld with --skip-external-locking.
-T or --read-only
Don't mark table as checked. This is useful if you use myisamchk to check a table that is in use by some other application that doesn't use locking (like mysqld --skip-external-locking).

myisamchk の修復オプション

以下のオプションは myisamchk-r-o オプションで 実行した場合に使用できます:

-D # or --data-file-length=#
Max length of datafile (when re-creating datafile when it's 'full').
-e or --extend-check
Try to recover every possible row from the datafile. Normally this will also find a lot of garbage rows. Don't use this option if you are not totally desperate.
-f or --force
Overwrite old temporary files (table_name.TMD) instead of aborting.
-k # or keys-used=#
If you are using ISAM, tells the ISAM storage engine to update only the first # indexes. If you are using MyISAM, tells which keys to use, where each binary bit stands for one key (first key is bit 0). これはインサートを速くします! 非アクティブになったインデックスは、myisamchk -r を使用すれば再びアクティ ブになります。
-l or --no-symlinks
修復時にシンボリックリンクを追いません。 通常、myisamchk はシンボリックリンクが指し示すテーブルも修復します。 This option doesn't exist in MySQL 4.0, as MySQL 4.0 will not remove symlinks during repair.
-r or --recover
Can fix almost anything except unique keys that aren't unique (which is an extremely unlikely error with ISAM/MyISAM tables). If you want to recover a table, this is the option to try first. Only if myisamchk reports that the table can't be recovered by -r, you should then try -o. (Note that in the unlikely case that -r fails, the datafile is still intact.) If you have lots of memory, you should increase the size of sort_buffer_size!
-o or --safe-recover
古い修復方法を使用します (reads through all rows in order and updates all index trees based on the found rows); これは -r よりも遅いですが、 -r が扱えないものも扱えます。 This recovery method also uses much less disk space than -r. Normally one should always first repair with -r, and only if this fails use -o. If you have lots of memory, you should increase the size of key_buffer_size!
-n or --sort-recover
Force myisamchk to use sorting to resolve the keys even if the temporary files should be very big.
--character-sets-dir=...
Directory where character sets are stored.
--set-character-set=name
Change the character set used by the index
-t or --tmpdir=path
一時ファイルを保存する先のパス。 もしセットされなければ、 myisamchkTMPDIR 環境変数の値をこのパスとします。 Starting from MySQL 4.1, tmpdir can be set to a list of paths separated by colon : (semicolon ; on Windows). They will be used in round-robin fashion.
-q or --quick
Faster repair by not modifying the datafile. One can give a second -q to force myisamchk to modify the original datafile in case of duplicate keys
-u or --unpack
myisampack でパックされたテーブルファイルをアンパックします。

myisamchk の他のオプション

Other actions that myisamchk can do, besides repair and check tables:

-a or --analyze
キーの分布(配置)を分析します。 This improves join performance by enabling the join optimiser to better choose in which order it should join the tables and which keys it should use: myisamchk --describe --verbose table_name' or using SHOW KEYS in MySQL.
-d or --description
テーブルに関するいくらかの情報を表示します
-A or --set-auto-increment[=value]
Force AUTO_INCREMENT to start at this or higher value. If no value is given, then sets the next AUTO_INCREMENT value to the highest used value for the auto key + 1.
-S or --sort-index
インデックスブロックのソート。 これは、アプリケーションでの ``read-next'' を速くします。
-R or --sort-records=#
インデックスに従ってソート。 これはあなたのデータをよりよく配置し、このインデックスへの SELECT, ORDER BY オペレーションを速くします。 (この操作の最初のソートは非常に遅くなるかもしれません!) テーブルのインデックスの番号をみつけるには SHOW INDEX を使用しますが、 これは myisamchk がテーブルのインデックスを見つけるのと同じ順序で行います。 インデックス番号は 1 から始まります。

myisamchk メモリ使用

myisamchk を走らす上でメモリーの配分は重要です。 myisamchk-O オプションで定義した以上のメモリは使用しません。 とても大きなファイルのたいして myisamchk をかけたいなら、 メモリーをどれくらい使用するかを最初に決めなくてはなりません。 デフォルトは固定で約 3M だけを使用します。大きな値を使用することで、 myisamchk をより速く動作できます。 例えば、32MBytesのRAMがあるなら、以下のように指定できます (他のオプションも指定して):

shell> myisamchk -O sort=16M -O key=16M -O read=1M -O write=1M ...

-O sort=16M の使用は多くの場合おそらく十分でしょう。

しかし、myisamchkTMPDIR 内に一時ファイルを使用します。 TMPDIR がメモリファイルシステムを指している場合は、簡単に out of memory エラーを得るでしょう。 If this happens, set TMPDIR to point at some directory with more space and restart myisamchk.

When repairing, myisamchk will also need a lot of disk space:

If you have a problem with disk space during repair, you can try to use --safe-recover instead of --recover.

Using myisamchk for Crash Recovery

If you run mysqld with --skip-external-locking (which is the default on some systems, like Linux), you can't reliably use myisamchk to check a table when mysqld is using the same table. If you can be sure that no one is accessing the tables through mysqld while you run myisamchk, you only have to do mysqladmin flush-tables before you start checking the tables. If you can't guarantee the above, then you must take down mysqld while you check the tables. If you run myisamchk while mysqld is updating the tables, you may get a warning that a table is corrupt even if it isn't.

If you are not using --skip-external-locking, you can use myisamchk to check tables at any time. While you do this, all clients that try to update the table will wait until myisamchk is ready before continuing.

If you use myisamchk to repair or optimise tables, you must always ensure that the mysqld server is not using the table (this also applies if you are using --skip-external-locking). If you don't take down mysqld you should at least do a mysqladmin flush-tables before you run myisamchk. Your tables may be corrupted if the server and myisamchk access the tables simultaneously.

This chapter describes how to check for and deal with data corruption in MySQL databases. If your tables get corrupted frequently you should try to find the reason for this! See section What To Do If MySQL Keeps Crashing.

The MyISAM table section contains reason for why a table could be corrupted. See section MyISAM table problems..

When performing crash recovery, it is important to understand that each table tbl_name in a database corresponds to three files in the database directory:

File Purpose
`tbl_name.frm' Table definition (form) file
`tbl_name.MYD' Datafile
`tbl_name.MYI' Index file

Each of these three file types is subject to corruption in various ways, but problems occur most often in datafiles and index files.

myisamchk works by creating a copy of the `.MYD' (data) file row by row. It ends the repair stage by removing the old `.MYD' file and renaming the new file to the original file name. If you use --quick, myisamchk does not create a temporary `.MYD' file, but instead assumes that the `.MYD' file is correct and only generates a new index file without touching the `.MYD' file. This is safe, because myisamchk automatically detects if the `.MYD' file is corrupt and aborts the repair in this case. You can also give two --quick options to myisamchk. In this case, myisamchk does not abort on some errors (like duplicate key) but instead tries to resolve them by modifying the `.MYD' file. Normally the use of two --quick options is useful only if you have too little free disk space to perform a normal repair. In this case you should at least make a backup before running myisamchk.

How to Check Tables for Errors

To check a MyISAM table, use the following commands:

myisamchk tbl_name
This finds 99.99% of all errors. What it can't find is corruption that involves only the datafile (which is very unusual). If you want to check a table, you should normally run myisamchk without options or with either the -s or --silent option.
myisamchk -m tbl_name
This finds 99.999% of all errors. It checks first all index entries for errors and then it reads through all rows. It calculates a checksum for all keys in the rows and verifies that they checksum matches the checksum for the keys in the index tree.
myisamchk -e tbl_name
This does a complete and thorough check of all data (-e means ``extended check''). It does a check-read of every key for each row to verify that they indeed point to the correct row. This may take a long time on a big table with many keys. myisamchk will normally stop after the first error it finds. If you want to obtain more information, you can add the --verbose (-v) option. This causes myisamchk to keep going, up through a maximum of 20 errors. In normal usage, a simple myisamchk (with no arguments other than the table name) is sufficient.
myisamchk -e -i tbl_name
Like the previous command, but the -i option tells myisamchk to print some informational statistics, too.

テーブルの修復方法

In the following section we only talk about using myisamchk on MyISAM tables (extensions `.MYI' and `.MYD'). If you are using ISAM tables (extensions `.ISM' and `.ISD'), you should use isamchk instead.

Starting with MySQL Version 3.23.14, you can repair MyISAM tables with the REPAIR TABLE command. See section REPAIR TABLE 構文 (3.23.14以上).

テーブル破壊の兆しとして、クエリが予期せず中断したり、以下のようなエラーが出たり します:

この他の場合、あなたは自分のテーブルを修理しなければなりません。 myisamchk はほとんどの問題を見つけ出し修正します。

修復過程は以下で記述する最大4つの段階を踏みます。 これを始める前に、あなたはデータベースディレクトリに cd して テーブルファイルのパーミッションを確認すべきです。 これらファイルは mysqld を実行している UNIX ユーザーが読み込み可能 であるようにしてください(検査のするのにあなたにファイルのアクセス権も必要)。 もしファイルの変更をする必要があるならば、ファイルへの書き込み許可も必要です。

If you are using MySQL Version 3.23.16 and above, you can (and should) use the CHECK and REPAIR commands to check and repair MyISAM tables. See section CHECK TABLE 構文 (3.23.13以上). See section REPAIR TABLE 構文 (3.23.14以上).

The manual section about table maintenance includes the options to isamchk/myisamchk. See section テーブルのメンテナンス、クラッシュからの修復のための myisamchk 使用.

The following section is for the cases where the above command fails or if you want to use the extended features that isamchk/myisamchk provides.

If you are going to repair a table from the command-line, you must first take down the mysqld server. Note that when you do mysqladmin shutdown on a remote server, the mysqld server will still be alive for a while after mysqladmin returns, until all queries are stopped and all keys have been flushed to disk.

Stage 1: テーブルをチェックする

myisamchk *.MYI (時間がかかってもよいなら myisamchk -e *.MYI) を実行します。 -s (silent) オプションは不要な情報の出力をおさえます。

If the mysqld server is done you should use the --update option to tell myisamchk to mark the table as 'checked'.

myisamchk がエラーを返した場合にだけ、テーブルを修復する必要があります。 この場合、Stage 2 へ進みます。

チェック時に奇妙なエラー(out of memory エラーのような) が起きた場合、 あるいは myisamchk が落ちた場合、Stage 3 に進んでください。

Stage 2: 簡単で安全な修復

Note: If you want repairing to go much faster, you should add: -O sort_buffer=# -O key_buffer=# (where # is about 1/4 of the available memory) to all isamchk/myisamchk commands.

まず最初に myisamchk -r -q tbl_name を試みてください (-r -q は ``quick recovery mode''の意)。 これはデータファイルに触れないでインデックスファイルの修理を試みます。 もしデータファイルが全てとデータファイル中の正しい場所での削除リンクポイントを 含んでいるなら、これは動作してテーブルを修復します。 成功後、次のテーブルの修復に進んでください。 失敗した場合は、以下の手順で試みてください:

  1. 続ける前にデータファイルをバックアップしてください。
  2. myisamchk -r tbl_name を使用します(-r は ``recovery mode''の意)。 これは不正なレコードと削除されたレコードをデータファイルから消去し、 インデックスファイル(.MYI)を再構築します。
  3. 上記が失敗した場合、myisamchk --safe-recover tbl_name を使用して下さい。 Safe recovery モードは古い方法を使用して修復します。 これは普通の修復モードでは行わない操作をいくつかもっています。(遅いですが)

If you get weird errors when repairing (such as out of memory errors), or if myisamchk crashes, go to Stage 3.

Stage 3: 難しい修復

インデックスファイル(.MYI)の最初の 16K ブロックが破壊された場合、 または不正な情報を含む場合、またはインデックスファイルがない場合にだけ、 本修復段階を経ます。 この場合、新しいインデックスファイルファイルを作成する必要があります。 次のようにしてください:

  1. データファイルをどこか安全場所に移動します。
  2. 新しい(空の)データとインデックスファイルを作るために、 テーブルディスクリプタファイルを使用します:
    shell> mysql db_name
    mysql> SET AUTOCOMMIT=1;
    mysql> TRUNCATE TABLE table_name;
    mysql> quit
    
    If your SQL version doesn't have TRUNCATE TABLE, use DELETE FROM table_name instead.
  3. 古いデータファイルを新しく作ったデータファイルにコピーします。 (Don't just move the old file back onto the new file; you want to retain a copy in case something goes wrong.)

Go back to Stage 2. myisamchk -r -q should work now. (This shouldn't be an endless loop.)

As of MySQL 4.0.2 you can also use REPAIR ... USE_FRM which performs the whole procedure automatically.

Stage 4: とても難しい修復

これは、ディスクリプタファイル(.frm)もクラッシュした場合にだけ発生します。 これは発生することはありません。なぜならディスクリプタファイルは テーブルが生成された後に書かれることはないからです。

  1. ディスクリプタファイルをバックアップからリストアして、Stage 3 に戻ってください。 インデックスファイルのリストアもできます。そして Stage 2 に戻ってください。 後者の場合、myisamchk -r で開始すべきです。
  2. バックアップを持っていなくても、テーブルがどのように作成されたかを正確に知って いれば、他のデータベース内にテーブルのコピーを生成します。 新しいデータファイルを削除し、先ほど作ったデータベースの中の ディスクリプタファイルとインデックスファイルを、壊れたデータベース内に 移動します。これは新しいディスクリプタファイルとインデックスファイルを 与えることになりますが、データファイルはそのまま残っています。 Stage 2 に進み、インデックスファイルの修復を行ってください。

テーブルの最適化

断片化されたレコードの結合と、 レコードの削除と更新から生じる無駄なスペースの排除、 これら行うには、修復モード(recovery mode)で myisamchk を実行します:

shell> myisamchk -r tbl_name

You can optimise a table in the same way using the SQL OPTIMIZE TABLE statement. OPTIMIZE TABLE does a repair of the table and a key analysis, and also sorts the index tree to give faster key lookups. There is also no possibility of unwanted interaction between a utility and the server, because the server does all the work when you use OPTIMIZE TABLE. See section OPTIMIZE TABLE 構文.

myisamchk には、あなたがテーブルの性能を向上させるのに使用することができる 他の多くのオプションがあります:

For a full description of the option. See section myisamchk 起動構文.

テーブルの保守体制の設定

Starting with MySQL Version 3.23.13, you can check MyISAM tables with the CHECK TABLE command. See section CHECK TABLE 構文 (3.23.13以上). You can repair tables with the REPAIR TABLE command. See section REPAIR TABLE 構文 (3.23.14以上).

問題が発生するまで待つより、定期的にテーブルを検査する方がよりよい考えです。 保守目的には、myisamchk -s でテーブルを検査するのがよいでしょう。 -s オプション(short for --silent) はサイレントモードなので、 エラーが起きた場合にだけメッセージを出力します。

サーバーを開始するときにテーブルを検査するのもよい考えです。 例えば、更新最中にマシンがリブートされたなら、全てのテーブルに関して その影響がないか検査する必要があります。(これは``expected crashed table''です) リブート後にもし古い `.pid' ファイル(プロセスID) があるならば、 24時間以内に変更されたテーブルに対して myisamchk を走らせて検査させるよう に、 safe_mysqld にテストを追加しても構いません。 (`.pid' ファイルは mysqld 起動時に作られ、通常修了時に消されます。 スタート時に `.pid' ファイルが存在するなら mysqld が異常終了したこと を示します。)

良いテストは、`.pid' ファイルの作成時間以降に変更された 全てのテーブルを検査するテストです。

通常のシステム運用中にもテーブルを検査すべきです。 MySQL AB では、週に一度、 cron を使用して重要なテーブルを検査し ています。 `crontab' ファイルには以下のように記述します:

35 0 * * 0 /path/to/myisamchk --fast --silent /path/to/datadir/*/*.MYI

これは壊れたテーブルの情報を出力しますので、必要とあらば検査、修復が行えるわけで す。

予想外の事故で壊れたテーブル(ハードウェアのトラブルが原因で崩壊)を除き、 2,3年間、テーブルは壊れたことはありません(これは本当に本当です)。 ので、一週間に一度のチェックでも十分です。

24時間以内に変更された全てのテーブルに対して、 myisamchk -s を毎晩実行する事を勧めます。 そうすれば、あなたは我々と同じぐらいに MySQL を 信頼することになります。

Normally you don't need to maintain MySQL tables that much. If you are changing tables with dynamic size rows (tables with VARCHAR, BLOB or TEXT columns) or have tables with many deleted rows you may want to from time to time (once a month?) defragment/reclaim space from the tables.

You can do this by using OPTIMIZE TABLE on the tables in question or if you can take the mysqld server down for a while do:

isamchk -r --silent --sort-index -O sort_buffer_size=16M */*.ISM
myisamchk -r --silent --sort-index  -O sort_buffer_size=16M */*.MYI

テーブル情報取得

テーブルから詳細/統計を得るためには、次の方法を使用します。後でさらに詳細な情 報をいくつか説明します。

myisamchk -d 出力の例:

MyISAM file:     company.MYI
Record format:   Fixed length
Data records:    1403698  Deleted blocks:         0
Recordlength:    226

table description:
Key Start Len Index   Type
1   2     8   unique  double
2   15    10  multip. text packed stripped
3   219   8   multip. double
4   63    10  multip. text packed stripped
5   167   2   multip. unsigned short
6   177   4   multip. unsigned long
7   155   4   multip. text
8   138   4   multip. unsigned long
9   177   4   multip. unsigned long
    193   1           text

myisamchk -d -v 出力の例:

MyISAM file:         company
Record format:       Fixed length
File-version:        1
Creation time:       1999-10-30 12:12:51
Recover time:        1999-10-31 19:13:01
Status:              checked
Data records:           1403698  Deleted blocks:              0
Datafile parts:         1403698  Deleted data:                0
Datafilepointer (bytes):      3  Keyfile pointer (bytes):     3
Max datafile length: 3791650815  Max keyfile length: 4294967294
Recordlength:               226

table description:
Key Start Len Index   Type                  Rec/key     Root Blocksize
1   2     8   unique  double                      1 15845376      1024
2   15    10  multip. text packed stripped        2 25062400      1024
3   219   8   multip. double                     73 40907776      1024
4   63    10  multip. text packed stripped        5 48097280      1024
5   167   2   multip. unsigned short           4840 55200768      1024
6   177   4   multip. unsigned long            1346 65145856      1024
7   155   4   multip. text                     4995 75090944      1024
8   138   4   multip. unsigned long              87 85036032      1024
9   177   4   multip. unsigned long             178 96481280      1024
    193   1           text

myisamchk -eis 出力の例:

Checking MyISAM file: company
Key:  1:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
Key:  2:  Keyblocks used:  98%  Packed:   50%  Max levels:  4
Key:  3:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
Key:  4:  Keyblocks used:  99%  Packed:   60%  Max levels:  3
Key:  5:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  6:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  7:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  8:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  9:  Keyblocks used:  98%  Packed:    0%  Max levels:  4
Total:    Keyblocks used:  98%  Packed:   17%

Records:          1403698    M.recordlength:     226
Packed:             0%
Recordspace used:     100%   Empty space:          0%
Blocks/Record:   1.00
Record blocks:    1403698    Delete blocks:        0
Recorddata:     317235748    Deleted data:         0
Lost space:             0    Linkdata:             0

User time 1626.51, System time 232.36
Maximum resident set size 0, Integral resident set size 0
Non physical pagefaults 0, Physical pagefaults 627, Swaps 0
Blocks in 0 out 0, Messages in 0 out 0, Signals 0
Voluntary context switches 639, Involuntary context switches 28966

myisamchk -eiv 出力の例:

Checking MyISAM file: company
Data records: 1403698   Deleted blocks:       0
- check file-size
- check delete-chain
block_size 1024:
index  1:
index  2:
index  3:
index  4:
index  5:
index  6:
index  7:
index  8:
index  9:
No recordlinks
- check index reference
- check data record references index: 1
Key:  1:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
- check data record references index: 2
Key:  2:  Keyblocks used:  98%  Packed:   50%  Max levels:  4
- check data record references index: 3
Key:  3:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
- check data record references index: 4
Key:  4:  Keyblocks used:  99%  Packed:   60%  Max levels:  3
- check data record references index: 5
Key:  5:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 6
Key:  6:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 7
Key:  7:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 8
Key:  8:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 9
Key:  9:  Keyblocks used:  98%  Packed:    0%  Max levels:  4
Total:    Keyblocks used:   9%  Packed:   17%

- check records and index references
[LOTS OF ROW NUMBERS DELETED]

Records:          1403698    M.recordlength:     226   Packed:             0%
Recordspace used:     100%   Empty space:          0%  Blocks/Record:   1.00
Record blocks:    1403698    Delete blocks:        0
Recorddata:     317235748    Deleted data:         0
Lost space:             0    Linkdata:             0

User time 1639.63, System time 251.61
Maximum resident set size 0, Integral resident set size 0
Non physical pagefaults 0, Physical pagefaults 10580, Swaps 0
Blocks in 4 out 0, Messages in 0 out 0, Signals 0
Voluntary context switches 10604, Involuntary context switches 122798

上で使用されたテーブルのデータファイルサイズをここに示します:

-rw-rw-r--   1 monty    tcx     317235748 Jan 12 17:30 company.MYD
-rw-rw-r--   1 davida   tcx      96482304 Jan 12 18:35 company.MYM

myisamchk が生成する情報の説明を以下に示します。 ``keyfile'' はインデックスファイルです。 ``Record'' と ``row'' は同義です。

テーブルが pack_isam で圧縮されているなら、myisamchk -d は それぞれのテーブルコラムに関する追加情報を出力します。 section myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ. を参照してください。 この情報例と説明記述の意味があります。

Database Administration Language Reference

OPTIMIZE TABLE 構文

OPTIMIZE TABLE tbl_name[,tbl_name]...

OPTIMIZE TABLEは、テーブルの大部分を削除したり、可変長となっているテーブ ル(VARCHARBLOBもしくはTEXTフィールドを持つテーブル)に多く の変更を加えた場合に使用すべきです。 削除されたレコードはリンクリストで維持され、次のINSERT操作は、古いレコー ド位置を再利用します。 未使用領域を再生するためにOPTIMIZE TABLEを使用することができます。

今のところ、OPTIMIZE TABLEMyISAMBDB テーブ ル上でだけ動作します。BDB テーブルでは、OPTIMIZE TABLE が現 在 ANALYZE TABLE にマップされます。 See section ANALYZE TABLE Syntax.

--skip-new または --safe-modemysqld を起動するこ とで、他のテーブル型で OPTIMIZE TABLE を動作するようにできます。しかし、こ の場合 OPTIMIZE TABLEALTER TABLE にマップされるだけです。

OPTIMIZE TABLE は次の方法で動作します:

MyISAM テーブルの OPTIMIZE TABLE はテーブル上で myisamchk --quick --check-changed-tables --sort-index --analyze を 実行することと同等です。

注意: テーブルは OPTIMIZE TABLE 実行中はロックされます!

ANALYZE TABLE Syntax

ANALYZE TABLE tbl_name[,tbl_name...]

Analyse and store the key distribution for the table. During the analysis, the table is locked with a read lock. This works on MyISAM and BDB tables.

This is equivalent to running myisamchk -a on the table.

MySQL uses the stored key distribution to decide in which order tables should be joined when one does a join on something else than a constant.

The command returns a table with the following columns:

Column Value
Table Table name
Op Always ``analyze''
Msg_type One of status, error, info or warning.
Msg_text The message.

You can check the stored key distribution with the SHOW INDEX command. See section Retrieving information about Database, Tables, Columns, and Indexes.

If the table hasn't changed since the last ANALYZE TABLE command, the table will not be analysed again.

FLUSH 構文

FLUSH flush_option [,flush_option] ...

FLUSH コマンドで MySQL が使用している内部キャッシュの いくつかをきれいに消すことができます。 FLUSH を実行するには、 RELOAD 権限がなければなりません。

flush_option には以下の内一つが指定できます:

Option Description
HOSTS ホストキャッシュテーブルを空にします。あなたのホストの IP アドレスを変えたり、Host ... is blocked というエラーメッセージが 出る場合はホストテーブルキャッシュを一度空にしなくてはなりません。 指定したホストに対して max_connect_errors 以上の接続エラーが出る場合、 MySQL は何か起きたと推定し、そのホストからのいかなる接続要求も 拒否します。ホストテーブルキャッシュの消去は、再び接続を許すようにします。 See section Host '...' is blocked エラー. mysqld-O max_connect_errors=999999999 開始し、 このエラーメッセージを回避できます
DES_KEY_FILE Reloads the DES keys from the file that was specified with the --des-key-file option at server startup time.
LOGS 標準のログファイルと更新ログファイルを 一度閉じて再び開きます。 もし更新ログファイルを拡張子無しで指定している場合、新しい更新ログファイルの 拡張子の番号は、一つ前のファイルより 1 増やした数になります。 ファイル名に拡張を使用した場合、MySQL は更新ログファイルを閉じて開きます。 See section 更新ログ. This is the same thing as sending the SIGHUP signal to the mysqld server.
PRIVILEGES mysql データベースの許可テーブルから、権限情報を再読込します。
QUERY CACHE Defragment the query cache to better utilise its memory. This command will not remove any queries from the cache, unlike RESET QUERY CACHE.
TABLES 全ての開いているテーブルを閉じます。使用中のテーブルに も close を強制します。 This also flushes the query cache.
[TABLE | TABLES] tbl_name [,tbl_name...] Flushes only the given tables.
TABLES WITH READ LOCK 全ての開いているテーブルを閉じ、 UNLOCK TABLES を実行するまで全てのテーブルを read lock でロックします。 This is very convenient way to get backups if you have a filesystem, like Veritas,that can take snapshots in time.
STATUS ほとんどのステータス変数を 0 にします。 This is something one should only use when debugging a query.
USER_RESOURCES Resets all user resources to zero. This will enable blocked users to login again. See section Limiting user resources.

上に示したコマンドは、mysqladmin を使用しても実行できます。 mysqladmin の引数はそれぞれ、flush-hosts, flush-logs, reload, flush-tables となります。

Take also a look at the RESET command used with replication. See section RESET 構文.

RESET 構文

RESET reset_option [,reset_option] ...

The RESET command is used to clear things. It also acts as an stronger version of the FLUSH command. See section FLUSH 構文.

To execute RESET, you must have the RELOAD privilege.

Option Description
MASTER Deletes all binary logs listed in the index file, resetting the binlog index file to be empty. In pre-3.23.26 versions, FLUSH MASTER (Master)
SLAVE Makes the slave forget its replication position in the master logs. In pre 3.23.26 versions the command was called FLUSH SLAVE(Slave)
QUERY CACHE Removes all query results from the query cache.

KILL 構文

KILL thread_id

thread_id には、mysqld に接続して走っているスレッドの ID を 空白で区切って指定します。 SHOW PROCESSLIST コマンドで走っているスレッドを知ることができ、 KILL thread_id コマンドでスレッドを KILL できます。

If you have the PROCESS privilege, you can see all threads. If you have the SUPER privilege, you can kill all threads. Otherwise, you can only see and kill your own threads. (version 4.0.2未満では: もし PROCESS 権限があるなら、全てのスレッドを確認し、KILL 出来ます。 そうでなければ、自分のスレッドだけを確認し、KILL する事ができます。)

mysqladmin processlistmysqladmin kill をスレッドの 検査と KILL に使用できます。

When you do a KILL, a thread-specific kill flag is set for the thread.

In most cases it may take some time for the thread to die as the kill flag is only checked at specific intervals.

SHOW 構文

   SHOW DATABASES [LIKE wild]
or SHOW [OPEN] TABLES [FROM db_name] [LIKE wild]
or SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [LIKE wild]
or SHOW INDEX FROM tbl_name [FROM db_name]
or SHOW TABLE STATUS [FROM db_name] [LIKE wild]
or SHOW STATUS [LIKE wild]
or SHOW VARIABLES [LIKE wild]
or SHOW LOGS
or SHOW [FULL] PROCESSLIST
or SHOW GRANTS FOR user
or SHOW CREATE TABLE table_name
or SHOW MASTER STATUS
or SHOW MASTER LOGS
or SHOW SLAVE STATUS
or SHOW WARNINGS [LIMIT #]
or SHOW ERRORS [LIMIT #]
or SHOW TABLE TYPES

SHOW はデータベース、テーブル、フィールド、サーバーについての情報を与えます。 LIKE wild が使用された場合、wild 文字列は通常の SQL ワイルドカード (`%'`_') です。

Retrieving information about Database, Tables, Columns, and Indexes

tbl_name FROM db_name の代わりに、db_name.tbl_name が使用できます。 これら二つは同じです:

mysql> SHOW INDEX FROM mytable FROM mydb;
mysql> SHOW INDEX FROM mydb.mytable;

SHOW DATABASES は MySQL サーバー上のデータベースを示します。 mysqlshow コマンドでも同じ情報が得られます。

SHOW TABLES は指定されたデータベースのテーブルを一覧表示します。 mysqlshow db_name コマンドでも同じ情報が得られます。 In version 4.0.2 you will only see those databases for which you have some kind of privilege, if you don't have the global SHOW DATABASES privilege.

Note: もしユーザーにテーブルに対する権限が無い場合、 テーブルは SHOW TABLESmysqlshow db_name の要求で 表示されません。

SHOW OPEN TABLES はテーブルキャッシュに現在オープン去れているテーブ ルを一覧表示します。See section MySQL はどのようにテーブルのオープン & クローズを行なうか?. Comment フィールドはテーブ ルが何回 cachedin_use になったかを知らせます。

SHOW COLUMNS は与えられたテーブルのフィールドを表示します。 FULL オプションを指定した場合、各フィールドに持つ権限も得られます。 もしそのフィールドの型が、あなたが CREATE TABLE 構文実行時に与えたものと 違う場合は、 MySQL は、フィールドの型をときおり変更することが あることに注意してください。 See section 暗黙のフィールド定義変更.

DESCRIBE 文は SHOW COLUMNS と似たような情報を提供します。 See section DESCRIBE 構文 (フィールドについての情報を得る).

SHOW FIELDSSHOW COLUMNS の別名として使用され、 SHOW KEYSSHOW INDEX の別名として使用されます。 テーブルのフィールドやインデックスは mysqlshow db_name tbl_namemysqlshow -k db_name tbl_name でも見れます。

SHOW INDEX は ODBC でいう SQLStatistics に近い形式で、インデックスの情報を表示します。 以下の項目が返ります:

Column 意味
Table テーブル名
Non_unique インデックスが重複を含まないなら 0
Key_name インデックス名
Seq_in_index インデックスの項目番号。1 から始まります。
Column_name フィールド名。
Collation どのようにこのフィールドがインデックス中で ソートされるか. MySQL ではこれは A (Ascending) か NULL (Not sorted) に なります。
Cardinality インデックス中のユニークな値の数。 これは isamchk -a の実行で更新されます。
Sub_part もしこのフィールドがインデックスに一部分だけ使用 している場合、そのインデックスに使用しているキャラクター数をしめす。 もしキー全 体がインデックスされているなら NULL
Null Contains 'YES' if the column may contain NULL.
Index_type Index method used.
Comment Various remarks. For now, it tells in MySQL < 4.0.2 whether index is FULLTEXT or not.

Note that as the Cardinality is counted based on statistics stored as integers, it's not necessarily accurate for small tables.

The Null and Index_type columns were added in MySQL 4.0.2.

SHOW TABLE STATUS

SHOW TABLE STATUS [FROM db_name] [LIKE wild]

SHOW TABLE STATUS (バージョン 3.23 の新機能) は SHOW STATUS のようですが、それぞれのテーブルについてより多くの情報を提供します。 mysqlshow --status db_name コマンドを実行しても同じものが得られます。 以下の項目が返ってきます:

項目 意味
Name テーブル名
Type テーブルの種類. See section MySQL テーブル型.
Row_format レコードの保存形式 (Fixed, Dynamic, or Compressed).
Rows レコード数.
Avg_row_length レコードの平均長.
Data_length データファイルの大きさ.
Max_data_length データファイルの最大長.
Index_length インデックスファイルの大きさ.
Data_free 割り当てられたが使用されていないバイト数.
Auto_increment 次の autoincrement 値.
Create_time テーブル作成時刻.
Update_time 一番最後にデータファイルが更新された時刻.
Check_time 一番最後にテーブルがチェックされた時刻.
Create_options CREATE TABLE で使用された拡張オプション
Comment テーブル作成時につけられたコメント (あるいは、なぜこの テーブルに MySQL がアクセスできないかのいくつかの情報).

InnoDB tables will report the free space in the tablespace in the table comment.

SHOW STATUS

SHOW STATUSmysqladmin extended-status と同様に、 サーバからのステータス情報を与えます。出力は次とは異なるかもしれません:

+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| Aborted_clients          | 0          |
| Aborted_connects         | 0          |
| Bytes_received           | 155372598  |
| Bytes_sent               | 1176560426 |
| Connections              | 30023      |
| Created_tmp_disk_tables  | 0          |
| Created_tmp_tables       | 8340       |
| Created_tmp_files        | 60         |
| Delayed_insert_threads   | 0          |
| Delayed_writes           | 0          |
| Delayed_errors           | 0          |
| Flush_commands           | 1          |
| Handler_delete           | 462604     |
| Handler_read_first       | 105881     |
| Handler_read_key         | 27820558   |
| Handler_read_next        | 390681754  |
| Handler_read_prev        | 6022500    |
| Handler_read_rnd         | 30546748   |
| Handler_read_rnd_next    | 246216530  |
| Handler_update           | 16945404   |
| Handler_write            | 60356676   |
| Key_blocks_used          | 14955      |
| Key_read_requests        | 96854827   |
| Key_reads                | 162040     |
| Key_write_requests       | 7589728    |
| Key_writes               | 3813196    |
| Max_used_connections     | 0          |
| Not_flushed_key_blocks   | 0          |
| Not_flushed_delayed_rows | 0          |
| Open_tables              | 1          |
| Open_files               | 2          |
| Open_streams             | 0          |
| Opened_tables            | 44600      |
| Questions                | 2026873    |
| Select_full_join         | 0          |
| Select_full_range_join   | 0          |
| Select_range             | 99646      |
| Select_range_check       | 0          |
| Select_scan              | 30802      |
| Slave_running            | OFF        |
| Slave_open_temp_tables   | 0          |
| Slow_launch_threads      | 0          |
| Slow_queries             | 0          |
| Sort_merge_passes        | 30         |
| Sort_range               | 500        |
| Sort_rows                | 30296250   |
| Sort_scan                | 4650       |
| Table_locks_immediate    | 1920382    |
| Table_locks_waited       | 0          |
| Threads_cached           | 0          |
| Threads_created          | 30022      |
| Threads_connected        | 1          |
| Threads_running          | 1          |
| Uptime                   | 80380      |
+--------------------------+------------+

上に示したステータス変数は以下に示すの意味を持ちます:

Variable Meaning
Aborted_clients クライアントが接続を閉じる前に死んでしまったために中断されたコネクション数。 See section Communication Errors / Aborted Connection.
Aborted_connects MySQL サーバーに接続を試みて失敗した数。 See section Communication Errors / Aborted Connection.
Bytes_received クライアントから受信したバイト数
Bytes_sent クライアントに送信したバイト数
Com_xxx Number of times each xxx command has been executed.
Connections サーバーに接続を試みた数
Created_tmp_disk_tables ステートメント実行中に暗黙のうちに作成されたメモり内にある一時テーブルの数
Created_tmp_tables Number of implicit temporary tables in memory created while executing statements.
Created_tmp_files How many temporary files mysqld has created.
Delayed_insert_threads Number of delayed insert handler threads in use.
Delayed_writes Number of rows written with INSERT DELAYED.
Delayed_errors Number of rows written with INSERT DELAYED for which some error occurred (probably duplicate key).
Flush_commands FLUSH コマンドの実行回数
Handler_commit Number of internal COMMIT commands.
Handler_delete Number of times a row was deleted from a table.
Handler_read_first Number of times the first entry was read from an index. If this is high, it suggests that the server is doing a lot of full index scans, for example, SELECT col1 FROM foo, assuming that col1 is indexed.
Handler_read_key Number of requests to read a row based on a key. If this is high, it is a good indication that your queries and tables are properly indexed.
Handler_read_next Number of requests to read next row in key order. This will be incremented if you are querying an index column with a range constraint. This also will be incremented if you are doing an index scan.
Handler_read_prev Number of requests to read previous row in key order. This is mainly used to optimise ORDER BY ... DESC.
Handler_read_rnd Number of requests to read a row based on a fixed position. This will be high if you are doing a lot of queries that require sorting of the result.
Handler_read_rnd_next Number of requests to read the next row in the datafile. This will be high if you are doing a lot of table scans. Generally this suggests that your tables are not properly indexed or that your queries are not written to take advantage of the indexes you have.
Handler_rollback Number of internal ROLLBACK commands.
Handler_update Number of requests to update a row in a table.
Handler_write Number of requests to insert a row in a table.
Key_blocks_used The number of used blocks in the key cache.
Key_read_requests The number of requests to read a key block from the cache.
Key_reads The number of physical reads of a key block from disk.
Key_write_requests The number of requests to write a key block to the cache.
Key_writes The number of physical writes of a key block to disk.
Max_used_connections The maximum number of connections in use simultaneously.
Not_flushed_key_blocks Keys blocks in the key cache that has changed but hasn't yet been flushed to disk.
Not_flushed_delayed_rows Number of rows waiting to be written in INSERT DELAY queues.
Open_tables オープンされているテーブル数
Open_files Number of files that are open.
Open_streams Number of streams that are open (used mainly for logging).
Opened_tables Number of tables that have been opened.
Rpl_status Status of failsafe replication. (Not yet in use).
Select_full_join Number of joins without keys (If this is 0, you should carefully check the index of your tables).
Select_full_range_join Number of joins where we used a range search on reference table.
Select_range Number of joins where we used ranges on the first table. (It's normally not critical even if this is big.)
Select_scan Number of joins where we did a full scan of the first table.
Select_range_check Number of joins without keys where we check for key usage after each row (If this is 0, you should carefully check the index of your tables).
Questions サーバーに送られたクエリの数
Slave_open_temp_tables Number of temporary tables currently open by the slave thread
Slave_running Is ON if this is a slave that is connected to a master.
Slow_launch_threads Number of threads that have taken more than slow_launch_time to create.
Slow_queries long_query_time 以上に時間のかかったクエリの数. See section The Slow Query Log (3.23.28以上).
Sort_merge_passes Number of merges passes the sort algoritm have had to do. If this value is large you should consider increasing sort_buffer.
Sort_range Number of sorts that where done with ranges.
Sort_rows Number of sorted rows.
Sort_scan Number of sorts that where done by scanning the table.
ssl_xxx Variables used by SSL; Not yet implemented.
Table_locks_immediate Number of times a table lock was acquired immediately. Available after 3.23.33.
Table_locks_waited Number of times a table lock could not be acquired immediately and a wait was needed. If this is high, and you have performance problems, you should first optimise your queries, and then either split your table(s) or use replication. Available after 3.23.33.
Threads_cached Number of threads in the thread cache.
Threads_connected 現在開いている接続数
Threads_created Number of threads created to handle connections.
Threads_running スリープ状態になっていないスレッドの数
Uptime サーバーが走っている秒数

上についてのいくつかコメント:

SHOW VARIABLES

SHOW [GLOBAL | SESSION] VARIABLES [LIKE wild]

SHOW VARIABLES は MySQL システム変数のいくつかの値を示します。 mysqlshow variables コマンドでも同じ情報が得られます。 もし標準値が適さないなら、ほとんどの変数を mysqld 起動時に コマンドラインのオプションとして与えることにより、変更できます。 See section mysqld コマンド行オプション.

The options GLOBAL and SESSION are new in MySQL 4.0.3. With GLOBAL you will get the variables that will be used for new connections to MySQL. With SESSION you will get the values that are in effect for the current connection. If you are not using either option, SESSION is used.

You can change most options with the SET command. See section SET 構文.

出力は以下のようになりますが、フォーマットや数はいくぶん違うでしょう:

+---------------------------------+------------------------------+
| Variable_name                   | Value                        |
+---------------------------------+------------------------------|
| back_log                        | 50                           |
| basedir                         | /usr/local/mysql             |
| bdb_cache_size                  | 8388572                      |
| bdb_log_buffer_size             | 32768                        |
| bdb_home                        | /usr/local/mysql             |
| bdb_max_lock                    | 10000                        |
| bdb_logdir                      |                              |
| bdb_shared_data                 | OFF                          |
| bdb_tmpdir                      | /tmp/                        |
| bdb_version                     | Sleepycat Software: ...	 |
| binlog_cache_size               | 32768                        |
| bulk_insert_buffer_size         | 8388608                      |
| character_set                   | latin1                       |
| character_sets                  | latin1 big5 czech euc_kr	 |
| concurrent_insert               | ON                           |
| connect_timeout                 | 5                            |
| convert_character_set           |                              |
| datadir                         | /usr/local/mysql/data/       |
| delay_key_write                 | ON                           |
| delayed_insert_limit            | 100                          |
| delayed_insert_timeout          | 300                          |
| delayed_queue_size              | 1000                         |
| flush                           | OFF                          |
| flush_time                      | 0                            |
| ft_boolean_syntax               | + -><()~*:""&|               |
| ft_min_word_len                 | 4                            |
| ft_max_word_len                 | 254                          |
| ft_max_word_len_for_sort        | 20                           |
| ft_stopword_file                | (built-in)                   |
| have_bdb                        | YES                          |
| have_innodb                     | YES                          |
| have_isam                       | YES                          |
| have_raid                       | NO                           |
| have_symlink                    | DISABLED                     |
| have_openssl                    | YES                          |
| have_query_cache                | YES                          |
| init_file                       |                              |
| innodb_additional_mem_pool_size | 1048576                      |
| innodb_buffer_pool_size         | 8388608                      |
| innodb_data_file_path           | ibdata1:10M:autoextend       |
| innodb_data_home_dir            |                              |
| innodb_file_io_threads          | 4                            |
| innodb_force_recovery           | 0                            |
| innodb_thread_concurrency       | 8                            |
| innodb_flush_log_at_trx_commit  | 0                            |
| innodb_fast_shutdown            | ON                           |
| innodb_flush_method             |                              |
| innodb_lock_wait_timeout        | 50                           |
| innodb_log_arch_dir             |                              |
| innodb_log_archive              | OFF                          |
| innodb_log_buffer_size          | 1048576                      |
| innodb_log_file_size            | 5242880                      |
| innodb_log_files_in_group       | 2                            |
| innodb_log_group_home_dir       | ./                           |
| innodb_mirrored_log_groups      | 1                            |
| interactive_timeout             | 28800                        |
| join_buffer_size                | 131072                       |
| key_buffer_size                 | 16773120                     |
| language                        | /usr/local/mysql/share/...   |
| large_files_support             | ON                           |
| local_infile                    | ON                           |
| locked_in_memory                | OFF                          |
| log                             | OFF                          |
| log_update                      | OFF                          |
| log_bin                         | OFF                          |
| log_slave_updates               | OFF                          |
| log_slow_queries                | OFF                          |
| log_warnings                    | OFF                          |
| long_query_time                 | 10                           |
| low_priority_updates            | OFF                          |
| lower_case_table_names          | OFF                          |
| max_allowed_packet              | 1047552                      |
| max_binlog_cache_size           | 4294967295                   |
| max_binlog_size                 | 1073741824                   |
| max_connections                 | 100                          |
| max_connect_errors              | 10                           |
| max_delayed_threads             | 20                           |
| max_heap_table_size             | 16777216                     |
| max_join_size                   | 4294967295                   |
| max_sort_length                 | 1024                         |
| max_user_connections            | 0                            |
| max_tmp_tables                  | 32                           |
| max_write_lock_count            | 4294967295                   |
| myisam_max_extra_sort_file_size | 268435456                    |
| myisam_max_sort_file_size       | 2147483647                   |
| myisam_recover_options          | force                        |
| myisam_sort_buffer_size         | 8388608                      |
| net_buffer_length               | 16384                        |
| net_read_timeout                | 30                           |
| net_retry_count                 | 10                           |
| net_write_timeout               | 60                           |
| open_files_limit                | 0                            |
| pid_file                        | /usr/local/mysql/name.pid    |
| port                            | 3306                         |
| protocol_version                | 10                           |
| read_buffer_size                | 131072                       |
| read_rnd_buffer_size            | 262144                       |
| rpl_recovery_rank               | 0                            |
| query_cache_limit               | 1048576                      |
| query_cache_size                | 0                            |
| query_cache_type                | ON                           |
| safe_show_database              | OFF                          |
| server_id                       | 0                            |
| slave_net_timeout               | 3600                         |
| skip_external_locking           | ON                           |
| skip_networking                 | OFF                          |
| skip_show_database              | OFF                          |
| slow_launch_time                | 2                            |
| socket                          | /tmp/mysql.sock              |
| sort_buffer_size                | 2097116                      |
| sql_mode                        | 0                            |
| table_cache                     | 64                           |
| table_type                      | MYISAM                       |
| thread_cache_size               | 3                            |
| thread_stack                    | 131072                       |
| tx_isolation                    | READ-COMMITTED               |
| timezone                        | EEST                         |
| tmp_table_size                  | 33554432                     |
| tmpdir                          | /tmp/:/mnt/hd2/tmp/          |
| version                         | 4.0.4-beta                   |
| wait_timeout                    | 28800                        |
+---------------------------------+------------------------------+

Each option is described here. Values for buffer sizes, lengths, and stack sizes are given in bytes. これらの値の後ろに `K'`M' を追加すると、キロバイト、 メガバイトになります。 例えば、16M は16メガバイトを示します。大文字小文字の区別はなく、 16M16m は同じ意味になります。

The manual section that describes tuning MySQL contains some information of how to tune the above variables. See section サーバーパラメーターのチューニング.

SHOW LOGS

SHOW LOGS shows you status information about existing log files. It currently only displays information about Berkeley DB log files.

SHOW PROCESSLIST

SHOW [FULL] PROCESSLIST はどのスレッドが走っているかを表示します。 mysqlshow processlist コマンドでも同じ情報が得られます。 もし SUPER 権限があるなら、全てのスレッドがみれます。 しかし権限がないなら、自分のスレッドしか見れません。 See section KILL 構文. (SUPERは4.0.2以上。4.0.2未満では PROCESS権限があるだけで全てのスレッドが見れた) FULL オプションを使用しない場合、各クエリの最初の100文字だけが表示 されます。

Starting from 4.0.12, MySQL reports the hostname for TCP/IP connections as hostname:client_port to make it easier to find out which client is doing what.

This command is very useful if you get the 'too many connections' error message and want to find out what's going on. MySQL reserves one extra connection for a client with the SUPER privilege to ensure that you should always be able to login and check the system (assuming you are not giving this privilege to all your users).

Some states commonly seen in mysqladmin processlist

Most states are very quick operations. If threads last in any of these states for many seconds, there may be a problem around that needs to be investigated.

There are some other states that are not mentioned previously, but most of these are only useful to find bugs in mysqld.

SHOW GRANTS

SHOW GRANTS FOR user はユーザの許可を複製するために発行する必要があ る grant コマンドをリストします。

mysql> SHOW GRANTS FOR root@localhost;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+

To list grants for the current session one may use CURRENT_USER() function (new in version 4.0.6) to find out what user the session was authentificated as. See section その他の関数.

SHOW CREATE TABLE

Shows a CREATE TABLE statement that will create the given table:

mysql> SHOW CREATE TABLE t\G
*************************** 1. row ***************************
       Table: t
Create Table: CREATE TABLE t (
  id int(11) default NULL auto_increment,
  s char(60) default NULL,
  PRIMARY KEY (id)
) TYPE=MyISAM

SHOW CREATE TABLE will quote table and column names according to SQL_QUOTE_SHOW_CREATE option. section SET 構文.

SHOW WARNINGS | ERRORS

SHOW WARNINGS [LIMIT #]
SHOW ERRORS [LIMIT #]

This command is implemented in MySQL 4.1.0.

It shows the errors, warnings and notes that one got for the last command. The errors/warnings are reset for each new command that uses a table.

The MySQL server sends back the total number of warnings and errors you got for the last commend; This can be retrieved by calling mysql_warning_count().

Up to max_error_count messages are stored (Global and thread specific variable).

You can retrieve the number of errors from @error_count and warnings from @warning_count.

SHOW WARNINGS shows all errors, warnings and notes you got for the last command while SHOW ERRORS only shows you the errors.

mysql> DROP TABLE IF EXISTS no_such_table;
mysql> SHOW WARNINGS;

+-------+------+-------------------------------+
| Level | Code | Message                       |
+-------+------+-------------------------------+
| Note  | 1051 | Unknown table 'no_such_table' |
+-------+------+-------------------------------+

SHOW TABLE TYPES

SHOW TABLE TYPES

This command is implemented in MySQL 4.1.0.

SHOW TABLE TYPES shows you status information about the table types. This is particulary useful for checking if a table type is supported; or to see what is the default table type is.

mysql> SHOW TABLE TYPES;

+--------+---------+-----------------------------------------------------------+
| Type   | Support | Comment                                                   |
+--------+---------+-----------------------------------------------------------+
| MyISAM | DEFAULT | Default type from 3.23 with great performance             |
| HEAP   | YES     | Hash based, stored in memory, useful for temporary tables |
| MERGE  | YES     | Collection of identical MyISAM tables                     |
| ISAM   | YES     | Obsolete table type; Is replaced by MyISAM                |
| InnoDB | YES     | Supports transactions, row-level locking and foreign keys |
| BDB    | NO      | Supports transactions and page-level locking              |
+--------+---------+-----------------------------------------------------------+
6 rows in set (0.00 sec)

The 'Support' option DEFAULT indicates whether the perticular table type is supported, and which is the default type. If the server is started with --default-table-type=InnoDB, then the InnoDB 'Support' field will have the value DEFAULT.

SHOW PRIVILEGES

SHOW PRIVILEGES

This command is implemented in MySQL 4.1.0.

SHOW PRIVILEGES shows the list of system privileges that the underlying MySQL server supports.

mysql> show privileges;
+------------+--------------------------+-------------------------------------------------------+
| Privilege  | Context                  | Comment                                               |
+------------+--------------------------+-------------------------------------------------------+
| Select     | Tables                   | To retrieve rows from table                           |
| Insert     | Tables                   | To insert data into tables                            |
| Update     | Tables                   | To update existing rows                               |
| Delete     | Tables                   | To delete existing rows                               |
| Index      | Tables                   | To create or drop indexes                             |
| Alter      | Tables                   | To alter the table                                    |
| Create     | Databases,Tables,Indexes | To create new databases and tables                    |
| Drop       | Databases,Tables         | To drop databases and tables                          |
| Grant      | Databases,Tables         | To give to other users those privileges you possess   |
| References | Databases,Tables         | To have references on tables                          |
| Reload     | Server Admin             | To reload or refresh tables, logs and privileges      |
| Shutdown   | Server Admin             | To shutdown the server                                |
| Process    | Server Admin             | To view the plain text of currently executing queries |
| File       | File access on server    | To read and write files on the server                 |
+------------+--------------------------+-------------------------------------------------------+
14 rows in set (0.00 sec)

MySQL Localisation and International Usage

データとソートに使用されるキャラクター・セット

デフォルトでは、MySQL は スウェーデン語/フィンランド語に一致する ISO8859-1 (Latin1) キャラクター・セットをソートに使用します。これは USA と西 ヨーロッパに適したキャラクター・セットです。

All standard MySQL binaries are compiled with --with-extra-charsets=complex. This will add code to all standard programs to be able to handle latin1 and all multi-byte character sets within the binary. Other character sets will be loaded from a character-set definition file when needed.

キャラクター・セットは名前として許される文字と、ORDER BYGROUP BY コマンドによってソートされる方法を決定します。 キャラクターセットは、名前として使用してもよい文字と SELECT 構文中の ORDER BYGROUP BY コマンドを用いたソート方法を決定します。

You can change the character set with the --default-character-set option when you start the server. The character sets available depend on the --with-charset=charset and --with-extra-charsets= list-of-charset | complex | all options to configure, and the character set configuration files listed in `SHAREDIR/charsets/Index'. See section 典型的な configure オプション.

もし MySQL が実行中にキャラクター・セットを変更するならば、 (これはソートの順番も変わります)、全てのテーブルに対して myisamchk -r -q --set-character-set=charset を実行しなくてはなりません。 インデックスがただしい順番で並んでいないかもしれないからです。

クライアントが MySQL サーバに接続したとき、サーバは使用している デフォルトのキャラクター・セットをクライアントに送ります。 これを受け取ったクライアントは、キャラクター・セットを切り替えます。

SQL クエリの文字列をエスケープする場合には、 mysql_real_escape_string() を 使用するべきです。 mysql_real_escape_string() は、最初のパラメタとして MySQL へのコネクション・ハンドルを与える以外は、 古い mysql_escape_string() 関数と同じです。

もしクライアントがサーバがインストールされているところ(パス)とは違う パスでコンパイルされていて、 MySQL をコンフィギャしたユーザーが すべてのキャラクター・セットを MySQL バイナリに含めていない場合には、 どこに必要とされるキャラクター・セットの追加情報があるかを、クライアントに 教えなくてはなりません。もしサーバとクライアントが違うキャラクター・セットで動作し ているならば。

これは MySQL オプションファイルに次のように記述することで可能です:

[client]
character-sets-dir=/usr/local/mysql/share/mysql/charsets

ここで、パスはダイナミック MySQL キャラクター・セットが保存されている場所 です。

クライアントに、キャラクター・セットを強制することも可能です:

[client]
default-character-set=character-set-name

しかし通常はこれは不要です。

German character set

To get German sorting order, you should start mysqld with --default-character-set=latin1_de. This will give you the following characteristics.

When sorting and comparing string's the following mapping is done on the strings before doing the comparison:

a  ->  ae
o  ->  oe
u  ->  ue
s  ->  ss

All accented characters, are converted to their un-accented uppercase counterpart. All letters are converted to uppercase.

When comparing strings with LIKE the one -> two character mapping is not done. All letters are converted to uppercase. Accent are removed from all letters except: , , , , and .

Non-English Error Messages

mysqld は次の言語でエラーメッセージを提供できます: チェコ語, デンマーク語, オランダ語, 英語(デフォルト), Estonia, フランス語, ドイツ語, ギリシャ語, ハンガリー語, イタリア語, 日本語, 韓国語, ノルウェー語, 新ノルウェー語,ポーランド語, ポルトガル語, スペイン語そしてスウェーデン語。

ある言語で mysqld を開始するためには --language=lang また は -L lang スイッチの一つを使います:

shell> mysqld --language=swedish

or:

shell> mysqld --language=/usr/local/share/swedish

言語名は全て小文字であることに注意してください。

言語ファイルは(デフォルトでは)次の場所にあります。 `mysql_base_dir/share/LANGUAGE/'.

エラーメッセージファイルを更新したい場合は、 `errmsg.txt' ファイルを編集し、 `errmsg.sys' ファイルを作成するために以下のように実行します:

shell> comp_err errmsg.txt errmsg.sys

もし MySQL を新しいものにアップグレードしたなら、以前修正した部分と同じ ところに、 新しい `errmsg.txt' ファイルに修正をほどこしてください。

新しいキャラクター・セットの追加

他のキャラクタ・セットを MySQL に追加するには、 以下の手順で行ないます。

そのキャラクター・セットが、simple か complex かを決めます。 もしそのキャラクター・セットがソートを行なうために特別な文字参照の ルーチンを必要としなくて、マルチバイト文字のサポートも必要としないのであれば、 そのキャラクター・セットは simple です。 もしどちらかの特徴を必要とするのであれば、それは complex です。

例えば、latin1danish は simple キャラクター・セットで、 big5czech は complex キャラクター・セットです。

以下のセクションでは、あなたがキャラクター・セットに MYSET という名前を つけていると仮定します。

For a simple character set do the following:

  1. MYSET を `sql/share/charsets/Index' ファイルの最後に追加。 一意な番号を与えます。
  2. `sql/share/charsets/MYSET.conf' ファイルを作成. (`sql/share/charsets/latin1.conf' をベースにしてよいでしょう). The syntax for the file very simple: See section The Character Definition Arrays.
  3. Add the character set name to the CHARSETS_AVAILABLE and COMPILED_CHARSETS lists in configure.in.
  4. Reconfigure, recompile, and test.

For a complex character set do the following:

  1. `strings/ctype-MYSET.c' ファイルを MySQL のソースディレクトリ以下 に作成します。
  2. MYSET を `sql/share/charsets/Index' ファイルの最後に追加。 一意な番号を与えます。
  3. 必要な定義されるものを調べるために、既存の `ctype-*.c' ファイルの一つを見てく ださい。このファイル中で使用する配列の名前は、 ctype_MYSET, to_lower_MYSET のようにしなければいけないことに注意し てください。 This corresponds to the arrays in the simple character set. See section The Character Definition Arrays. For a complex character set
  4. `ctype-*.c' ファイルの先頭付近に、以下のようなコメントを書きます:
    /*
     * This comment is parsed by configure to create ctype.c,
     * so don't change it unless you know what you are doing.
     *
     * .configure. number_MYSET=MYNUMBER
     * .configure. strxfrm_multiply_MYSET=N
     * .configure. mbmaxlen_MYSET=N
     */
    
    configure プログラムは、MySQL ライブラリに自動的に キャラクター・セットを含めるために、このコメントを使用します。 The strxfrm_multiply and mbmaxlen lines will be explained in the following sections. Only include these if you need the string collating functions or the multi-byte character set functions, respectively.
  5. 以下の関数を作成しなくてはなりません: See section String Collating Support.
  6. キャラクター・セット名を、configure.in 中の CHARSETS_AVAILABLECOMPILED_CHARSETS に追加します。
  7. Reconfigure, recompile, and test.

The file `sql/share/charsets/README' includes some more instructions.

If you want to have the character set included in the MySQL distribution, mail a patch to internals@lists.mysql.com.

The Character Definition Arrays

to_lower[]to_upper[] は、それぞれのキャラクターセットに於ける 大文字、小文字の対応を定義した、単純な配列です。 例えば:

to_lower['A'] should contain 'a'
to_upper['a'] should contain 'A'

sort_order[] は文字がどのように比較され、ソートされるべきかのマップです。 本当に多くの(しかし全てのキャラクタセットではありません)セットでは、 これは to_upper[] と同じです (ケース非依存ソート)。 MySQL は sort_order[character] の値を元に文字をソートします。 MySQL will sort characters based on the value of sort_order[character]. For more complicated sorting rules, see the discussion of string collating below. See section String Collating Support.

ctype[] は各文字を説明するビットの配列で、1かたまりのビット列が1文字を定 義します。 ( to_lower[], to_upper[],sort_order[]は、文字の値でインデッ クスされますが、 ctype[]は文字の値+1 でインデックスされます。

これは EOF を操作するためにずいぶん前から使われているので、この方法を使用してい ます。) `m_ctype.h' に次のビットマスクの定義を見ることができます:

#define _U      01      /* Uppercase */
#define _L      02      /* Lowercase */
#define _N      04      /* Numeral (digit) */
#define _S      010     /* Spacing character */
#define _P      020     /* Punctuation */
#define _C      040     /* Control character */
#define _B      0100    /* Blank */
#define _X      0200    /* heXadecimal digit */

それぞれの文字に対する ctype[] は、文字を確定するために ビット列と組になっていなければなりません。 たとえば、'A' は大文字定義 (_U) と 16進定義 (_X) 両方ともに 属するので、ctype['A'+1] は以下の値を含まなくてはなりません:

_U + _X = 01 + 0200 = 0201

String Collating Support

If the sorting rules for your language are too complex to be handled with the simple sort_order[] table, you need to use the string collating functions.

Right now the best documentation on this is the character sets that are already implemented. Look at the big5, czech, gbk, sjis, and tis160 character sets for examples.

You must specify the strxfrm_multiply_MYSET=N value in the special comment at the top of the file. N should be set to the maximum ratio the strings may grow during my_strxfrm_MYSET (it must be a positive integer).

マルチバイト文字のサポート

If your want to add support for a new character set that includes multi-byte characters, you need to use the multi-byte character functions.

Right now the best documentation on this is the character sets that are already implemented. Look at the euc_kr, gb2312, gbk, sjis, and ujis character sets for examples. These are implemented in the `ctype-'charset'.c' files in the `strings' directory.

You must specify the mbmaxlen_MYSET=N value in the special comment at the top of the source file. N should be set to the size in bytes of the largest character in the set.

Problems With Character Sets

If you try to use a character set that is not compiled into your binary, you can run into a couple of different problems:

For MyISAM tables, you can check the character set name and number for a table with myisamchk -dvv table_name.

MySQL サーバー サイド の スクリプトとユーティリティ

Overview of the Server-Side Scripts and Utilities

All MySQL programs take many different options. However, every MySQL program provides a --help option that you can use to get a full description of the program's different options. For example, try mysql --help.

You can override default options for all standard programs with an option file. section `my.cnf' オプションファイル.

The following list briefly describes the server-side MySQL programs:

myisamchk
Utility to describe, check, optimise, and repair MySQL tables. Because myisamchk has many functions, it is described in its own chapter. See section データベース管理.
make_binary_distribution
Makes a binary release of a compiled MySQL. This could be sent by FTP to `/pub/mysql/Incoming' on support.mysql.com for the convenience of other MySQL users.
mysqlbug
The MySQL bug report script. This script should always be used when filing a bug report to the MySQL list.
mysqld
The SQL daemon. This should always be running.
mysql_install_db
Creates the MySQL grant tables with default privileges. This is usually executed only once, when first installing MySQL on a system.

safe_mysqld, The Wrapper Around mysqld

Note that in MySQL 4.0 safe_mysqld was renamed to mysqld_safe.

safe_mysqld is the recommended way to start a mysqld daemon on Unix. safe_mysqld adds some safety features such as restarting the server when an error occurs and logging run-time information to a log file.

If you don't use --mysqld=# or --mysqld-version=# safe_mysqld will use an executable named mysqld-max if it exists. If not, safe_mysqld will start mysqld. This makes it very easy to test to use mysqld-max instead of mysqld; just copy mysqld-max to where you have mysqld and it will be used.

Normally one should never edit the safe_mysqld script, but instead put the options to safe_mysqld in the [safe_mysqld] section in the `my.cnf' file. safe_mysqld will read all options from the [mysqld], [server] and [safe_mysqld] sections from the option files. See section `my.cnf' オプションファイル.

Note that all options on the command-line to safe_mysqld are passed to mysqld. If you wants to use any options in safe_mysqld that mysqld doesn't support, you must specify these in the option file.

Most of the options to safe_mysqld are the same as the options to mysqld. See section mysqld コマンド行オプション.

safe_mysqld supports the following options:

--basedir=path
--core-file-size=#
Size of the core file mysqld should be able to create. Passed to ulimit -c.
--datadir=path
--defaults-extra-file=path
--defaults-file=path
--err-log=path (this is marked obsolete in 4.0; Use --log-error instead)
--log-error=path
Write the error log to the above file. See section The Error Log.
--ledir=path
Path to mysqld
--log=path
--mysqld=mysqld-version
Name of the mysqld version in the ledir directory you want to start.
--mysqld-version=version
Similar to --mysqld= but here you only give the suffix for mysqld. For example if you use --mysqld-version=max, safe_mysqld will start the ledir/mysqld-max version. If the argument to --mysqld-version is empty, ledir/mysqld will be used.
--no-defaults
--open-files-limit=#
Number of files mysqld should be able to open. Passed to ulimit -n. Note that you need to start safe_mysqld as root for this to work properly!
--pid-file=path
--port=#
--socket=path
--timezone=#
Set the timezone (the TZ) variable to the value of this parameter.
--user=#

The safe_mysqld script is written so that it normally is able to start a server that was installed from either a source or a binary version of MySQL, even if these install the server in slightly different locations. safe_mysqld expects one of these conditions to be true:

Because safe_mysqld will try to find the server and databases relative to its own working directory, you can install a binary distribution of MySQL anywhere, as long as you start safe_mysqld from the MySQL installation directory:

shell> cd mysql_installation_directory
shell> bin/safe_mysqld &

If safe_mysqld fails, even when invoked from the MySQL installation directory, you can modify it to use the path to mysqld and the pathname options that are correct for your system. Note that if you upgrade MySQL in the future, your modified version of safe_mysqld will be overwritten, so you should make a copy of your edited version that you can reinstall.

mysqld_multi, 複数の MySQL サーバーを管理するプログラム

mysqld_multi is meant for managing several mysqld processes that listen for connections on different Unix sockets and TCP/IP ports. このプログラムは、`my.cnf' ファイル (もしくは、--config-file=... で与えられたファイル)の [mysqld#] (ここで # は 1から始まる数字) と命名されたセクションを探します。 This number is referred to in the following discussion as the option group number, or GNR. Group numbers distinquish option groups from one another and are used as arguments to mysqld_multi to specify which servers you want to start, stop, or obtain status for. Options listed in these groups should be the same as you would use in the usual [mysqld] group used for starting mysqld. (See, for example, section MySQL の自動起動と自動停止.) However, for mysqld_multi, be sure that each group includes options for values such as the port, socket, etc., to be used for each individual mysqld process.

mysqld_multi is invoked using the following syntax:

Usage: mysqld_multi [OPTIONS] {start|stop|report} [GNR,GNR,GNR...]
か     mysqld_multi [OPTIONS] {start|stop|report} [GNR-GNR,GNR,GNR-GNR,...]

Each GNR represents an option group number. You can start, stop or report any GNR, or several of them at the same time. For an example of how you might set up an option file, use this command:

shell> mysqld_multi --example

The GNR values in the list can be comma-separated or combined with a dash; in the latter case, all the GNRs between GNR1-GNR2 will be affected. GNR が引数に与えられなかった場合は、 全てのグループが、起動、停止、レポートされます。 GNR のリストには空白は許されません。スペースの後ろは無視されます。

mysqld_multi は以下のオプションをサポートします:

--config-file=...
Alternative config file. Note: This will not affect this program's own options (group [mysqld_multi]), but only groups [mysqld#]. Without this option, everything will be searched from the ordinary `my.cnf' file.
--example
オプション例を表示.
--help
ヘルプを表示して終了
--log=...
ログファイル。フルパスで与えます。 もしファイルが存在している場合は、ログはファイルに追加されます。
--mysqladmin=...
サーバーの シャットダウン に使用する mysqladmin バイナリの指定
--mysqld=...
使用する mysqld バイナリの指定。 safe_mysqld をこのオプションに指定することも可能です。 指定されたオプションは mysqld に渡されます。 Just make sure you have mysqld in your environment variable PATH or fix safe_mysqld.
--no-log
ログをログファイルではなく標準出力に書きだします。 デフォルトでは、ログファイルに書き込むモードです。
--password=...
mysqladmin で使用するユーザーのパスワード.
--tcp-ip
Connect to the MySQL server(s) via the TCP/IP port instead of the Unix socket. This affects stopping and reporting. If a socket file is missing, the server may still be running, but can be accessed only via the TCP/IP port. By default, connections are made using the Unix socket.
--user=...
mysqladmin で使用する MySQL ユーザー.
--version
バージョンを表示して終了.

Some notes about mysqld_multi:

See section 同一マシン上に複数の MySQL サーバーを走らせる.

This is an example of the config file on behalf of mysqld_multi.

# This file should probably be in your home dir (~/.my.cnf) or /etc/my.cnf
# Version 2.1 by Jani Tolonen

[mysqld_multi]
mysqld     = /usr/local/bin/safe_mysqld
mysqladmin = /usr/local/bin/mysqladmin
user       = multi_admin
password   = multipass

[mysqld2]
socket     = /tmp/mysql.sock2
port       = 3307
pid-file   = /usr/local/mysql/var2/hostname.pid2
datadir    = /usr/local/mysql/var2
language   = /usr/local/share/mysql/english
user       = john

[mysqld3]
socket     = /tmp/mysql.sock3
port       = 3308
pid-file   = /usr/local/mysql/var3/hostname.pid3
datadir    = /usr/local/mysql/var3
language   = /usr/local/share/mysql/swedish
user       = monty

[mysqld4]
socket     = /tmp/mysql.sock4
port       = 3309
pid-file   = /usr/local/mysql/var4/hostname.pid4
datadir    = /usr/local/mysql/var4
language   = /usr/local/share/mysql/estonia
user       = tonu

[mysqld6]
socket     = /tmp/mysql.sock6
port       = 3311
pid-file   = /usr/local/mysql/var6/hostname.pid6
datadir    = /usr/local/mysql/var6
language   = /usr/local/share/mysql/japanese
user       = jani

See section `my.cnf' オプションファイル.

myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ

myisampack is used to compress MyISAM tables, and pack_isam is used to compress ISAM tables. Because ISAM tables are deprecated, we will only discuss myisampack here, but everything said about myisampack should also be true for pack_isam.

myisampack はテーブル内の各項目を別々に圧縮するように働きます。展開のため の情報は、テーブルがオープンされた時にメモリに読まれます。これは、正確に1レコー ドだけを展開する必要があるような、個々のレコードへのアクセス時にとても良 い性能を与えます。MSDOS 上の Stacker 使用時のように、ディスクブロックは そんなに大きくありません。 通常、myisampack はデータファイルを 40〜70% にパックします。

MySQL は圧縮されたテーブルでメモリマップ (mmap()) を使用します。 mmap() が働かない場合は、通常のファイルの読み書きを使用します。

Please note the following:

myisampack is invoked like this:

shell> myisampack [options] filename ...

それぞれのファイル名はインデックスファイル(`.MYI')の名前です。 もしデータディレクトリにカレントディレクトリを移動していないなら、 ファイルのパスを指定しなくてはなりません。`.MYI' 拡張子は 省略することが可能です。

myisampack は以下のオプションをサポートします:

-b, --backup
tbl_name.OLD としてバックアップを作成します.
-#, --debug=debug_options
デバック出力。debug_options'd:t:o,filename'.
-f, --force
一時ファイルが存在していようが、サイズが大きくなろうが、強制的にテーブルを パックします。 myisampack はテーブルを圧縮している間、 一時ファイルを `tbl_name.TMD' という名前で作成します。 もし myisampack を途中で kill した場合、 `.TMD' ファイルが消されて いない事があります。通常、myisampack`tbl_name.TMD' ファイルが 既に存在する場合はエラーで終了します。 --force を使用すると、 myisampack はそのような場合でもテーブルをパックします。
-?, --help
ヘルプメッセージを出力して終了。
-j big_tbl_name, --join=big_tbl_name
全てのテーブルをコマンドラインで指定した big_tbl_name 一つに まとめます。結合される全てのテーブル定義は同じでなければなりません (同じ項目名、同じ項目型、同じインデックス、等)
-p #, --packlength=#
Specify the record length storage size, in bytes. The value should be 1, 2, or 3. (myisampack stores all rows with length pointers of 1, 2, or 3 bytes. In most normal cases, myisampack can determine the right length value before it begins packing the file, but it may notice during the packing process that it could have used a shorter length. In this case, myisampack will print a note that the next time you pack the same file, you could use a shorter record length.)
-s, --silent
Silent mode. Write output only when errors occur.
-t, --test
Don't actually pack table, just test packing it.
-T dir_name, --tmp_dir=dir_name
Use the named directory as the location in which to write the temporary table.
-v, --verbose
Verbose mode. Write information about progress and packing result.
-V, --version
Display version information and exit.
-w, --wait
Wait and retry if table is in use. If the mysqld server was invoked with the --skip-external-locking option, it is not a good idea to invoke myisampack if the table might be updated during the packing process.

The sequence of commands shown here illustrates a typical table compression session:

shell> ls -l station.*
-rw-rw-r--   1 monty    my         994128 Apr 17 19:00 station.MYD
-rw-rw-r--   1 monty    my          53248 Apr 17 19:00 station.MYI
-rw-rw-r--   1 monty    my           5767 Apr 17 19:00 station.frm

shell> myisamchk -dvv station

MyISAM file:     station
Isam-version:  2
Creation time: 1996-03-13 10:08:58
Recover time:  1997-02-02  3:06:43
Data records:              1192  Deleted blocks:              0
Datafile: Parts:           1192  Deleted data:                0
Datafile pointer (bytes):     2  Keyfile pointer (bytes):     2
Max datafile length:   54657023  Max keyfile length:   33554431
Recordlength:               834
Record format: Fixed length

table description:
Key Start Len Index   Type                       Root  Blocksize    Rec/key
1   2     4   unique  unsigned long              1024       1024          1
2   32    30  multip. text                      10240       1024          1

Field Start Length Type
1     1     1
2     2     4
3     6     4
4     10    1
5     11    20
6     31    1
7     32    30
8     62    35
9     97    35
10    132   35
11    167   4
12    171   16
13    187   35
14    222   4
15    226   16
16    242   20
17    262   20
18    282   20
19    302   30
20    332   4
21    336   4
22    340   1
23    341   8
24    349   8
25    357   8
26    365   2
27    367   2
28    369   4
29    373   4
30    377   1
31    378   2
32    380   8
33    388   4
34    392   4
35    396   4
36    400   4
37    404   1
38    405   4
39    409   4
40    413   4
41    417   4
42    421   4
43    425   4
44    429   20
45    449   30
46    479   1
47    480   1
48    481   79
49    560   79
50    639   79
51    718   79
52    797   8
53    805   1
54    806   1
55    807   20
56    827   4
57    831   4

shell> myisampack station.MYI
Compressing station.MYI: (1192 records)
- Calculating statistics

normal:     20  empty-space:      16  empty-zero:        12  empty-fill:  11
pre-space:   0  end-space:        12  table-lookups:      5  zero:         7
Original trees:  57  After join: 17
- Compressing file
87.14%

shell> ls -l station.*
-rw-rw-r--   1 monty    my         127874 Apr 17 19:00 station.MYD
-rw-rw-r--   1 monty    my          55296 Apr 17 19:04 station.MYI
-rw-rw-r--   1 monty    my           5767 Apr 17 19:00 station.frm

shell> myisamchk -dvv station

MyISAM file:     station
Isam-version:  2
Creation time: 1996-03-13 10:08:58
Recover time:  1997-04-17 19:04:26
Data records:              1192  Deleted blocks:              0
Datafile: Parts:           1192  Deleted data:                0
Datafilepointer (bytes):      3  Keyfile pointer (bytes):     1
Max datafile length:   16777215  Max keyfile length:     131071
Recordlength:               834
Record format: Compressed

table description:
Key Start Len Index   Type                       Root  Blocksize    Rec/key
1   2     4   unique  unsigned long             10240       1024          1
2   32    30  multip. text                      54272       1024          1

Field Start Length Type                         Huff tree  Bits
1     1     1      constant                             1     0
2     2     4      zerofill(1)                          2     9
3     6     4      no zeros, zerofill(1)                2     9
4     10    1                                           3     9
5     11    20     table-lookup                         4     0
6     31    1                                           3     9
7     32    30     no endspace, not_always              5     9
8     62    35     no endspace, not_always, no empty    6     9
9     97    35     no empty                             7     9
10    132   35     no endspace, not_always, no empty    6     9
11    167   4      zerofill(1)                          2     9
12    171   16     no endspace, not_always, no empty    5     9
13    187   35     no endspace, not_always, no empty    6     9
14    222   4      zerofill(1)                          2     9
15    226   16     no endspace, not_always, no empty    5     9
16    242   20     no endspace, not_always              8     9
17    262   20     no endspace, no empty                8     9
18    282   20     no endspace, no empty                5     9
19    302   30     no endspace, no empty                6     9
20    332   4      always zero                          2     9
21    336   4      always zero                          2     9
22    340   1                                           3     9
23    341   8      table-lookup                         9     0
24    349   8      table-lookup                        10     0
25    357   8      always zero                          2     9
26    365   2                                           2     9
27    367   2      no zeros, zerofill(1)                2     9
28    369   4      no zeros, zerofill(1)                2     9
29    373   4      table-lookup                        11     0
30    377   1                                           3     9
31    378   2      no zeros, zerofill(1)                2     9
32    380   8      no zeros                             2     9
33    388   4      always zero                          2     9
34    392   4      table-lookup                        12     0
35    396   4      no zeros, zerofill(1)               13     9
36    400   4      no zeros, zerofill(1)                2     9
37    404   1                                           2     9
38    405   4      no zeros                             2     9
39    409   4      always zero                          2     9
40    413   4      no zeros                             2     9
41    417   4      always zero                          2     9
42    421   4      no zeros                             2     9
43    425   4      always zero                          2     9
44    429   20     no empty                             3     9
45    449   30     no empty                             3     9
46    479   1                                          14     4
47    480   1                                          14     4
48    481   79     no endspace, no empty               15     9
49    560   79     no empty                             2     9
50    639   79     no empty                             2     9
51    718   79     no endspace                         16     9
52    797   8      no empty                             2     9
53    805   1                                          17     1
54    806   1                                           3     9
55    807   20     no empty                             3     9
56    827   4      no zeros, zerofill(2)                2     9
57    831   4      no zeros, zerofill(1)                2     9

The information printed by myisampack is described here:

normal
The number of columns for which no extra packing is used.
empty-space
The number of columns containing values that are only spaces; these will occupy 1 bit.
empty-zero
The number of columns containing values that are only binary 0's; these will occupy 1 bit.
empty-fill
The number of integer columns that don't occupy the full byte range of their type; these are changed to a smaller type (for example, an INTEGER column may be changed to MEDIUMINT).
pre-space
The number of decimal columns that are stored with leading spaces. In this case, each value will contain a count for the number of leading spaces.
end-space
The number of columns that have a lot of trailing spaces. In this case, each value will contain a count for the number of trailing spaces.
table-lookup
The column had only a small number of different values, which were converted to an ENUM before Huffman compression.
zero
The number of columns for which all values are zero.
Original trees
The initial number of Huffman trees.
After join
The number of distinct Huffman trees left after joining trees to save some header space.

After a table has been compressed, myisamchk -dvv prints additional information about each field:

Type
The field type may contain the following descriptors:
constant
All rows have the same value.
no endspace
Don't store endspace.
no endspace, not_always
Don't store endspace and don't do end space compression for all values.
no endspace, no empty
Don't store endspace. Don't store empty values.
table-lookup
The column was converted to an ENUM.
zerofill(n)
The most significant n bytes in the value are always 0 and are not stored.
no zeros
Don't store zeros.
always zero
0 values are stored in 1 bit.
Huff tree
The Huffman tree associated with the field.
Bits
The number of bits used in the Huffman tree.

After you have run pack_isam/myisampack you must run isamchk/myisamchk to re-create the index. At this time you can also sort the index blocks and create statistics needed for the MySQL optimiser to work more efficiently:

myisamchk -rq --analyze --sort-index table_name.MYI
isamchk   -rq --analyze --sort-index table_name.ISM

After you have installed the packed table into the MySQL database directory you should do mysqladmin flush-tables to force mysqld to start using the new table.

If you want to unpack a packed table, you can do this with the --unpack option to isamchk or myisamchk.

mysqld-max, An Extended mysqld Server

mysqld-max is the MySQL server (mysqld) configured with the following configure options:

Option Comment
--with-server-suffix=-max Add a suffix to the mysqld version string.
--with-innodb Support for InnoDB tables.
--with-bdb Support for Berkeley DB (BDB) tables
CFLAGS=-DUSE_SYMDIR Symbolic links support for Windows.

You can find the MySQL-max binaries at http://www.mysql.com/downloads/mysql-max-3.23.html.

The Windows MySQL binary distributions includes both the standard mysqld.exe binary and the mysqld-max.exe binary. http://www.mysql.com/downloads/mysql-3.23.html. See section Windows への MySQL のインストール.

Note that as InnoDB and Berkeley DB are not available for all platforms, some of the Max binaries may not have support for both of these. You can check which table types are supported by doing the following query:

mysql> SHOW VARIABLES LIKE "have_%";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| have_bdb      | YES   |
| have_innodb   | NO    |
| have_isam     | YES   |
| have_raid     | NO    |
| have_openssl  | NO    |
+---------------+-------+

The meaning of the values are:

Value Meaning
YES The option is activated and usable.
NO MySQL is not compiled with support for this option.
DISABLED The xxxx option is disabled because one started mysqld with --skip-xxxx or because one didn't start mysqld with all needed options to enable the option. In this case the hostname.err file should contain a reason for why the option is disabled.

Note: To be able to create InnoDB tables you must edit your startup options to include at least the innodb_data_file_path option. See section InnoDB 起動オプション.

To get better performance for BDB tables, you should add some configuration options for these too. See section BDB startup options.

safe_mysqld will automatically try to start any mysqld binary with the -max suffix. This makes it very easy to test out a another mysqld binary in an existing installation. Just run configure with the options you want and then install the new mysqld binary as mysqld-max in the same directory where your old mysqld binary is. See section safe_mysqld, The Wrapper Around mysqld.

The mysqld-max RPM uses the above mentioned safe_mysqld feature. It just installs the mysqld-max executable and safe_mysqld will automatically use this executable when safe_mysqld is restarted.

The following table shows which table types our standard MySQL-Max binaries includes:

System BDB InnoDB
AIX 4.3 N Y
HP-UX 11.0 N Y
Linux-Alpha N Y
Linux-Intel Y Y
Linux-IA64 N Y
Solaris-Intel N Y
Solaris-SPARC Y Y
Caldera (SCO) OSR5 Y Y
UnixWare Y Y
Windows/NT Y Y

MySQL Client-Side Scripts and Utilities

Overview of the Client-Side Scripts and Utilities

All MySQL clients that communicate with the server using the mysqlclient library use the following environment variables:

Name Description
MYSQL_UNIX_PORT The default socket; used for connections to localhost
MYSQL_TCP_PORT The default TCP/IP port
MYSQL_PWD The default password
MYSQL_DEBUG Debug-trace options when debugging
TMPDIR The directory where temporary tables/files are created

Use of MYSQL_PWD is insecure. See section MySQL サーバーに接続.

The `mysql' client uses the file named in the MYSQL_HISTFILE environment variable to save the command-line history. The default value for the history file is `$HOME/.mysql_history', where $HOME is the value of the HOME environment variable. See section Environment Variables.

All MySQL programs take many different options. However, every MySQL program provides a --help option that you can use to get a full description of the program's different options. For example, try mysql --help.

You can override default options for all standard client programs with an option file. section `my.cnf' オプションファイル.

The following list briefly describes the client-side MySQL programs:

msql2mysql
A shell script that converts mSQL programs to MySQL. It doesn't handle all cases, but it gives a good start when converting.
mysqlaccess
A script that checks the access privileges for a host, user, and database combination.
mysqladmin
Utility for performing administrative operations, such as creating or dropping databases, reloading the grant tables, flushing tables to disk, and reopening log files. mysqladmin can also be used to retrieve version, process, and status information from the server. See section mysqladmin, MySQL サーバーの管理.
mysqldump
Dumps a MySQL database into a file as SQL statements or as tab-separated text files. Enhanced freeware originally by Igor Romanenko. See section mysqldump, データベースとテーブルから、構造とデータをダンプ.
mysqlimport
Imports text files into their respective tables using LOAD DATA INFILE. See section mysqlimport, テキストファイルからデータを取り込む.
mysqlshow
Displays information about databases, tables, columns, and indexes.
replace
A utility program that is used by msql2mysql, but that has more general applicability as well. replace changes strings in place in files or on the standard input. Uses a finite state machine to match longer strings first. Can be used to swap strings. For example, this command swaps a and b in the given files:
shell> replace a b b a -- file1 file2 ...

mysql, コマンドラインツール

mysql はシンプルな SQL shell です(GNU readline を持っています). これは対話モードと、非対話モードを持っています。 対話モードで使用された場合、 クエリの結果は ASCII テーブルのフォーマットで与えられます。 非対話モードで使用された場合(例えばフィルターとして)、結果はタブ区切りの フォーマットで返ります。 (出力フォーマットはコマンドラインのオプションで変更できます) 以下のようにしてスクリプトを実行できます:

shell> mysql database < script.sql > output.tab

もしクライアントでメモリー不足の問題が出た場合、--quick オプションを 使用します! これは mysql に、結果セットを取得する際に、 mysql_store_result() ではなく mysql_use_result() を 使用させます。

mysql の使用はとても簡単です: mysql databasemysql --user=user_name --password=your_password d atabase のようにしてはじめます。 SQL 文を入力し、一文を `;', `\g' or `\G' で終え、 RETURN/ENTER を押します。

mysql は以下のオプションをサポートします:

-?, --help
help を表示して終了
-A, --no-auto-rehash
自動リハッシュをしない。 テーブルとフィールドの取得には 'rehash' を 使用しなくてはなりません。 これは mysql の起動を速くします。
--prompt=...
Set the mysql prompt to specified format.
-b, --no-beep
Turn off beep-on-error.
-B, --batch
結果をタブ区切り、1レコードは1行で出力します。 history ファイルは使用しません。
--character-sets-dir=...
Directory where character sets are located.
-C, --compress
サーバー・クライアント間の通信を圧縮します
-#, --debug[=...]
デバッグログ。 デフォルトは 'd:t:o,/tmp/mysql.trace'
-D, --database=...
使用するデータベース。 これは my.cnf ファイルが便利です
--default-character-set=...
Set the default character set.
-e, --execute=...
コマンドを実行して終了。 (Output like with --batch)
-E, --vertical
垂直にレコードを出力します。 このオプションを指定していなくても、 SQL 文を \G で終了した場合、同じように垂直に出力します。
-f, --force
SQL エラーがおきたとしても、処理を続けます
-g, --no-named-commands
Named commands are disabled. Use \* form only, or use named commands only in the beginning of a line ending with a semicolon (`;'). Since Version 10.9, the client now starts with this option enabled by default! With the -g option, long format commands will still work from the first line, however.
-G, --enable-named-commands
Named commands are enabled. Long format commands are allowed as well as shortened \* commands.
-i, --ignore-space
関数名の後ろについたスペースを無視します
-h, --host=...
指定したホストに接続します
-H, --html
結果を HTML フォーマットで返します
-X, --xml
Produce XML output.
-L, --skip-line-numbers
エラーの起きた行の番号を書きません。 これはエラーメッセージを含んだ結果を 比較する場合に便利です。
--no-pager
Disable pager and print to stdout. See interactive help (\h) also.
--no-tee
Disable outfile. See interactive help (\h) also.
-n, --unbuffered
それぞれのクエリ毎にバッファをフラッシュします
-N, --skip-column-names
結果に、フィールド名を書き出しません。
-O, --set-variable var=option
変数に値をセットします。 --help lists variables. Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own.
-o, --one-database
デフォルトのデータベースのみ更新します。 これは update ログファイルを 使用して更新する場合、他のデータベースの更新を避けたい時に便利です。
--pager[=...]
Output type. Default is your ENV variable PAGER. Valid pagers are less, more, cat [> filename], etc. See interactive help (\h) also. This option does not work in batch mode. Pager works only in Unix.
-p[password], --password[=...]
サーバーに接続する際のパスワード。 もしパスワードがコマンドラインに 指定されていなかった場合、tty 上でパスワードが問い合わされます。 -p を使用する場合、このオプションとパスワードの間には スペースが不要だということに注意してください。
-P port_num, --port=port_num
接続に使用する TCP/IP ポート番号
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-q, --quick
結果をキャッシュせず、一レコードづつ出力します。 これはもし出力を中止した場合、サーバーを遅くします。 ヒストリファイルは使用しません。
-r, --raw
エスケープ処理をしないで値を書き出します。 --batch とともに使用されます
--reconnect
If the connection is lost, automatically try to reconnect once to the server.
-s, --silent
静粛モード
-S --socket=...
接続に使用する ソケットファイル
-t --table
表の形式で出力します。 これは batch モード以外でのデフォルトです。
-T, --debug-info
Print some debug information at exit.
--tee=...
Append everything into outfile. See interactive help (\h) also. Does not work in batch mode.
-u, --user=#
ログインユーザー名
-U, --safe-updates[=#], --i-am-a-dummy[=#]
キーを使用する UPDATE and DELETE のみを行います。 これは後述します。 このオプションをもし my.cnf に書いている場合は、 --safe-updates=0 でこのオプションをリセットできます。
-v, --verbose
冗長出力。 (-v -v -v は表形式の出力を与える)
-V, --version
バージョンを表示して終了
-w, --wait
もし接続が落ちた場合、中断しないで、待って、再試行します。

You can also set the following variables with -O or --set-variable; please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own:

Variable Name Default Description
connect_timeout 0 Number of seconds before timeout connection.
max_allowed_packet 16777216 Max packetlength to send/receive from to server
net_buffer_length 16384 Buffer for TCP/IP and socket communication
select_limit 1000 Automatic limit for SELECT when using --i-am-a-dummy
max_join_size 1000000 Automatic limit for rows in a join when using --i-am-a-dummy.

If the mysql client loses connection to the server while sending it a query, it will immediately and automatically try to reconnect once to the server and send the query again. Note that even if it succeeds in reconnecting, as your first connection has ended, all your previous session objects are lost : temporary tables, user and session variables. Therefore, the above behaviour may be dangerous for you, like in this example where the server was shut down and restarted without you knowing it :

mysql> set @a=1;
Query OK, 0 rows affected (0.05 sec)

mysql> insert into t values(@a);
ERROR 2006: MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    1
Current database: test

Query OK, 1 row affected (1.30 sec)

mysql> select * from t;
+------+
| a    |
+------+
| NULL |
+------+
1 row in set (0.05 sec)

The @a user variable has been lost with the connection, and after the reconnection it is undefined. To protect from this risk, you can start the mysql client with the --disable-reconnect option.

もしコマンドラインで 'help' と打った場合、mysql はサポートする コマンドを表示します:

mysql> help

MySQL commands:
help    (\h)    Display this text.
?       (\h)    Synonym for `help'.
clear   (\c)    Clear command.
connect (\r)    Reconnect to the server.
                Optional arguments are db and host.
edit    (\e)    Edit command with $EDITOR.
ego     (\G)    Send command to mysql server,
                display result vertically.
exit    (\q)    Exit mysql. Same as quit.
go      (\g)    Send command to mysql server.
nopager (\n)    Disable pager, print to stdout.
notee   (\t)    Don't write into outfile.
pager   (\P)    Set PAGER [to_pager].
                Print the query results via PAGER.
print   (\p)    Print current command.
prompt  (\R)    Change your mysql prompt.
quit    (\q)    Quit mysql.
rehash  (\#)    Rebuild completion hash.
source  (\.)    Execute a SQL script file.
                Takes a file name as an argument.
status  (\s)    Get status information from the server.
tee     (\T)    Set outfile [to_outfile].
                Append everything into given outfile.
use     (\u)    Use another database.
                Takes database name as argument.

The pager command works only in Unix.

status コマンドは、今使用している 接続とサーバーについての情報をいくつか表示します。 もし --safe-updates モードで使用している場合、 status は あなたのクエリに影響する mysql 変数の値を表示します。

初心者に便利な起動オプション(MySQL バージョン 3.23.11 で導入されました)は、 --safe-updates あるいは --i-am-a-dummy です。 ( これは DELETE FROM table_nameWHERE 節を忘れて 実行しようとした場合のためにあります。) このオプションが使用されると、 mysql は接続時に MySQL サーバーに 以下のようなコマンドを送ります:

SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#,
    SQL_MAX_JOIN_SIZE=#max_join_size#"

ここで #select_limit##max_join_size# は変数で これらは mysql コマンドからセット可能です。 See section SET 構文.

この効果は:

Some useful hints about the mysql client:

Some data is much more readable when displayed vertically, instead of the usual horizontal box type output. For example longer text, which includes new lines, is often much easier to be read with vertical output.

mysql> SELECT * FROM mails WHERE LENGTH(txt) < 300 lIMIT 300,1\G
*************************** 1. row ***************************
  msg_nro: 3068
     date: 2000-03-01 23:29:50
time_zone: +0200
mail_from: Monty
    reply: monty@no.spam.com
  mail_to: "Thimble Smith" <tim@no.spam.com>
      sbj: UTF-8
      txt: >>>>> "Thimble" == Thimble Smith writes:

Thimble> Hi.  I think this is a good idea.  Is anyone familiar with UTF-8
Thimble> or Unicode? Otherwise, I'll put this on my TODO list and see what
Thimble> happens.

Yes, please do that.

Regards,
Monty
     file: inbox-jani-1
     hash: 190402944
1 row in set (0.09 sec)

For logging, you can use the tee option. The tee can be started with option --tee=..., or from the command-line interactively with command tee. All the data displayed on the screen will also be appended into a given file. This can be very useful for debugging purposes also. The tee can be disabled from the command-line with command notee. Executing tee again starts logging again. Without a parameter the previous file will be used. Note that tee will flush the results into the file after each command, just before the command-line appears again waiting for the next command.

Browsing, or searching the results in the interactive mode in Unix less, more, or any other similar program, is now possible with option --pager[=...]. Without argument, mysql client will look for environment variable PAGER and set pager to that. pager can be started from the interactive command-line with command pager and disabled with command nopager. The command takes an argument optionally and the pager will be set to that. Command pager can be called without an argument, but this requires that the option --pager was used, or the pager will default to stdout. pager works only in Unix, since it uses the popen() function, which doesn't exist in Windows. In Windows, the tee option can be used instead, although it may not be as handy as pager can be in some situations.

A few tips about pager:

You can also combine the two functions above; have the tee enabled, pager set to 'less' and you will be able to browse the results in unix 'less' and still have everything appended into a file the same time. The difference between Unix tee used with the pager and the mysql client in-built tee, is that the in-built tee works even if you don't have the Unix tee available. The in-built tee also logs everything that is printed on the screen, where the Unix tee used with pager doesn't log quite that much. Last, but not least, the interactive tee is more handy to switch on and off, when you want to log something into a file, but want to be able to turn the feature off sometimes.

From MySQL version 4.0.2 it is possible to change the prompt in the mysql command-line client.

You can use the following prompt options:
Option Description
\v mysqld version
\d database in use
\h host connected to
\p port connected on
\u username
\U full username@host
\\ `\'
\n new line break
\t tab
\ space
\_ space
\R military hour time (0-23)
\r standard hour time (1-12)
\m minutes
\y two digit year
\Y four digit year
\D full date format
\s seconds
\w day of the week in three letter format (Mon, Tue, ...)
\P am/pm
\o month in number format
\O month in three letter format (Jan, Feb, ...)
\c counter that counts up for each command you do

`\' followed by any other letter just becomes that letter.

You may set the prompt in the following places:

Environment Variable
You may set the MYSQL_PS1 environment variable to a prompt string. For example:
shell> export MYSQL_PS1="(\u@\h) [\d]> "
`my.cnf'
`.my.cnf'
You may set the prompt option in any MySQL configuration file, in the mysql group. For example:
[mysql]
prompt=(\u@\h) [\d]>\_
Command Line
You may set the --prompt option on the command line to mysql. For example:
shell> mysql --prompt="(\u@\h) [\d]> "

(user@host) [database]> 
Interactively
You may also use the prompt (or \R) command to change your prompt interactively. For example:
mysql> prompt (\u@\h) [\d]>\_
PROMPT set to '(\u@\h) [\d]>\_'
(user@host) [database]> 
(user@host) [database]> prompt
Returning to default PROMPT of mysql> 
mysql> 

mysqladmin, MySQL サーバーの管理

管理オペレーションを実行するためのユーティリティ。シンタックスは:

shell> mysqladmin [OPTIONS] command [command-option] command ...

mysqladmin --help によって、オプションの一覧を手にいれることができます。

現在の mysqladmin は以下のコマンドをサポートします:

create databasename
新しいデータベースの作成
drop databasename
データベースとテーブルの全削除。
extended-status
サーバーから拡張ステータスを取得。
flush-hosts
キャッシュされている全ホストをフラッシュ。
flush-logs
全てのログをフラッシュ
flush-tables
全てのテーブルをフラッシュ
flush-privileges
許可テーブルの再読み込み (reload と同じ)
kill id,id,...
mysql スレッドの kill.
password
Set a new password. 古いパスワードを New-password に変更
ping
mysqld が生きているかチェック
processlist
現在活動中の mysql スレッドを表示
reload
権限テーブルの再読み込み
refresh
全テーブルをフラッシュし、ログファイルを一度閉じて開きます。
shutdown
サーバーをダウンさせます。
slave-start
Start slave replication thread.
slave-stop
Stop slave replication thread.
status
サーバーから短いステータスを得ます。
variables
変数の表示
version
サーバーからバージョンを得ます。

全てのコマンドは、ユニークなプレフィックスで省略可能です。 例えば:

shell> mysqladmin proc stat
+----+-------+-----------+----+-------------+------+-------+------+
| Id | User  | Host      | db | Command     | Time | State | Info |
+----+-------+-----------+----+-------------+------+-------+------+
| 6  | monty | localhost |    | Processlist | 0    |       |      |
+----+-------+-----------+----+-------------+------+-------+------+
Uptime: 10077  Threads: 1  Questions: 9  Slow queries: 0
Opens: 6 Flush tables: 1  Open tables: 2
Memory in use: 1092K  Max memory used: 1116K

The mysqladmin status command result has the following columns:

Column Description
Uptime MySQL サーバーの起動秒数
Threads 稼働中のスレッド数 (clients).
Questions mysqld が開始してからのクライアントからのクエリ数
Slow queries long_query_time 秒より時間のかかったクエリの数 See section The Slow Query Log (3.23.28以上).
Opens mysqld が開いたテーブル数
Flush tables Number of flush ..., refresh, and reload commands.
Open tables 現在開かれているテーブルの数
Memory in use mysqld のコードによって直接割り当てられたメモリ (only available when MySQL is compiled with --with-debug=full).
Max memory used mysqld のコードによって直接割り当てられる最大メモリー量 (only available when MySQL is compiled with --with-debug=full).

If you do mysqladmin shutdown on a socket (in other words, on a the computer where mysqld is running), mysqladmin will wait until the MySQL pid-file is removed to ensure that the mysqld server has stopped properly.

Using mysqlcheck for Table Maintenance and Crash Recovery

Since MySQL version 3.23.38 you will be able to use a new checking and repairing tool for MyISAM tables. The difference to myisamchk is that mysqlcheck should be used when the mysqld server is running, where as myisamchk should be used when it is not. The benefit is that you no longer have to take the server down for checking or repairing your tables.

mysqlcheck uses MySQL server commands CHECK, REPAIR, ANALYZE and OPTIMIZE in a convenient way for the user.

There are three alternative ways to invoke mysqlcheck:

shell> mysqlcheck [OPTIONS] database [tables]
shell> mysqlcheck [OPTIONS] --databases DB1 [DB2 DB3...]
shell> mysqlcheck [OPTIONS] --all-databases

So it can be used in a similar way as mysqldump when it comes to what databases and tables you want to choose.

mysqlcheck does have a special feature compared to the other clients; the default behaviour, checking tables (-c), can be changed by renaming the binary. So if you want to have a tool that repairs tables by default, you should just copy mysqlcheck to your harddrive with a new name, mysqlrepair, or alternatively make a symbolic link to mysqlrepair and name the symbolic link as mysqlrepair. If you invoke mysqlrepair now, it will repair tables by default.

The names that you can use to change mysqlcheck default behaviour are here:

mysqlrepair:   The default option will be -r
mysqlanalyze:  The default option will be -a
mysqloptimize: The default option will be -o

The options available for mysqlcheck are listed here, please check what your version supports with mysqlcheck --help.

-A, --all-databases
Check all the databases. This will be same as --databases with all databases selected
-1, --all-in-1
Instead of making one query for each table, execute all queries in 1 query separately for each database. Table names will be in a comma separated list.
-a, --analyze
Analyse given tables.
--auto-repair
If a checked table is corrupted, automatically fix it. Repairing will be done after all tables have been checked, if corrupted ones were found.
-#, --debug=...
Output debug log. Often this is 'd:t:o,filename'
--character-sets-dir=...
Directory where character sets are
-c, --check
Check table for errors
-C, --check-only-changed
Check only tables that have changed since last check or haven't been closed properly.
--compress
Use compression in server/client protocol.
-?, --help
Display this help message and exit.
-B, --databases
To check several databases. Note the difference in usage; in this case no tables are given. All name arguments are regarded as database names.
--default-character-set=...
Set the default character set
-F, --fast
Check only tables that hasn't been closed properly
-f, --force
Continue even if we get an sql-error.
-e, --extended
If you are using this option with CHECK TABLE, it will ensure that the table is 100 percent consistent, but will take a long time. If you are using this option with REPAIR TABLE, it will run an extended repair on the table, which may not only take a long time to execute, but may produce a lot of garbage rows also!
-h, --host=...
Connect to host.
-m, --medium-check
Faster than extended-check, but only finds 99.99 percent of all errors. Should be good enough for most cases.
-o, --optimize
Optimise table
-p, --password[=...]
Password to use when connecting to server. If password is not given it's solicited on the tty.
-P port_num, --port=port_num
Port number to use for TCP/IP connections.
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-q, --quick
If you are using this option with CHECK TABLE, it prevents the check from scanning the rows to check for wrong links. This is the fastest check. If you are using this option with REPAIR TABLE, it will try to repair only the index tree. This is the fastest repair method for a table.
-r, --repair
Can fix almost anything except unique keys that aren't unique.
-s, --silent
Print only error messages.
-S, --socket=...
Socket file to use for connection.
--tables
Overrides option --databases (-B).
-u, --user=#
User for login if not current user.
-v, --verbose
Print info about the various stages.
-V, --version
Output version information and exit.

mysqldump, データベースとテーブルから、構造とデータをダンプ

データベース、あるいは、バックアップ、他のSQLサーバー(MySQL サーバであ る必要はない)へのデータを移動を目的としたデータのまとまり、これらをダンプする ためのユーティリティ。ダンプは、テーブルの作成のための SQL 文を含みます。

サーバでバックアップを行なう場合、mysqlhotcopy を代わりに使用するこ とを考慮すべきです。 See section mysqlhotcopy, Copying MySQL Databases and Tables.

shell> mysqldump [OPTIONS] database [tables]
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]

もしテーブルを指定せず、--databases--all-databases を 使用しなかったなら、データベースの全てのテーブルがダンプされます。

mysqldump --help によって、オプションの一覧を手にいれることができます。

もし mysqldump--quick--opt なしで実行するならば、 mysqldump は結果を表示する前に、結果をメモリに全てロードすることに 注意してください。 これは大きなデータベースをダンプする際に問題になるでしょう。

Note that if you are using a new copy of the mysqldump program and you are going to do a dump that will be read into a very old MySQL server, you should not use the --opt or -e options.

mysqldump は以下のオプションをサポートします:

--add-locks
Add LOCK TABLES before and UNLOCK TABLE after each table dump. (To get faster inserts into MySQL.)
--add-drop-table
Add a drop table before each create statement.
-A, --all-databases
Dump all the databases. This will be same as --databases with all databases selected.
-a, --all
Include all MySQL-specific create options.
--allow-keywords
Allow creation of column names that are keywords. This works by prefixing each column name with the table name.
-c, --complete-insert
Use complete insert statements (with column names).
-C, --compress
Compress all information between the client and the server if both support compression.
-B, --databases
To dump several databases. Note the difference in usage. In this case no tables are given. All name arguments are regarded as database names. USE db_name; will be included in the output before each new database.
--delayed
Insert rows with the INSERT DELAYED command.
-e, --extended-insert
Use the new multiline INSERT syntax. (Gives more compact and faster inserts statements.)
-#, --debug[=option_string]
Trace usage of the program (for debugging).
--help
Display a help message and exit.
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
These options are used with the -T option and have the same meaning as the corresponding clauses for LOAD DATA INFILE. See section LOAD DATA INFILE 構文.
-F, --flush-logs
Flush log file in the MySQL server before starting the dump.
-f, --force,
Continue even if we get a SQL error during a table dump.
-h, --host=..
Dump data from the MySQL server on the named host. The default host is localhost.
-l, --lock-tables.
Lock all tables before starting the dump. The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables. Please note that when dumping multiple databases, --lock-tables will lock tables for each database separately. So using this option will not guarantee your tables will be logically consistent between databases. Tables in different databases may be dumped in completely different states.
-K, --disable-keys
/*!40000 ALTER TABLE tb_name DISABLE KEYS */; and /*!40000 ALTER TABLE tb_name ENABLE KEYS */; will be put in the output. This will make loading the data into a MySQL 4.0 server faster as the indexes are created after all data are inserted.
-n, --no-create-db
CREATE DATABASE /*!32312 IF NOT EXISTS*/ db_name; will not be put in the output. The above line will be added otherwise, if a --databases or --all-databases option was given.
-t, --no-create-info
Don't write table creation information (the CREATE TABLE statement).
-d, --no-data
Don't write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!
--opt
Same as --quick --add-drop-table --add-locks --extended-insert --lock-tables. Should give you the fastest possible dump for reading into a MySQL server.
-pyour_pass, --password[=your_pass]
The password to use when connecting to the server. If you specify no `=your_pass' part, mysqldump you will be prompted for a password.
-P port_num, --port=port_num
Port number to use for TCP/IP connections.
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-q, --quick
Don't buffer query, dump directly to stdout. Uses mysql_use_result() to do this.
-Q, --quote-names
Quote table and column names within ``' characters.
-r, --result-file=...
Direct output to a given file. This option should be used in MSDOS, because it prevents new line `\n' from being converted to `\n\r' (new line + carriage return).
--single-transaction
This option issues a BEGIN SQL command before dumping data from server. It is mostly useful with InnoDB tables and READ_COMMITTED transaction isolation level, as in this mode it will dump the consistent state of the database at the time then BEGIN was issued without blocking any applications. When using this option you should keep in mind that only transactional tables will be dumped in a consistent state, e.g., any MyISAM or HEAP tables dumped while using this option may still change state. The --single-transaction option was added in version 4.0.2. This option is mutually exclusive with the --lock-tables option as LOCK TABLES already commits a previous transaction internally.
-S /path/to/socket, --socket=/path/to/socket
The socket file to use when connecting to localhost (which is the default host).
--tables
Overrides option --databases (-B).
-T, --tab=path-to-some-directory
Creates a table_name.sql file, that contains the SQL CREATE commands, and a table_name.txt file, that contains the data, for each give table. The format of the `.txt' file is made according to the --fields-xxx and --lines--xxx options. Note: This option only works if mysqldump is run on the same machine as the mysqld daemon, and the user/group that mysqld is running as (normally user mysql, group mysql) needs to have permission to create/write a file at the location you specify.
-u user_name, --user=user_name
The MySQL user name to use when connecting to the server. The default value is your Unix login name.
-O var=option, --set-variable var=option
Set the value of a variable. The possible variables are listed below. Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own.
-v, --verbose
Verbose mode. Print out more information on what the program does.
-V, --version
Print version information and exit.
-w, --where='where-condition'
Dump only selected records. Note that quotes are mandatory:
-X, --xml
Dumps a database as well formed XML
-x, --first-slave
Locks all tables across all databases.
"--where=user='jimf'" "-wuserid>1" "-wuserid<1"
-O net_buffer_length=#, where # < 16M
When creating multi-row-insert statements (as with option --extended-insert or --opt), mysqldump will create rows up to net_buffer_length length. If you increase this variable, you should also ensure that the max_allowed_packet variable in the MySQL server is bigger than the net_buffer_length.

The most normal use of mysqldump is probably for making a backup of whole databases. See section データベースのバックアップ.

mysqldump --opt database > backup-file.sql

You can read this back into MySQL with:

mysql database < backup-file.sql

or

mysql -e "source /patch-to-backup/backup-file.sql" database

However, it's also very useful to populate another MySQL server with information from a database:

mysqldump --opt database | mysql --host=remote-host -C database

It is possible to dump several databases with one command:

mysqldump --databases database1 [database2 ...] > my_databases.sql

If all the databases are wanted, one can use:

mysqldump --all-databases > all_databases.sql

mysqlhotcopy, Copying MySQL Databases and Tables

mysqlhotcopy is a Perl script that uses LOCK TABLES, FLUSH TABLES and cp or scp to quickly make a backup of a database. It's the fastest way to make a backup of the database or single tables, but it can only be run on the same machine where the database directories are.

mysqlhotcopy db_name [/path/to/new_directory]

mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory

mysqlhotcopy db_name./regex/

mysqlhotcopy supports the following options:

-?, --help
Display a help screen and exit
-u, --user=#
User for database login
-p, --password=#
Password to use when connecting to server
-P, --port=#
Port to use when connecting to local server
-S, --socket=#
Socket to use when connecting to local server
--allowold
Don't abort if target already exists (rename it _old)
--keepold
Don't delete previous (now renamed) target when done
--noindices
Don't include full index files in copy to make the backup smaller and faster The indexes can later be reconstructed with myisamchk -rq..
--method=#
Method for copy (cp or scp).
-q, --quiet
Be silent except for errors
--debug
Enable debug
-n, --dryrun
Report actions without doing them
--regexp=#
Copy all databases with names matching regexp
--suffix=#
Suffix for names of copied databases
--checkpoint=#
Insert checkpoint entry into specified db.table
--flushlog
Flush logs once all tables are locked.
--tmpdir=#
Temporary directory (instead of /tmp).

You can use perldoc mysqlhotcopy to get more complete documentation for mysqlhotcopy.

mysqlhotcopy reads the groups [client] and [mysqlhotcopy] from the option files.

To be able to execute mysqlhotcopy you need write access to the backup directory, the SELECT privilege for the tables you are about to copy and the MySQL RELOAD privilege (to be able to execute FLUSH TABLES).

mysqlimport, テキストファイルからデータを取り込む

mysqlimport は、LOAD DATA INFILE SQL 構文を、 コマンドラインインターフェースで提供します。 mysqlimport のオプションのほとんどが、 LOAD DATA INFILE への同じオプションに対応します。 See section LOAD DATA INFILE 構文.

mysqlimport の実行は以下のようにします:

shell> mysqlimport [options] database textfile1 [textfile2 ...]

mysqlimport は、コマンドラインの引数に与えられたファイル名の拡張子を取り、 拡張子を取った後の名前を、ファイルの内容を取り込むテーブルの名前とします。 例えば、`patient.txt', `patient.text', `patient' という ファイルは全て、patient とという名前のテーブルに取り込まれます。

mysqlimport は以下のオプションをサポートします:

-c, --columns=...
This option takes a comma-separated list of field names as an argument. The field list is used to create a proper LOAD DATA INFILE command, which is then passed to MySQL. See section LOAD DATA INFILE 構文.
-C, --compress
クライアントとサーバーの両方が圧縮をサポートしているなら、 クライアント・サーバー間でやり取りされる全ての情報を圧縮します。
-#, --debug[=option_string]
プログラムのトレース(デバッグ)
-d, --delete
テキストファイルを取り込む前にテーブルを空にします。
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
これらのオプションは、LOAD DATA INFILE の対応する文節と同じ意味になります See section LOAD DATA INFILE 構文.
-f, --force
エラーを無視します。例えば、テキストファイルを取り込むテーブルがない場合、 残りのファイルの処理に移ります。 --force がなければ、 テーブルがなければ mysqlimport は終了します。
--help
ヘルプを表示して終了。
-h host_name, --host=host_name
名前を指定された MySQL サーバーにデータを取り入れます。 デフォルトでは localhost.
-i, --ignore
--replace オプションの説明を見てください。
-l, --lock-tables
それぞれのテキストファイルを処理する前に、書き込まれる 全てのテーブルをロックします。 これは確実に、すべてのテーブルをサーバ上で同期させます。
-L, --local
クライアントからの入力ファイルを読みます。 デフォルトでは、localhost に接続した場合、テキストファイルは サーバー上にあると仮定されます。(localhost はデフォルト値)
-pyour_pass, --password[=your_pass]
サーバーに接続するときに使用するパスワード。 もし `=your_pass' のところにパスワードを書かなければ、 mysqlimport はパスワードのためのプロンプトをだします。
-P port_num, --port=port_num
ホストに接続するための TCP/IP ポート番号。 (これは localhost を除くホストへの接続に使用します。 localhost へは、Unix ソケットを使用します。)
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-r, --replace
--replace--ignore オプションは、 入力されているレコードのユニークキーの値が、 既に存在しているレコードのユニークキーの値と同じ場合、 その入力されているデータの取り扱いを決定します。 もし --replace が指定されているなら、 既にあるレコードは新しく読まれたレコードに置き換えられます。 もし --ignore が指定されているなら、 入力された物は無視されます。 どちらのオプションも指定していない場合、 キーの値が重なっているとエラーを発し、 テキストファイルの残りの部分は無視されます。
-s, --silent
静粛モード。エラーだけ出力します。
-S /path/to/socket, --socket=/path/to/socket
localhost への接続時に使用するソケットファイルを指定します。
-u user_name, --user=user_name
サーバーの接続に使用する MySQL ユーザー名の指定。 デフォルトは、Unix のログイン名。
-v, --verbose
冗長モード。プログラムがしている事について多く出力します。
-V, --version
バージョンを表示して終了。

Here is a sample run using mysqlimport:

$ mysql --version
mysql  Ver 9.33 Distrib 3.22.25, for pc-linux-gnu (i686)
$ uname -a
Linux xxx.com 2.2.5-15 #1 Mon Apr 19 22:21:09 EDT 1999 i586 unknown
$ mysql -e 'CREATE TABLE imptest(id INT, n VARCHAR(30))' test
$ ed
a
100     Max Sydow
101     Count Dracula
.
w imptest.txt
32
q
$ od -c imptest.txt
0000000   1   0   0  \t   M   a   x       S   y   d   o   w  \n   1   0
0000020   1  \t   C   o   u   n   t       D   r   a   c   u   l   a  \n
0000040
$ mysqlimport --local test imptest.txt
test.imptest: Records: 2  Deleted: 0  Skipped: 0  Warnings: 0
$ mysql -e 'SELECT * FROM imptest' test
+------+---------------+
| id   | n             |
+------+---------------+
|  100 | Max Sydow     |
|  101 | Count Dracula |
+------+---------------+

mysqlshow, Showing Databases, Tables, and Columns

mysqlshow can be used to quickly look at which databases exist, their tables, and the table's columns.

With the mysql program you can get the same information with the SHOW commands. See section SHOW 構文.

mysqlshow is invoked like this:

shell> mysqlshow [OPTIONS] [database [table [column]]]

Note that in newer MySQL versions, you only see those database/tables/columns for which you have some privileges.

If the last argument contains a shell or SQL wildcard (*, ?, % or _) then only what's matched by the wildcard is shown. If a database contains underscore(s), those should be escaped with backslash (some Unix shells will require two), in order to get tables / columns properly. '*' are converted into SQL '%' wildcard and '?' into SQL '_' wildcard. This may cause some confusion when you try to display the columns for a table with a _ as in this case mysqlshow only shows you the table names that match the pattern. This is easily fixed by adding an extra % last on the command-line (as a separate argument).

mysql_config, Get compile options for compiling clients

mysql_config provides you with useful information how to compile your MySQL client and connect it to MySQL.

mysql_config supports the following options:

--cflags
Compiler flags to find include files
--libs
Libs and options required to link with the MySQL client library.
--socket
The default socket name, defined when configuring MySQL.
--port
The default port number, defined when configuring MySQL.
--version
Version number and version for the MySQL distribution
--libmysqld-libs
Libs and options required to link with the MySQL embedded server.

If you execute mysql_config without any options it will print all options it supports plus the value of all options:

shell> mysql_config
sage: /usr/local/mysql/bin/mysql_config [OPTIONS]
Options:
        --cflags         [-I'/usr/local/mysql/include/mysql']
        --libs           [-L'/usr/local/mysql/lib/mysql' -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib -lssl -lcrypto]
        --socket         [/tmp/mysql.sock]
        --port           [3306]
        --version        [4.0.8-gamma]
        --libmysqld-libs [ -L'/usr/local/mysql/lib/mysql' -lmysqld -lpthread -lz -lcrypt -lnsl -lm  -lpthread  -lrt]

You can use this to compile a MySQL client by as follows:

CFG=/usr/local/mysql/bin/mysql_config
sh -c "gcc -o progname `$CFG --cflags` progname.c `$CFG --libs`"

perror, Explaining Error Codes

For most system errors MySQL will, in addition to a internal text message, also print the system error code in one of the following styles: message ... (errno: #) or message ... (Errcode: #).

You can find out what the error code means by either examining the documentation for your system or use the perror utility.

perror prints a description for a system error code, or an MyISAM/ISAM storage engine (table handler) error code.

perror is invoked like this:

shell> perror [OPTIONS] [ERRORCODE [ERRORCODE...]]

Example:

shell> perror 13 64
Error code  13:  Permission denied
Error code  64:  Machine is not on the network

Note that the error messages are mostly system dependent!

How to Run SQL Commands from a Text File

The mysql client typically is used interactively, like this:

shell> mysql database

However, it's also possible to put your SQL commands in a file and tell mysql to read its input from that file. To do so, create a text file `text_file' that contains the commands you wish to execute. Then invoke mysql as shown here:

shell> mysql database < text_file

You can also start your text file with a USE db_name statement. In this case, it is unnecessary to specify the database name on the command line:

shell> mysql < text_file

If you are already running mysql, you can execute a SQL script file using the source command:

mysql> source filename;

For more information about batch mode, section mysql のバッチモードでの使用.

The MySQL Log Files

MySQL has several different log files that can help you find out what's going on inside mysqld:

Log file Description
The error log Problems encountering starting, running or stopping mysqld.
The isam log Logs all changes to the ISAM tables. Used only for debugging the isam code.
The query log Established connections and executed queries.
The update log Deprecated: Stores all statements that changes data
The binary log Stores all statements that changes something. Used also for replication
The slow log Stores all queries that took more than long_query_time to execute or didn't use indexes.

All logs can be found in the mysqld data directory. You can force mysqld to reopen the log files (or in some cases switch to a new log) by executing FLUSH LOGS. See section FLUSH 構文.

The Error Log

The error log file contains information indicating when mysqld was started and stopped and also any critical errors found when running.

If mysqld dies unexpectedly and mysqld_safe needs to restart mysqld, mysqld_safe will write a restarted mysqld row in this file. This log also holds a warning if mysqld notices a table that needs to be automatically checked or repaired.

On some operating systems, the error log will contain a stack trace for where mysqld died. This can be used to find out where mysqld died. See section Using a Stack Trace.

Beginning with MySQL 4.0.10 you can specify where mysqld stores the error log file with the option --log-error[=filename]. If no file name is given mysqld will use mysql-data-dir/'hostname'.err on Unix and `\mysql\data\mysql.err' on windows. If you execute flush logs the old file will be prefixed with --old and mysqld will create a new empty log file.

In older MySQL versions the error log handling was done by mysqld_safe which redirected the error file to 'hostname'.err. One could change this file name with the option --err-log=filename.

If you don't specify --log-error or if you use the --console option the errors will be written to stderr (the terminal).

On windows the output is always done to the .err file if --console is not given.

The General Query Log

If you want to know what happens within mysqld, you should start it with --log[=file]. This will log all connections and queries to the log file (by default named `'hostname'.log'). This log can be very useful when you suspect an error in a client and want to know exactly what mysqld thought the client sent to it.

Older versions of the mysql.server script (from MySQL 3.23.4 to 3.23.8) pass safe_mysqld a --log option (enable general query log). If you need better performance when you start using MySQL in a production environment, you can remove the --log option from mysql.server or change it to --log-bin. See section The Binary Update Log バイナリ更新ログ (3.23.15以上).

The entries in this log are written as mysqld receives the questions. This may be different from the order in which the statements are executed. This is in contrast to the update log and the binary log which are written after the query is executed, but before any locks are released.

更新ログ

Note: the update log is replaced by the binary log. See section The Binary Update Log バイナリ更新ログ (3.23.15以上). With this you can do anything that you can do with the update log.

--log-update=file_nameオプションを使用してmysqldを起動すると、 データを更新した全てのSQLコマンドをログファイルに書きます。 もし file_name が与えられなかった場合は、ホスト名がデフォルトで使用されます。 もし file_name にディレクトリパスが含まれなかった場合は、 このファイルはデータディレクトリに書かれます。 もし file_name が拡張を持たなかったなら、mysqldfile_name.### という形でログファイルを作成します。 このログファイルはデータディレクトリにかかれ、 その名前は file_name.### という形式の名前になっています。 ###mysqladmin refreshmysqladmin flush-logs を実行す る度に、 あるいは FLUSH LOGS 構文を実行したり、サーバーをリスタートする度に 自動的に増える数字です。

Note: for the above scheme to work, you must not create your own files with the same filename as the update log + some extensions that may be regarded as a number, in the directory used by the update log!

もし --log-l オプションを使用した場合、ログファイルの名前は mysqld は全部のログを `hostname.log' に書き出します。 この場合、リスタートやりフレッシュを行っても新しくログファイルを作りません。 (一度クローズして再度オープンします。) In this case you can copy it (on Unix) by doing:

mv hostname.log hostname-old.log
mysqladmin flush-logs
cp hostname-old.log to-backup-directory
rm hostname-old.log

更新ログは、実際に更新されたデータのステートメントだけを書くため、きびきびと動作 します。 WHERE を使用した UPDATEDELETE で結果が得られなかった場合、 ログは書き出されません。 すでにセットされている値に、もう一度項目を更新するような UPDATE もスキッ プされます。

The update logging is done immediately after a query completes but before any locks are released or any commit is done. This ensures that the log will be logged in the execution order.

ログファイルの更新に従ってデータベースを更新したい場合は、次を行います (更新ログファイル名を `file_name.###' と仮定します):

shell> ls -1 -t -r file_name.[0-9]* | xargs cat | mysql

ls は全てのログファイルを正しく並べるために使用しています。

これは、クラッシュ後にバックアップした状態まで戻りたい、あるいは、 バックアップした後からクラッシュするまでの間のデータの更新を行いたい、 そんな場合に使えます。

The Binary Update Log バイナリ更新ログ (3.23.15以上)

The intention is that the binary log should replace the update log, so we recommend you to switch to this log format as soon as possible!

The binary log contains all information that is available in the update log in a more efficient format. It also contains information about how long each query took that updated the database. It doesn't contain queries that don't modify any data. If you want to log all queries (for example to find a problem query) you should use the general query log. See section The General Query Log.

バイナリログはマスターからスレーブにレプリケーションを行なうときにも 使用されます。 See section MySQL のレプリケーション (3.23.15以上).

--log-bin[=file_name] オプションで mysqld が起動されると、 mysqld は全てのデータを更新する SQL コマンドをログファイルに書き出します。 もしファイル名がオプションに渡されなかった場合は、ホストマシンの名前に -bin がついた名前が、ファイル名として使用されます。 もしファイル名が指定されていても、パスが指定されていない場合には、 ログファイルはデータディレクトリに書かれます。

もし --log-bin=filename.extension という形で ファイル名に拡張子を指定した場合、拡張子は取り除かれます。

バイナリログファイル名のため、mysqld は数字をファイル名に付け加えます。 この数字はサーバー上で mysqladmin refresh, mysqladmin flush-logs, FLUSH LOGS を実行する度に増えていきます。 新しいバイナリログは max_binlog_size に達するまで自動的に作成されます。 RESET MASTER コマンドを使用すれば、書き込み中ではないバイナリログファイルを 全て消すことが可能です。 See section RESET 構文.

You can use the following options to mysqld to affect what is logged to the binary log:

Option Description
binlog-do-db=database_name Tells the master that it should log updates to the binary log if the current database (i.e. the one selected by USE) database is 'database_name'. All others databases which are not explicitly mentioned are ignored. Note that if you use this you should ensure that you only do updates in the current database. (Example: binlog-do-db=some_database)
binlog-ignore-db=database_name Tells the master that updates where the current database (i.e. the one selected by USE) is 'database_name' should not be stored in the binary log. Note that if you use this you should ensure that you only do updates in the current database. (Example: binlog-ignore-db=some_database)

To be able to know which different binary log files have been used, mysqld will also create a binary log index file that contains the name of all used binary log files. By default this has the same name as the binary log file, with the extension '.index'. You can change the name of the binary log index file with the --log-bin-index=[filename] option. You should not manually edit this file while mysqld is running; doing this would confuse mysqld.

If you are using replication, you should not delete old binary log files until you are sure that no slave will ever need to use them. One way to do this is to do mysqladmin flush-logs once a day and then remove any logs that are more than 3 days old. You can remove them manually, or preferably using PURGE MASTER LOGS TO (see section レプリケーションに関連する SQL コマンド) which will also safely update the binary log index file for you.

You can examine the binary log file with the mysqlbinlog command. For example, you can update a MySQL server from the binary log as follows:

shell> mysqlbinlog log-file | mysql -h server_name

You can also use the mysqlbinlog program to read the binary log directly from a remote MySQL server!

mysqlbinlog --help will give you more information of how to use this program!

If you are using BEGIN [WORK] or SET AUTOCOMMIT=0, you must use the MySQL binary log for backups instead of the old update log.

The binary logging is done immediately after a query completes but before any locks are released or any commit is done. This ensures that the log will be logged in the execution order.

Updates to non-transactional tables are stored in the binary log immediately after execution. For transactional tables such as BDB or InnoDB tables, all updates (UPDATE, DELETE or INSERT) that change tables are cached until a COMMIT command is sent to the server. At this point mysqld writes the whole transaction to the binary log before the COMMIT is executed. Every thread will, on start, allocate a buffer of binlog_cache_size to buffer queries. If a query is bigger than this, the thread will open a temporary file to store the transaction. The temporary file will be deleted when the thread ends.

The max_binlog_cache_size (default 4G) can be used to restrict the total size used to cache a multi-query transaction. If a transaction is bigger than this it will fail and roll back.

If you are using the update or binary log, concurrent inserts will be converted to normal inserts when using CREATE ... SELECT or INSERT ... SELECT. This is to ensure that you can recreate an exact copy of your tables by applying the log on a backup.

The Slow Query Log (3.23.28以上)

MySQL を --log-slow-queries[=file_name] オプションで起動すると、 mysqld は、 実行に long_query_time に指定された値以上に時間のかかった 全ての SQL コマンドをログに書き出します。 この時間には、最初のテーブルをロックするまでの時間は含まれていません。

slow query log はクエリが実行され、全てのロックが解除された後に、 書き込まれます。 そのため、SQL 文が実行された順番とは違う順に 書かれるかもしれません。

もしファイル名が指定されなかったら、ホスト名に -slow.log をつけた ファイル名が使用されます。 もしファイル名が指定されていてもパスが指定されなかったなら、 ログファイルはデータディレクトリに記録されます。

slow query log は実行に時間のかかったクエリを見つけ出すのに使用することが 可能で、最適化に用いられます。 ログファイルが大きくなると、それが難しくなります。そこで、 mysqldumpslow コマンドを使用すれば、ログファイルの slow query の サマリ一覧を得ることが可能です。

--log-long-format オプションを使用すれば、インデックスを使用しなかった クエリも記録します。 See section mysqld コマンド行オプション.

Log File Maintenance

The MySQL Server can create a number of different log files, which make it easy to see what is going on. See section The MySQL Log Files. One must however regularly clean up these files, to ensure that the logs don't take up too much disk space.

MySQL をログファイルとともに使用する場合、 あなたは、時々古いログファイルを リムーブ/バックアップし、 MySQL に新しいファイルにログを取るように指示したいと思うことでしょう。 See section データベースのバックアップ.

Linux (Red Hat) においては、mysql-log-rotate スクリプトを これに使用できます。 もし RPM ディストリビューションの MySQL を インストールしたなら、このスクリプトは自動でインストールされているはずです。 Note that you should be careful with this if you are using the log for replication!

他のシステムでは、自分自身で短いスクリプトをインストールします。 cron でログファイルを扱うようにします。

mysqladmin flush-logs コマンドか FLUSH LOGS SQL文で、 MySQL に新しいログファイルを使用させることが出来ます。 もしあなたが MySQL Version 3.21 を使用しているなら、 mysqladmin refresh を使用しなくてはなりません。

上記のコマンドは、以下のように動作します:

もし更新ログだけを使用しているなら、あなたは、ログを flush するだけでよくて、 その時、バックアップのため古い更新ログファイルを移動します。 もし普通のログを使っていれば、あなたは以下のようにすることができます:

shell> cd mysql-data-directory
shell> mv mysql.log mysql.old
shell> mysqladmin flush-logs

こうしておいて、`mysql.old' をバックアップし削除します。

MySQL のレプリケーション (3.23.15以上)

この章は MySQL の様々なレプリケーション機能を説明します。レプリケーション で有効なオプションのリファレンスとしても役立ちます。レプリケーションの紹介 と、その実装方法を学べます。終りの方には、いくつかの FAQ と問題の説明とそ の解決方法もあります。

我々のウェブサイト http://www.mysql.com/ によく訪れ、この節の最新 版を読むようるように提案します。レプリケーションは絶えず改良されていて、 最新の情報でマニュアルを頻繁に更新します。

Introduction

一方通行レプリケーションは、堅牢さと速度の両方を増加させるために使用できま す。堅牢さについて、2つのシステムを持つことができ、マスターで問題が発生し た場合にバックアップに切り替えられます。速度の増加は、更新でないクエリの一 部をレプリカサーバに送ることで、成立します。もちろん、これは更新でないクエ リが多い時にだけ働くのですが、通常はそうなります。

バージョン 3.23.15 から、MySQL はワンウェイ・レプリケーションを サポートしました。 1つのサーバーがマスターの役をつとめ,もう一方は、スレーブの役をつとめます。 1つのサーバーはマスターとして動くことも、他に対するスレーブとして動作することも 可能です。 マスターサーバーは update のバイナリログを保持しています(See section The Binary Update Log バイナリ更新ログ (3.23.15以上).)。 また、インデックスファイルは、バイナリログのローテーションの切り出し記録を残すた めに保持されます。 スレーブは接続時に、マスタに対し更新の伝達が最後に成功してからやめた場所 を知らせ、更新を取り戻し、それからブロックし、マスタが新しい更新を通知す るのを待ちます。

もしデータベースの複製を行なうなら、このデータベースに対する全ての更新は マスター上で行なわなくてはならないことに注意!

レプリケーションを使用することのもう一つの恩恵は、マスターの代わりに、スレー ブでバックアップを行なうことで、システムのライブバックアップを取ることがで きるということです。See section データベースのバックアップ

レプリケーション実装概要

MySQL レプリケーションは、サーバがデータベースへのすべての変更のトラックを バイナリログ (see section The Binary Update Log バイナリ更新ログ (3.23.15以上)) に保持し、スレーブサーバがデータのコピー 上で同じクエリを実行できるように、マスターサーバのバイナリログから保存され たクエリを読み込むということを基本にします。

バイナリログは単に固定点(バイナリロギングを有効にした瞬間)からの記録である ことを理解することがとても重要です。セットアップするすべてのスレー ブで、マスターからすべてのデータのコピーが必要です。マスター上でバイナリロ ギングを有効にした瞬間に存在していたように。 スレーブのデータがマスターに存在するデータと違う状態でスレーブを起動したならば、 バイナリログが開始されたときに、スレーブは失敗するでしょう。

Please see the following table for an indication of master-slave compatibility between different versions. With regard to version 4.0, we recommend using same version on both sides.

Master Master Master Master
3.23.33 and up 4.0.0 4.0.1 4.0.3 and up
Slave 3.23.33 and up yes no no no
Slave 4.0.0 no yes no no
Slave 4.0.1 yes no yes no
Slave 4.0.3 and up yes no no yes

Note: MySQL Version 4.0.2 is not recommended for replication.

Starting from 4.0.0, one can use LOAD DATA FROM MASTER to set up a slave. Be aware that LOAD DATA FROM MASTER currently works only if all the tables on the master are MyISAM type, and will acquire a global read lock, so no writes are possible while the tables are being transferred from the master. This limitation is of a temporary nature, and is due to the fact that we have not yet implemented hot lock-free table backup. It will be removed in the future 4.0 branch versions once we implement hot backup enabling LOAD DATA FROM MASTER to work without blocking master updates.

Due to the above limitation, we recommend that at this point you use LOAD DATA FROM MASTER only if the dataset on the master is relatively small, or if a prolonged read lock on the master is acceptable. While the actual speed of LOAD DATA FROM MASTER may vary from system to system, a good rule for a rough estimate of how long it is going to take is 1 second per 1 MB of the datafile. You will get close to the estimate if both master and slave are equivalent to 700 MHz Pentium, are connected through 100 MBit/s network, and your index file is about half the size of your data file. Of course, your mileage will vary from system to system, the above rule just gives you a rough order of magnitude estimate.

一旦スレーブが適切に構成され、実行していれば、スレーブは単にマスターに接続して、 更新が処理されるのを待つでしょう。 もしマスターがなくなったり、または、スレーブがマスターとの接続性を失えば、 スレーブは再接続できるまで master-connect-retry 秒毎に接続を試み、 そして、更新の監視を再開します。

各スレーブはそれが止まった場所のトラックを保持します。マスターサーバはいく つのスレーブが存在し、どれがいつ更新を行なったかについての知識はありません。

次の節ではマスター/スレーブ設定過程を詳細に説明します。

レプリケーションの設定方法

以下は、現在の MySQL サーバ上に完全なレプリケーションを設定する方法の簡単 な記述です。あなたがすべてのデータベースのレプリケーションを行ないたくて、 事前にレプリケーションを設定していないと仮定します。以下に示すステップを完 了するためには、マスターサーバを少しシャットダウンすることが必要になります。

上述の方法は、スレーブを設定するもっとも素直な方法ですが、それが唯一の方 法ではありません。たとえば、既にマスタのスナップショットを持っていて、マ スタがすでにサーバIDを設定して、バイナリログを有効にしている場合、マスタ をシャットダウンしたり更新をブロックすることなしに、スレーブを設定できま す。詳細については section Replication FAQ. を参照してください。

MySQL レプリケーションの達人(guru)になりたければ、学習し、熟考し、 section レプリケーションに関連する SQL コマンド に記述されているすべてのコマンドを試すように提案 します。 section `my.cnf' 内のレプリケーションオプションmy.cnf 内のレプリケーション 開始オプションにも精通すべきです。

  1. マスターとスレーブに、最新の MySQL (同じバージョン) をインストールします。 バージョン 3.23.29 以上を使用すること。 これより前のバージョンでは、バイナリログのフォーマットが違い、また、新しい バージョンで直っているバグも含まれます。 最新のバージョンで確かめるまでは、バグレポートを送らないでください。
  2. マスター上に、レプリケーション用の特別なユーザーを登録します。 このユーザーには FILE 権限(in MySQL versions older than 4.0.2)か REPLICATION SLAVE 権限(in newer MySQL versions)が必要です。 全てのスレーブからこのユーザーで接続できるようにします。 もしユーザーがレプリケーションのみ(推奨)を行なうなら、 他の権限は与える必要は有りません。 例えば、repl という名前のユーザー(マスターにアクセス可能なユーザー)を 作成するには、次のようにします:
    mysql> GRANT FILE ON *.* TO repl@"%" IDENTIFIED BY '<password>'; # master < 4.0.2
    
    mysql> GRANT REPLICATION SLAVE ON *.* TO repl@"%" IDENTIFIED BY '<password>'; # master >= 4.0.2
    
    If you plan to use the LOAD TABLE FROM MASTER or LOAD DATA FROM MASTER commands (available starting from version 4.0.0), you will also need to grant the RELOAD and SUPER privileges on the master to the above user.
  3. If you are using MyISAM tables, flush all the tables and block write queries by executing FLUSH TABLES WITH READ LOCK command.
    mysql> FLUSH TABLES WITH READ LOCK;
    
    and then take a snapshot of the data on your master server. (Unixでは) もっとも簡単な方法は tar を使用してデータディレクトリの アーカーブを作成することです。 正確なデータディレクトリの場所はインストール方法に依存します。
    tar -cvf /tmp/mysql-snapshot.tar /path/to/data-dir
    
    Windows ユーザは WinZIP か似たソフトウェアを使用してデータディレクトリのアー カイブを作成することができます。 After or during the process of taking a snapshot, read the value of the current binary log name and the offset on the master:
    mysql > SHOW MASTER STATUS;
    +---------------+----------+--------------+-------------------------------+
    | File          | Position | Binlog_do_db | Binlog_ignore_db              |
    +---------------+----------+--------------+-------------------------------+
    | mysql-bin.003 | 73       | test,bar     | foo,manual,sasha_likes_to_run |
    +---------------+----------+--------------+-------------------------------+
    1 row in set (0.06 sec)
    
    The File column shows the name of the log, while Position shows the offset. In the above example, the binary log value is mysql-bin.003 and the offset is 73. Record the values - you will need to use them later when you are setting up the slave. Once you have taken the snapshot and recorded the log name and offset, you can re-enable write activity on the master:
    mysql> UNLOCK TABLES;
    
    If you are using InnoDB tables, ideally you should use the InnoDB Hot Backup tool that is available to those who purchase MySQL commercial licenses, support, or the backup tool itself. It will take a consistent snapshot without acquiring any locks on the master server, and record the log name and offset corresponding to the snapshot to be later used on the slave. More information about the tool is avaliable at http://www.innodb.com/hotbackup.html. Without the hot backup tool, the quickest way to take a snapshot of InnoDB tables is to shut the master server down and copy the data files, the logs, and the table definition files (.frm). To record the current log file name and offset, you should do the following before you shut down the server:
    mysql> FLUSH TABLES WITH READ LOCK;
    mysql> SHOW MASTER STATUS;
    
    And then record the log name and the offset from the output of SHOW MASTER STATUS as was shown earlier. Once you have recorded the log name and the offset, shut the server down without unlocking the tables to make sure it goes down with the snapshot corresponding to the current log file and offset:
    shell> mysqladmin -uroot shutdown
    
    If the master has been previously running without log-bin enabled, the values of log name and position will be empty when you run SHOW MASTER STATUS. In that case, record empty string ('') for the log name, and 4 for the offset.
  4. Make sure that `my.cnf' on the master has log-bin if it is not there already and server-id=unique number in the [mysqld] section. If those options are not present, add them and restart the server. It is very important that the id of the slave is different from the id of the master. Think of server-id as something similar to the IP address - it uniquely identifies the server instance in the community of replication partners.
    [mysqld]
    log-bin
    server-id=1
    
  5. マスター上の MySQL を再起動します。
  6. スレーブの my.cnf ファイルに、次を追加します:
    server-id=<some unique number between 1 and 2^32-1 that is different from
     that of the master>
    
    システムに関連したものは <> 内の値で置き換えてあります。 server-id には、サーバーそれぞれで違う番号にしなくてはなりません。 (同じ複製のグループ内で)。 もし server-id を指定しなければ、 master-host が無い場合には 1 に なり、それ以外の場合には 2 に自動的になります。 マスターで server-id の記入漏れがあった場合、 マスターはスレーブからの接続を拒否します。 スレーブ上での記入漏れの場合には、スレーブはマスターへの接続を拒否します。 従って、server-id の省略はバイナリログのバックアップのためにだけ良 いことです。
  7. While the slave is running, make it forget about the old replication configuration if it has been replicating previously:
    mysql> RESET SLAVE;
    
  8. スレーブのデータディレクトリにデータのスナップショットをコピーします。 ファイルとディレクトリのユーザーとパーミッションは確実に正しいものに してください。 これらのファイルに対して、 MySQL を実行している アカウントで、読み書きできるようにする必要があります。
  9. スレーブの再起動。
  10. Once the slave comes up, execute the following command:
    mysql> CHANGE MASTER TO MASTER_HOST='<master host name>',
     MASTER_USER='<replication user name>',
     MASTER_PASSWORD='<replication password>',
     MASTER_LOG_FILE='<recorded log file name>',
     MASTER_LOG_POS=<recorded log offset>;
    
    replacing the values in <> with the actual values relevant to your system.
  11. Start the slave thread:
    mysql> SLAVE START;
    

上記を行なった後、スレーブはマスターに接続し、スナップショット以後の 更新をキャッチするはずです。

もしスレーブに server-id をセットし忘れた場合、エラーログファイルに 次のようなエラーが出るでしょう:

Warning: one should set server_id to a non-0 value if master_host is set.
The server will not act as a slave.

もしマスターにセットし忘れたなら、スレーブはマスターに接続できません。

もし何かの理由でスレーブが複製できなかったなら、スレーブ上のエラーログ ファイルに、エラーメッセージが出るでしょう。

一度スレーブがレプリケーションを始めたなら、 エラーログファイルと同じディレクトリに master.info ファイルを見ることができます。 master.info ファイルはスレーブに使用され、 これは、マスターのバイナリログのいくつまで処理したかを保持しています。 このファイルを消したり編集したりしては いけません。 (あなたがやろうとしていることが確実に分かるまでは)。 そういうやむを得ない場合には、 CHANGE MASTER TO コマンドの使用の方が良いです。

Now that you have a snapshot, you can use it to set up other slaves. To do so, follow the slave portion of the procedure described above. You do not need to take another snapshot of the master.

レプリケーション機能と既知の問題

以下はサポートされていることとサポートされていないことの説明です:

`my.cnf' 内のレプリケーションオプション

レプリケーションを使用する場合は、我々は MySQL Version 3.23.33 以降を 推奨します。 これより古いバージョンでも動きますが、古い物はバグがあったり機能が無かったりします。 Some of the options mentioned here may not be available in your version if it is not the most recent one. For all options specific to the 4.0 branch, there is a note indicating so. Otherwise, if you discover that the option you are interested in is not available in your 3.23 version, and you really need it, please upgrade to the most recent 3.23 branch.

Please be aware that 4.0 branch is still in alpha, so some things may not be working as smoothly as you would like. If you really would like to try the new features of 4.0, we recommend you do it in such a way that in case there is a problem your mission critical applications will not be disrupted.

マスターとスレーブの両方に、 server-id オプションが必要です。 これは一意のレプリケーションid をセットします。 マスター、スレーブそれぞれのために、一意な値を、1 から 2^32-1 までの間から 選ばねばなりません。 例: server-id=3

以下の表は、MASTER で使用できるオプションを示したものです:

オプション 説明
log-bin=filename Write to a binary update log to the specified location. Note that if you give it a parameter with an extension (for example, log-bin=/mysql/logs/replication.log ) versions up to 3.23.24 will not work right during replication if you do FLUSH LOGS . The problem is fixed in Version 3.23.25. If you are using this kind of log name, FLUSH LOGS will be ignored on binlog. log を clear するには、FLUSH MASTER の実行をします。 FLUSH SLAVE を全てのスレーブ上で実行することも忘れてはいけません。 バージョン 3.23.36 以上では、RESET MASTERRESET SLAVE を使用す べきです。 You can use this option if you want to have a name which is independant of your hostname (could be useful in case you rename your host one day). (訳注: RESET はログを本当に全部消してしまうので、注意が必要。)
log-bin-index=filename FLUSH LOGS コマンドの実行のためには、どのログが現在使用されているもので、 どれがローテートされたもので、どの順番なのか、ということを知る必要があります。 この情報はバイナリログ index ファイルに記述されます。 デフォルトでは ``hostname`.index' というファイルになります。 違う名前にしたい場合に、このオプションを使用します。 Example: log-bin-index=db.index
sql-bin-update-same 設定されると、SQL_LOG_BIN に値を設定すると自動的に SQL_LOG_UPDATE を同じ値に設定します。逆も同様です。
binlog-do-db=database_name 現在の(いうなれば USE で選択している)データベースが database_name の場合、 バイナリログに更新をログすべきことをマスターに伝えます。 他のすべてのデータベースは無視されます。 注意: これを使用する場合は、現在のデータベースでだけ更新を行なうことを 確実にすべきです。 Example: binlog-do-db=sales
binlog-ignore-db=database_name 現在のデータベース(USEで選択しているデータベース) が database_name という名前であり、このデータベースの更新記録を バイナリログに格納すべきでないと、マスターに伝えます。 注意: これを使用する場合は、現在のデータベー スでだけ更新を行なうことを確実にすべきです。 Example: binlog-ignore-db=accounting

次の表は SLAVE に使用できるオプションです:

Option Description
master-host=host マスタのホスト名か IP アドレス。 もし設定されていないと、スレーブはスタートしません。 Note that the setting of master-host will be ignored if there exists a valid `master.info' file. Probably a better name for this options would have been something like bootstrap-master-host, but it is too late to change now. Example: master-host=db-master.mycompany.com
master-user=username スレーブスレッドがマスターに接続する時に自分を認証するためのユーザ。ユーザ は FILE 権限を持つ必要があります。マスターユーザが設定されない場合 は、test が適用されます。 The value in `master.info' will take precedence if it can be read. Example: master-user=scott
master-password=password スレーブスレッドがマスターサーバに接続する時に認証するパスワード。設定され ない場合は、空のパスワードが適用されます。 The value in `master.info' will take precedence if it can be read. Example: master-password=tiger
master-port=portnumber マスターが listen しているポート。設定されない場合は、MYSQL_PORT の コンパイル時の設定が適用されます。configure オプションで何もしてな ければ、これは 3306 です。 The value in `master.info' will take precedence if it can be read. Example: master-port=3306
master-connect-retry=seconds マスターが落ちたり接続が失われた場合に、スレーブスレッドがマスターへの接続 を再試行するまでに休眠する秒数。デフォルトは 60。 Example: master-connect-retry=60
master-ssl Available after 4.0.0. Turn SSL on for replication. Be warned that is this is a relatively new feature. Example: master-ssl
master-ssl-key Available after 4.0.0. Master SSL keyfile name. Only applies if you have enabled master-ssl. Example: master-ssl-key=SSL/master-key.pem
master-ssl-cert Available after 4.0.0. Master SSL certificate file name. Only applies if you have enabled master-ssl. Example: master-ssl-key=SSL/master-cert.pem
master-info-file=filename 複製処理がマスターのどこまで行なったかを覚えておくファイルの場所。デフォル トはデータディレクトリの `master.info' です。 You should not need to change this. Example: master-info-file=master.info
report-host バージョン 4.0.0 から。 スレーブ登録中にマスタに報告されるスレーブのホス ト名と IP 。これは SHOW SLAVE HOSTS の出力に表われます。スレーブ をマスタに登録したくない場合は、設定しないでください。注意: マスタがスレー ブ接続時のソケットの IP を単純に読むだけでは不十分です。NAT や他 のルーティングの問題で、マスタや他のホストからスレーブへの接続IPが正しく ないことがあります。 Example: report-host=slave1.mycompany.com
report-port バージョン 4.0.0 から。スレーブ登録中にマスタに報告されるスレーブのポー ト。スレーブがデフォルトでないポートで listen する場合か、マスタか他のク ライアントからスレーブへの特殊なトンネルを持つ場合にだけ設定してください。 確かでなければ、このオプションを設定しないでください。
replicate-do-table=db_name.table_name 指定されたテーブルに複製を制限することをスレーブスレッドに伝えます。一つ以 上のテーブルを指定するには、この命令を複数回(各テーブルに1回ずつ)使用しま す。 This will work for cross-database updates, in contrast to replicate-do-db. Example: replicate-do-table=some_db.some_table
replicate-ignore-table=db_name.table_name 指定されたテーブルを複製しないことをスレーブスレッドに伝えます。 (even if any other tables may be update by the same command). 一つ以上の テーブルを無視するように指定するには、この命令を複数回(各テーブルに1回ず つ)使用します。これは replicate-ignore-db とは対照的に、データベー スをまたがった更新について動作します。 Example: replicate-ignore-table=db_name.some_table
replicate-wild-do-table=db_name.table_name 指定されたワイルドカードパターンに適合するテーブルに複製を制限することをス レーブスレッドに伝えます。一つ以上のテーブルを指定するには、この命令を複数 回(各テーブルに1回ずつ)使用します。これはデータベースをまたがった更新につ いて動作します。 Example: replicate-wild-do-table=foo%.bar%foo で始まるすべての データベースの bar で始まるテーブルだけに更新を複製します。 Note that if you do replicate-wild-do-table=foo%.% then the rule will be propagated to CREATE DATABASE and DROP DATABASE, i.e. these two statements will be replicated if the database name matches the database pattern ('foo%' here) (this magic is triggered by '%' being the table pattern).
replicate-wild-ignore-table=db_name.table_name 与えられたワイルドカードパターンに適合するテーブルを複製しないことをスレー ブスレッドに伝えます。一つ以上のテーブルを無視するように指定するには、この 命令を複数回(各テーブルに1回ずつ)使用します。これはデータベースをまたがっ た更新について動作します。 Example: replicate-wild-ignore-table=foo%.bar%foo で始まるすべての データベースの bar で始まるテーブルを更新しません。 Note that if you do replicate-wild-ignore-table=foo%.% then the rule will be propagated to CREATE DATABASE and DROP DATABASE, i.e. these two statements will not be replicated if the database name matches the database pattern ('foo%' here) (this magic is triggered by '%' being the table pattern).
replicate-ignore-db=database_name Tells the slave thread to not replicate any command where the current database (i.e. the one selected by USE) is database_name. To specify more than one database to ignore, use the directive multiple times, once for each database. You should not use this directive if you are using cross table updates and you don't want these update to be replicated. The main reason for this ``just-check-the-current-database'' behaviour is that it's hard from the command alone to know if a query should be replicated or not ; for example if you are using multi-table-delete or multi-table-update commands in MySQL 4.x that go across multiple databases. It's also very fast to just check the current database, as this only has to be done once at connect time or when the database changes. If you need cross database updates to work, make sure you have 3.23.28 or later, and use replicate-wild-ignore-table=db_name.%. Example: replicate-ignore-db=some_db
replicate-do-db=database_name Tells the slave thread to restrict replication to commands where the current database (i.e. the one selected by USE) is database_name. To specify more than one database, use the directive multiple times, once for each database. Note that this will not replicate cross-database queries such as UPDATE some_db.some_table SET foo='bar' while having selected a different or no database. If you need cross database updates to work, make sure you have 3.23.28 or later, and use replicate-wild-do-table=db_name.%. Example: replicate-do-db=some_db
log-slave-updates スレーブスレッドからの更新をバイナリログに記録するように、スレーブに告げます。 デフォルトは Off です。 Of course, it requires that the slave be started with binary logging enabled (log-bin option). You have to use log-slave-updates to chain several slaves ; for example for the following setup to work
A -> B ->C
(C is a slave of B which is a slave of A) you need to start B with the log-slave-updates option.
replicate-rewrite-db=from_name->to_name Tells the slave to translate the current database (i.e. the one selected by USE) to to_name if it was from_name on the master. Only statements involving tables may be affected (CREATE DATABASE, DROP DATABASE won't), and only if from_name was the current database on the master. This will not work for cross-database updates. Example: replicate-rewrite-db=master_db_name->slave_db_name
slave-skip-errors= [err_code1,err_code2,... | all] バージョン 3.23.47 以上。 与えられたエラーコードではレプリケーションを止めないように、 スレーブスレッドに告げます。 通常、レプリケーションはエラーに出会うと中止し、マニュアルでデータの矛盾を 解決する機会をユーザに与えます。 このオプションは、なぜエラーが発生したのかを完全に理解するまでは 使用してはいけません。 もしレプリケーションのセットアップ、クライアントプログラム、MySQL 自身に なにもバグがないのであれば、エラーで止まるはずはありません。 このオプションを見境なく使用すると、スレーブで期待に反してマスタとの同期が ずれ、なぜ問題が発生したかについての理解ができない結果になるでしょう。 エラーコードには、スレーブのログファイルに記録されているものや SHOW SLAVE STATUS で出力される、数字の番号を使用しなくてはなりません。 全てのエラーメッセージは、ソース配布に含まれる Docs/mysqld_error.txt にあります. とても推奨できない値である all を使用することもできます(ですがすべ きではありません)。これはすべてのエラーメッセージを無視し、keep barging along regardless. 言うまでもなく、これを使用する場合は、データの完全性に関 してなんの保証もできません。 Please do not complain if your data on the slave is not anywhere close to what it is on the master in this case -- you have been warned. Example: slave-skip-errors=1062,1053 or slave-skip-errors=all
skip-slave-start 起動時にスレーブを開始しないようにスレーブサーバに伝えます。ユーザは後で SLAVE START で開始できます。
slave_compressed_protocol=# If 1, then use compression on the slave/client protocol if both slave and master support this.
slave_net_timeout=# 読み込みがアボートする前にマスターからデータを待つ秒数。

レプリケーションに関連する SQL コマンド

レプリケーションは SQL インタフェースを通じて制御できます。以下はコマンド のサマリです:

Command Description
SLAVE START スレーブスレッドを開始します。 As of MySQL 4.0.2, you can add IO_THREAD or SQL_THREAD options to the statement to start the I/O thread or the SQL thread. The I/O thread reads queries from the master server and stores them in the relay log. The SQL thread reads the relay log and executes the queries. (スレーブ)
SLAVE STOP スレーブスレッドを停止します。 Like SLAVE START, this statement may be used with IO_THREAD and SQL_THREAD options. (スレーブ)
SET SQL_LOG_BIN=0 ユーザが SUPER 権限(in MySQL 4.0.2 and above) PROCESS (in older MySQL versions) を持っている場合に 更新ログを無効にします。そうでなければ無視されます。(マスター)
SET SQL_LOG_BIN=1 ユーザが SUPER 権限(in MySQL 4.0.2 and above)か PROCESS 権限(in older MySQL versions) を 持っている場合更新ロギングを再度有効にします。 そうでなければ無視されます。(マスター)
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=n マスターからの次の n イベントをスキップします。スレーブスレッ ドが実行していない場合にだけ正当です。そうでなければエラーになります。レプ リケーションの不調からの復旧に有用です。
RESET MASTER インデックスファイルにリストされたすべてのバイナリログを削除し、 binlog インデックスファイルを空にリセットします。3.23.26 バージョンより前 では、FLUSH MASTER (Master)
RESET SLAVE スレーブにマスターログのレプリケーション位置を忘れさせます。 3.23.26 バージョンより前ではこのコマンドは FLUSH SLAVE と呼ばれてい ました(Slave)
LOAD TABLE tblname FROM MASTER マスターからスレーブにテーブルのコピーをダウンロードします。主に LOAD DATA FROM MASTER のデバッグ用に実装されていますが、but some ``gourmet'' users might find it useful for other things. 自分自身が並の "非ハッカー" タイプの ユーザー(並みのユーザー)であると思う場合は、使用しないでください。 Requires that the replication user which is used to connect to the master has RELOAD and SUPER privileges on the master. Please read the timeout notes in the description of LOAD DATA FROM MASTER below, they apply here too. (Slave)
LOAD DATA FROM MASTER バージョン 4.0.0 から。 マスターのスナップショットを取り、スレーブにコピーします。 Requires that the replication user which is used to connect to the master has RELOAD and SUPER privileges on the master. スレーブが正しい位置からレプリケーションを開始するように、 MASTER_LOG_FILEMASTER_LOG_POS の値を更新します。 Will honor table and database exclusion rules specified with replicate-* options. So far works only with MyISAM tables and acquires a global read lock on the master while taking the snapshot. In the future it is planned to make it work with InnoDB tables and to remove the need for global read lock using the non-blocking online backup feature. If you are loading big tables, you may have to increase the values of net_read_timeout and net_write_timeout on both your master and slave ; see section SHOW VARIABLES. Note that LOAD DATA FROM MASTER does NOT copy any tables from the mysql database. This is to make it easy to have different users and privileges on the master and the slave.
CHANGE MASTER TO master_def_list マスターパラメータを master_def_list に指定された値に変更し、 スレーブスレッドを再起動します。master_def_list はコンマで区切られ た master_def のリストです。master_def は次のうちの一つです : MASTER_HOST, MASTER_USER, MASTER_PASSWORD, MASTER_PORT, MASTER_CONNECT_RETRY, MASTER_LOG_FILE, MASTER_LOG_POS. For example:
CHANGE MASTER TO
  MASTER_HOST='master2.mycompany.com',
  MASTER_USER='replication',
  MASTER_PASSWORD='bigs3cret',
  MASTER_PORT=3306,
  MASTER_LOG_FILE='master2-bin.001',
  MASTER_LOG_POS=4;
変更する必要のある値だけを指定する必要があります。省略した値は同じ値を維持 します。ホストまたはポートを変更した時を除きます。この場合、スレーブは異な るホストまたは異なるポートに接続しているのでマスターが異なっているとみなし ます。従って、古いログと位置の値はどこにも該当しません。そして、自動的に空 文字列と 0 にそれぞれリセットされます (開始値)。注意: スレーブを再起動する 場合、最後のマスターを覚えています。これが望ましくない場合、 `master.info' ファイルを再起動前に削除すべきです。すると、スレーブは my.cnf またはコマンドラインからそのマスターを読み込みます。 このコマンドは、マスタのスナップショットを持っていて、スナップショットに対 応するマスタ上のログとオフセットの記録がある場合に、スレーブをセットアップ するのに有用です。スナップショットからのリストア後にスレーブ上で、 CHANGE MASTER TO MASTER_LOG_FILE='log_name_on_master', MASTER_LOG_POS=log_offset_on_masterを実行できます。 (Slave)
SHOW MASTER STATUS マスターの binlog のステータス情報を提供します。(Master)
SHOW SLAVE HOSTS バージョン 4.0 からの機能。 Gives a listing of slaves currently registered with the master. (Master)
SHOW SLAVE STATUS スレーブスレッドの基本的な パラメータのステータス情報を提供します。(Slave)
SHOW MASTER LOGS バージョン 3.23.28 以降だけで有効です。 マスター上のバイナリログをリストします。 どれくらい行くべきかを見つけるためには、 このコマンドを PURGE MASTER LOGS TO よりも先に使用すべきです。 (Master)
SHOW BINLOG EVENTS [ IN 'logname' ] [ FROM pos ] [ LIMIT [offset,] rows ] バージョン 4.0 からの機能。 binary update log 中のイベントを見せます。 基本的にはテストやデバッグで使用されます。 通常のクライアントからバイナリログを読む必要がある場合にも 使用することが可能です。 (Master)
SHOW NEW MASTER FOR SLAVE WITH MASTER_LOG_FILE='logfile' AND MASTER_LOG_POS=pos AND MASTER_LOG_SEQ=log_seq AND MASTER_SERVER_ID=server_id バージョン 4.0 からの機能。 おそらく死んだ/無効になったマスタのスレーブが、同じマスタをレプリケーショ ンしていた他のスレーブからレプリケーションするようにスイッチすることが必 要な場合に、このコマンドが使用されます。コマンドは再計算されたレプリケー ション coordinates を返します (the slave's current binary log file + name and position within that file). この出力は続く CHANGE MASTER TO コマン ドで使用することができます。通常、ユーザはこのコマンドを実行する必要はあ りません。これは本来 fail-safe レプリケーションコードに内部使用に予約さ れています。この操作を記述するのにもっと直観的な方法を見つけた場合、この 文法は変更されるでしょう。
PURGE MASTER LOGS TO 'logname' バージョン 3.23.28 からの機能。 index ファイルに書かれているログファイルのうち、 指定されたログよりも前のログファイルを全て消します。 index ファイルのリストからもエントリを消します。 そして、指定されたログを一番最初の物とします。 例えば:
PURGE MASTER LOGS TO 'mysql-bin.010'
(訳注: このコマンドの場合、mysql-bin.001 〜 mysql-bin.009 までの ファイルは消され、mysql.index ファイルの中身は、mysql-bin.010 のみ、 記述される状態になるということ。) 削除しようとしているログの一つを現在読み込み中の実行中スレーブがある場合、 このコマンドは何も行なわず、エラーで失敗します。しかし、休眠中のスレーブが あり、それが読もうとしているログの一つをパージしてしまうと、スレーブは複製 できなくなります。このコマンドはスレーブが複製中には安全に実行できます - それらを停止する必要はありません。 最初に SHOW SLAVE STATUS で、どのログが on になっているか、すべての スレーブをチェックする必要があります。それからマスターで SHOW MASTER LOGS でログのリストを行ない、すべてのスレーブに共通の最も古いログ を見つけ(すべてのスレーブが最新の場合、リストの最後のログになります)、削除 しようとするすべてのログをバックアップし、目的のログをパージします。

Replication FAQ

Q: マスタが既に走っている状態で、マスタを止めないで、新しく スレーブを作るには、どのようにすればいいの?

A: いくつか方法があります。 もしマスタのどこかの時点でのバックアップを取っていて、そして そのバックアップした時点に対応する バイナリログの名前と位置を記録しているのであれば、 ( SHOW MASTER STATUS で知ることが出来ます) 以下のようにします:

もし現在のマスタのバックアップを取っていないのであれば、以下が素早く セットアップする方法です:

Afterwards, follow the instructions for the case when you have a snapshot and have recorded the log name and offset. 同じスナップショットをいくつものスレーブをセットアップするために使用す ることができます。一度マスタのスナップショットを得れば、マスタのバイナ リログが無傷で残っている限り、何日でも場合によっては一月でも、待ってス レーブを設定することができます。理論的には待つ期間は無限にできます。2 つの現実的な制限があり、1つは古いログで一杯になるマスタのディスク容量 と、スレーブがキャッチアップするのに掛かる時間の大きさです。

バージョン 4.0.0 以降では、LOAD DATA FROM MASTER も使用できます。 これは、スナップショットを取ってスレーブにリストアし、ログ名とオフセッ トをスレーブ上で一度に調整する便利なコマンドです。将来、LOAD DATA FROM MASTER はスレーブをセットアップする推奨方法になるでしょう。 しかし、このコマンドを使用する場合、読み込みロックが長い時間保持される こともあることに注意してください。まだ、我々がそうしたいほど効率よくは 実装されていません。大きなテーブルがある場合、現時点での推奨方法は、ま だ FLUSH TABLES WITH READ LOCK 実行後のローカル tar スナッ プショットです。

Q: スレーブは常にマスターに接続していなければならないの?

A: いいえ、その必要はありません。 スレーブを数時間でも数日でも止めたり落としたりしておき、 そのあと再接続して、更新を行ない、再度また、スレーブを落とすことが可能です。 So you can, for example, use master-slave setup over a dial-up link that is up only for short periods of time. The implications of that are that at any given time the slave is not guaranteed to be in sync with the master unless you take some special measures. In the future, we will have the option to block the master until at least one slave is in sync.

Q: スレーブがキャッチアップするまで、マスタの更新をブロックする には?

A: 次のコマンドを実行してください:

Q: Why do I sometimes see more than one Binlog_Dump thread on the master after I have restarted the slave?

A: Binlog_Dump is a continuous process that is handled by the server in the following way:

So if the slave thread stops on the slave, the corresponding Binlog_Dump thread on the master will not notice it until after at least one update to the master (or a kill), which is needed to wake it up from pthread_cond_wait(). In the meantime, the slave could have opened another connection, which resulted in another Binlog_Dump thread.

The above problem should not be present in Version 3.23.26 and later versions. In Version 3.23.26 we added server-id to each replication server, and now all the old zombie threads are killed on the master when a new replication thread connects from the same slave

Q: replication log をどうやってローテートするの?

A: バージョン 3.23.28 からでは、PURGE MASTER LOGS TO コマンド を使用するべきです。 実行前には、どのログが消せれるか確認し、場合によっては バックアップを取っておきます。 In earlier versions the process is much more painful, and cannot be safely done without stopping all the slaves in the case that you plan to re-use log names. You will need to stop the slave threads, edit the binary log index file, delete all the old logs, restart the master, start slave threads, and then remove the old log files.

Q: How do I upgrade on a hot replication setup?

A: If you are upgrading pre-3.23.26 versions, you should just lock the master tables, let the slave catch up, then run FLUSH MASTER on the master, and FLUSH SLAVE on the slave to reset the logs, then restart new versions of the master and the slave. Note that the slave can stay down for some time -- since the master is logging all the updates, the slave will be able to catch up once it is up and can connect.

バージョン 3.23.26 以降では、レプリケーションプロトコルのロック (変更のための)を持ちます。 そのため、あなたはマスタとスレーブを on the fly で 新しい 3.23 バージョンにアップグレードできます。 そして、マスタとスレーブがバージョン 3.23.26 以上の場合においては、 マスタとスレーブが違うバージョンの MySQL でもかまいません。

Q: What issues should I be aware of when setting up two-way replication?

A: MySQL replication currently does not support any locking protocol between master and slave to guarantee the atomicity of a distributed (cross-server) update. In other words, it is possible for client A to make an update to co-master 1, and in the meantime, before it propagates to co-master 2, client B could make an update to co-master 2 that will make the update of client A work differently than it did on co-master 1. Thus when the update of client A will make it to co-master 2, it will produce tables that will be different from what you have on co-master 1, even after all the updates from co-master 2 have also propagated. So you should not co-chain two servers in a two-way replication relationship, unless you are sure that you updates can safely happen in any order, or unless you take care of mis-ordered updates somehow in the client code.

You must also realise that two-way replication actually does not improve performance very much, if at all, as far as updates are concerned. Both servers need to do the same amount of updates each, as you would have one server do. The only difference is that there will be a little less lock contention, because the updates originating on another server will be serialised in one slave thread. This benefit, though, might be offset by network delays.

Q: How can I use replication to improve performance of my system?

A: You should set up one server as the master, and direct all writes to it, and configure as many slaves as you have the money and rackspace for, distributing the reads among the master and the slaves. You can also start the slaves with --skip-bdb, --low-priority-updates and --delay-key-write=ALL to get speed improvements for the slave. In this case the slave will use non-transactional MyISAM tables instead of BDB tables to get more speed.

Q: What should I do to prepare my client code to use performance-enhancing replication?

A: If the part of your code that is responsible for database access has been properly abstracted/modularised, converting it to run with the replicated setup should be very smooth and easy -- just change the implementation of your database access to read from some slave or the master, and to always write to the master. If your code does not have this level of abstraction, setting up a replicated system will give you an opportunity/motivation to it clean up. You should start by creating a wrapper library /module with the following functions:

safe_ means that the function will take care of handling all the error conditions.

You should then convert your client code to use the wrapper library. It may be a painful and scary process at first, but it will pay off in the long run. All applications that follow the above pattern will be able to take advantage of one-master/many slaves solution. The code will be a lot easier to maintain, and adding troubleshooting options will be trivial. You will just need to modify one or two functions, for example, to log how long each query took, or which query, among your many thousands, gave you an error. If you have written a lot of code already, you may want to automate the conversion task by using Monty's replace utility, which comes with the standard distribution of MySQL, or just write your own Perl script. Hopefully, your code follows some recognisable pattern. If not, then you are probably better off rewriting it anyway, or at least going through and manually beating it into a pattern.

Note that, of course, you can use different names for the functions. What is important is having unified interface for connecting for reads, connecting for writes, doing a read, and doing a write.

Q: When and how much can MySQL replication improve the performance of my system?

A: MySQL replication is most beneficial for a system with frequent reads and not so frequent writes. In theory, by using a one master/many slaves setup you can scale by adding more slaves until you either run out of network bandwidth, or your update load grows to the point that the master cannot handle it.

In order to determine how many slaves you can get before the added benefits begin to level out, and how much you can improve performance of your site, you need to know your query patterns, and empirically (by benchmarking) determine the relationship between the throughput on reads (reads per second, or max_reads) and on writes max_writes) on a typical master and a typical slave. The example here will show you a rather simplified calculation of what you can get with replication for our imagined system.

Let's say our system load consists of 10% writes and 90% reads, and we have determined that max_reads = 1200 - 2 * max_writes, or in other words, our system can do 1200 reads per second with no writes, our average write is twice as slow as average read, and the relationship is linear. Let us suppose that our master and slave are of the same capacity, and we have N slaves and 1 master. Then we have for each server (master or slave):

reads = 1200 - 2 * writes (from bencmarks)

reads = 9* writes / (N + 1) (reads split, but writes go to all servers)

9*writes/(N+1) + 2 * writes = 1200

writes = 1200/(2 + 9/(N+1)

So if N = 0, which means we have no replication, our system can handle 1200/11, about 109 writes per second (which means we will have 9 times as many reads due to the nature of our application).

If N = 1, we can get up to 184 writes per second.

If N = 8, we get up to 400.

If N = 17, 480 writes.

Eventually as N approaches infinity (and our budget negative infinity), we can get very close to 600 writes per second, increasing system throughput about 5.5 times. However, with only 8 servers, we increased it almost 4 times already.

Note that our computations assumed infinite network bandwidth, and neglected several other factors that could turn out to be significant on your system. In many cases, you may not be able to make a computation similar to the one above that will accurately predict what will happen on your system if you add N replication slaves. However, answering the following questions should help you decided whether and how much, if at all, the replication will improve the performance of your system:

Q: 冗長性/高可用性を提供するようにレプリケーションを使用するには?

A: 現在有効な機能で、マスターとスレーブ(またはいくつかのスレーブ 達)をセットアップする必要があります。マスターが生きているかどうかを監視し、 アプリケーションとマスターのスレーブに失敗時に変更を指示するスクリプトを書 きます。以下はいくつかの提案です:

我々は現在自動マスター選択システムを MySQL に統合するように働いていますが、 準備ができるまでは、あなた自身のモニタリングツールを作成する必要があります。

Q: How does the slave server keep track of where it is on the master?

A: The slave uses a file in the the data directory defined by the master-info-file=filename path. This file holds all the information needed by the slave to request new updates. The file contains the following information:

Line# Description
1 Binary log file id
2 Log file postion
3 Host (master)
4 Login user
5 Login password
6 Login port
7 Interval, the length of time between reconnects

Troubleshooting Replication

If you have followed the instructions, and your replication setup is not working, first eliminate the user error factor by checking the following:

When you have determined that there is no user error involved, and replication still either does not work at all or is unstable, it is time to start working on a bug report. We need to get as much info as possible from you to be able to track down the bug. Please do spend some time and effort preparing a good bug report. Ideally, we would like to have a test case in the format found in mysql-test/t/rpl* directory of the source tree. If you submit a test case like that, you can expect a patch within a day or two in most cases, although, of course, you mileage may vary depending on a number of factors.

The second best option is to write a simple program with easily configurable connection arguments for the master and the slave that will demonstrate the problem on our systems. You can write one in Perl or in C, depending on which language you know better.

If you have one of the above ways to demonstrate the bug, use mysqlbug to prepare a bug report and send it to bugs@lists.mysql.com. If you have a phantom -- a problem that does occur but you cannot duplicate "at will":

Once you have collected the evidence on the phantom problem, try hard to isolate it into a separate test case first. Then report the problem to bugs@lists.mysql.com with as much info as possible.

MySQL Optimization

Optimization is a complicated task because it ultimately requires understanding of the whole system. While it may be possible to do some local optimizations with small knowledge of your system or application, the more optimal you want your system to become the more you will have to know about it.

This chapter will try to explain and give some examples of different ways to optimise MySQL. Remember, however, that there are always some (increasingly harder) additional ways to make the system even faster.

最適化 概要

システムを速くするための最も重要な部分は、もちろん基礎的な設計です。 You also need to know what kinds of things your system will be doing, and what your bottlenecks are.

主なボトルネックは:

MySQL Design Limitations/Tradeoffs

When using the MyISAM storage engine, MySQL uses extremely fast table locking (multiple readers / single writers). The biggest problem with this table type is a if you have a mix of a steady stream of updates and slow selects on the same table. If this is a problem with some tables, you can use another table type for these. See section MySQL テーブル型.

MySQL can work with both transactional and not transactional tables. To be able to work smoothly with not transactional tables (which can't rollback if something goes wrong), MySQL has the following rules:

The reason for the above rules is that we can't check these conditions before the query starts to execute. If we encounter a problem after updating a few rows, we can't just rollback as the table type may not support this. We can't stop because in that case the update would be 'half done' which is probably the worst possible scenario. In this case it's better to 'do the best you can' and then continue as if nothing happened.

The above means that one should not use MySQL to check fields content, but one should do this in the application.

Portability

全てのSQLサーバはそれぞれ異なるSQL処理ルーチンにより構成されています。 したがって色々なSQLサーバ上で同じように動作するような(ポータブルな) SQLアプリケーションを書くのは手間がかかります。 確かに単純なインサートやセレクトを行うようなものは簡単ですが、 必要な機能が増えれば増えるほど難しくなっていきます。 高速動作を要求されるSQLプラットフォームの数が増えれば増えるほど そのようなアプリケーションの開発は大変になっていきます。

ポータブルな多機能アプリケーションを開発するためには 沢山のSQLサーバでの動作を検証する必要があります。

You can use the MySQL crash-me program/web-page http://www.mysql.com/information/crash-me.php to find functions, types, and limits you can use with a selection of database servers. Crash-me now tests far from everything possible, but it is still comprehensive with about 450 things tested.

For example, you shouldn't have column names longer than 18 characters if you want to be able to use Informix or DB2.

Both the MySQL benchmarks and crash-me programs are very database-independent. By taking a look at how we have handled this, you can get a feeling for what you have to do to write your application database-independent. The benchmarks themselves can be found in the `sql-bench' directory in the MySQL source distribution. They are written in Perl with DBI database interface (which solves the access part of the problem).

See http://www.mysql.com/information/benchmarks.html for the results from this benchmark.

As you can see in these results, all databases have some weak points. That is, they have different design compromises that lead to different behaviour.

If you strive for database independence, you need to get a good feeling for each SQL server's bottlenecks. MySQL is very fast in retrieving and updating things, but will have a problem in mixing slow readers/writers on the same table. Oracle, on the other hand, has a big problem when you try to access rows that you have recently updated (until they are flushed to disk). Transaction databases in general are not very good at generating summary tables from log tables, as in this case row locking is almost useless.

To get your application really database-independent, you need to define an easy extendable interface through which you manipulate your data. As C++ is available on most systems, it makes sense to use a C++ classes interface to the databases.

If you use some specific feature for some database (like the REPLACE command in MySQL), you should code a method for the other SQL servers to implement the same feature (but slower). With MySQL you can use the /*! */ syntax to add MySQL-specific keywords to a query. The code inside /**/ will be treated as a comment (ignored) by most other SQL servers.

If high performance is more important than exactness, as in some web applications, it is possibile to create an application layer that caches all results to give you even higher performance. By letting old results 'expire' after a while, you can keep the cache reasonably fresh. This provides a method to handle high load spikes, in which case you can dynamically increase the cache and set the expire timeout higher until things get back to normal.

In this case the table creation information should contain information of the initial size of the cache and how often the table should normally be refreshed.

What Have We Used MySQL For?

MySQL の初期の開発期には、MySQL は我々のもっとも大口の顧客に合うように 機能が作成されました。 彼らは、いくつかのスウェーデン最大手の小売り業者 のために、倉庫に入れている(商品)データを取り扱います。

我々は、すべての店から、全ボーナス・カード取扱高の、その週間まとめを得ます。 そして、その店のオーナにとって有益な情報、その店の広告キャンペーンが お客にどの程度影響を及ぼすか、を提供することが、我々に求められています。

そのデータは、とても大きくて (約700万/月 回の取り扱い)、 我々はその顧客に提供する必要のあるデータを 4〜10年分、持っています。 我々は、カスタマーから、彼らがこのデータからできる新しいレポートに ”即時に”アクセスしたいという、要求を受けました。

我々はこれを、全ての月ごとの情報を圧縮した 'transaction' テーブルに 保存することで解決しました。 We have a set of simple macros (script) that generates summary tables grouped by different criteria (product group, customer id, store ...) from the transaction tables. そのレポートは Web ページで、これは小さな perl スクリプトで動的に 作成されます。 この perl script は Web Page を分析し、SQL 文を 実行し、結果を挿入します。 We would have used PHP or mod_perl instead but they were not available at that time.

画像データのために、我々は簡単なツールを C でかきました。 これは SQL のクエリの結果を元に(結果にいくつか処理をして) GIF を提供します。 これも動的に perl スクリプト(HTML ファイルを分析する)から実行されます。

In most cases a new report can simply be done by copying an existing script and modifying the SQL query in it. In some cases, we will need to add more fields to an existing summary table or generate a new one, but this is also quite simple, as we keep all transactions tables on disk. (Currently we have at least 50G of transactions tables and 200G of other customer data.)

We also let our customers access the summary tables directly with ODBC so that the advanced users can themselves experiment with the data.

我々はこれらを Sun Ultra SPARCstation (2x200 Mz) で扱っていますが、 なんの問題もありません。 We recently upgraded one of our servers to a 2 CPU 400 Mhz UltraSPARC, and we are now planning to start handling transactions on the product level, which would mean a ten-fold increase of data. We think we can keep up with this by just adding more disk to our systems.

We are also experimenting with Intel-Linux to be able to get more CPU power cheaper. 現在、我々はバイナリ互換のデータベースフォーマットを持っており (new in Version 3.23) 、我々はこれをアプリケーションのいくつかの部分に使用しはじ める事でしょう。

Our initial feelings are that Linux will perform much better on low-to-medium load and Solaris will perform better when you start to get a high load because of extreme disk IO, but we don't yet have anything conclusive about this. After some discussion with a Linux Kernel developer, this might be a side effect of Linux giving so much resources to the batch job that the interactive performance gets very low. This makes the machine feel very slow and unresponsive while big batches are going. Hopefully this will be better handled in future Linux Kernels.

The MySQL Benchmark Suite

This should contain a technical description of the MySQL benchmark suite (and crash-me), but that description is not written yet. Currently, you can get a good idea of the benchmark by looking at the code and results in the `sql-bench' directory in any MySQL source distributions.

This benchmark suite is meant to be a benchmark that will tell any user what things a given SQL implementation performs well or poorly at.

Note that this benchmark is single threaded, so it measures the minimum time for the operations. We plan to in the future add a lot of multi-threaded tests to the benchmark suite.

For example, (run on the same NT 4.0 machine):

Reading 2000000 rows by index Seconds Seconds
mysql 367 249
mysql_odbc 464
db2_odbc 1206
informix_odbc 121126
ms-sql_odbc 1634
oracle_odbc 20800
solid_odbc 877
sybase_odbc 17614
Inserting (350768) rows Seconds Seconds
mysql 381 206
mysql_odbc 619
db2_odbc 3460
informix_odbc 2692
ms-sql_odbc 4012
oracle_odbc 11291
solid_odbc 1801
sybase_odbc 4802

In the above test MySQL was run with a 8M index cache.

We have gathered some more benchmark results at http://www.mysql.com/information/benchmarks.html.

Note that Oracle is not included because they asked to be removed. All Oracle benchmarks have to be passed by Oracle! We believe that makes Oracle benchmarks very biased because the above benchmarks are supposed to show what a standard installation can do for a single client.

To run the benchmark suite, you have to download a MySQL source distribution, install the Perl DBI driver, the Perl DBD driver for the database you want to test and then do:

cd sql-bench
perl run-all-tests --server=#

where # is one of supported servers. You can get a list of all options and supported servers by doing run-all-tests --help.

crash-me tries to determine what features a database supports and what its capabilities and limitations are by actually running queries. For example, it determines:

We can find the result from crash-me on a lot of different databases at http://www.mysql.com/information/crash-me.php.

Using Your Own Benchmarks

You should definitely benchmark your application and database to find out where the bottlenecks are. By fixing it (or by replacing the bottleneck with a 'dummy module') you can then easily identify the next bottleneck (and so on). Even if the overall performance for your application is sufficient, you should at least make a plan for each bottleneck, and decide how to solve it if someday you really need the extra performance.

For an example of portable benchmark programs, look at the MySQL benchmark suite. See section The MySQL Benchmark Suite. You can take any program from this suite and modify it for your needs. By doing this, you can try different solutions to your problem and test which is really the fastest solution for you.

It is very common that some problems only occur when the system is very heavily loaded. We have had many customers who contact us when they have a (tested) system in production and have encountered load problems. In every one of these cases so far, it has been problems with basic design (table scans are not good at high load) or OS/Library issues. Most of this would be a lot easier to fix if the systems were not already in production.

To avoid problems like this, you should put some effort into benchmarking your whole application under the worst possible load! You can use Super Smack for this, and it is available at: http://www.mysql.com/Downloads/super-smack/super-smack-1.0.tar.gz. As the name suggests, it can bring your system down to its knees if you ask it, so make sure to use it only on your development systems.

Optimizing SELECTs and Other Queries

最初に、全てのクエリに影響する一つの事柄をのべます: より複雑な権限の設定を行うと、オーバーヘッドが多くなります。

もしあなたがいかなる GRANT 文も行っていなければ、 MySQL はパーミッションの検査を少ししか最適化しないでしょう。 So if you have a very high volume it may be worth the time to avoid grants. Otherwise more permission check results in a larger overhead.

もし MySQL 関数のあるものが確実に問題を引き起こしているのならば、 常に MySQL クライアント側は以下のようになります:

mysql> SELECT BENCHMARK(1000000,1+1);
+------------------------+
| BENCHMARK(1000000,1+1) |
+------------------------+
|                      0 |
+------------------------+
1 row in set (0.32 sec)

上の例では MySQL は 1,000,000 + 式を 0.32 秒で実行できています (たんなる PentiumII 400MHz マシンで)。

全ての MySQL 関数は最適化されていますが、 いくつかは例外があるかもしれません。 BENCHMARK(loop_count,expression)はあなたのクエリの 問題を見つけるためのとてもよいツールです。

EXPLAIN 構文 (SELECTについての情報を得る)

    EXPLAIN tbl_name
or  EXPLAIN SELECT select_options

EXPLAIN tbl_name は、 DESCRIBE tbl_nameSHOW COLUMNS FROM tbl_name と同義です。

もし EXPLAIN をともなって SELECT 構文を実行した場合、 MySQL はこの SELECT がいかに動作するかを説明し、 いかにテーブルが結合されるかの情報を与えます。

EXPLAIN の情報を元に、インデックスを使用した速い SELECT を 得るためにテーブルにインデックスを加えなくてはならないという事がわかります。

You should frequently run ANALYZE TABLE to update table statistics such as cardinality of keys which can affect the choices the optimiser makes. See section ANALYZE TABLE Syntax.

テーブル結合の最適化もオプションによって見ることができます。 SELECT 構文での結合を強制的に最適化するには STRAIGHT_JOIN 節を加え ます。

単純ではない join のために、EXPLAINSELECT 文で使用されている それぞれのテーブルの情報を返します。 テーブルは読まれる順に表示されます。MySQL は one-sweep multi-join method を用いた全ての join を解決します。これは MySQL は最初のテーブルから 一レコード読み込み、二つ目のテーブルからマッチしたレコードを探し、そして三番目を 探すということです。 全てのテーブルが処理される時、選択されたフィールドを出力し、テーブルの一覧は よりマッチするレコードをもつテーブルを見つけるまで back-track されます。 次のレコードはこのテーブルから読まれ、次のテーブルから処理を続けます。

In MySQL version 4.1 the EXPLAIN output was changed to work better with constructs like UNIONs, subqueries and derived tables. Most notable is the addition of two new columns: id and select_type.

EXPLAIN の出力は以下のフィールドを含みます:

id
SELECT identifier, the sequential number of this SELECT within the query.
select_type
Type of SELECT clause, which can be any of the following:
SIMPLE
Simple SELECT (without UNIONs or subqueries).
PRIMARY
Outermost SELECT.
UNION
Second and further UNION SELECTs.
DEPENDENT UNION
Second and further UNION SELECTSs, dependent on outer subquery.
SUBSELECT
First SELECT in subquery.
DEPENDENT SUBSELECT
First SELECT, dependent on outer subquery.
DERIVED
Derived table SELECT.
table
出力レコードが参照されるテーブル
type
join タイプ. join type は以下のものがあります。良い物から順に書いています:
system
テーブルが一レコードだけ持っている (= system table). これは const join type の特別な場合です。
const
テーブルは、最もマッチするレコードを1つもっており、これはクエリの 最初に読まれます。 1 つのレコードであるため、このレコード中のフィールドの値は オプティマイザーによって常数としてみなされます。 1回だけ読まれるので、const テーブルはとても速いです!
eq_ref
前のテーブルのそれぞれのレコードと結合する際、このテーブルから1レコード読まれま す。これは join では const よりも良い形です。 インデックスの全てのパートが join で使用され、かつ、インデックスが UNIQUEPRIMARY KEY であるときに、これは使用されます。
ref
インデックスの値に合ったすべてのレコードは、前のテーブルからレコードと結合するた めに、このテーブルから読まれるでしょう。 もしその join がキーの一番左の接頭部分だけを使用するならば、 あるいは、もしそのキーが UNIQUEPRIMARY KEY でなければ (言い換えるなら、もし join がキーの値を元に一つだけの、レコードを選択できなけれ ば)、ref は使用されます。 もしそのキーがいくつかのマッチするレコードに使用されるだけなら、 join は良い形です。
range
示された範囲内にあるレコードのみが検索されます。 key 項目はどのインデックスが使用されているか示します。 The key_len contains the longest key part that was used. The ref column will be NULL for this type.
index
ALL と同じですが、インデックスツリーが走査される場合のみを除きます。 これは、インデックスファイルはデータファイルよりも小さいため、通常 ALL よ り速いです。
ALL
前のテーブルのレコードとのそれぞれの結合において、全テーブルが走査されます。 もしそのテーブルが最初のテーブルで const 状態ではないなら、通常 これは良くありません。他の状態ではとても悪くなります。 これは普通、レコードががより早いテーブルからから定数値に基づいて検索することがで きるように、 インデックスを追加することにより ALL を避けることが可能です。
possible_keys
possible_keys 項目は、MySQL がテーブルからレコードを見つけるために どのインデックスを使用する事ができたかを示します。 注意: このフィールドはテーブルの順にまったく依存しません。これは、 possible_keys 内のいくつかのキーは、生成されたテーブル順での実行に使用でき ないことを意味します。 この項目が空なら、関連した インデックスは無いということです。この場合、あなたは WHERE 節を 調べることによって、クエリの性能を向上させることができるかもしれません。 もしそれがインデックスに適合したフィールドを参照しているならば。 仮にそうだとすると、適切なインデックスを作成し、 EXPLAIN でクエリを もう一度チェックしてみてください。 テーブルがどんなインデックスを持っているかみるには、SHOW INDEX FROM tbl_name とします。
key
key 項目は、 MySQL が使用すると実際に決めたキー(インデックス)を示します。 どのインデックスも選ばれなかったならば、インデックスは NULL です。 MySQL に possible_keys 項目にあるインデックスを使用するように 強制するにはクエリに USE KEY/IGNORE KEY を使用することができます。 See section SELECT 構文. Also, running myisamchk --analyze (see section myisamchk 起動構文) or ANALYZE TABLE (see section ANALYZE TABLE Syntax) on the table will help the optimiser choose better indexes.
key_len
key_len 項目は、MySQL が使用すると決めたキーの長さを示します。 もし keyNULL なら、長さは NULL です。 注意: これはMySQL がマルチパートキーのいくつのパートを実際に使用 するかを示します。
ref
ref 項目は、テーブルからレコードを select するために、どのフィールドや 定数が key と共に使用されたかを示します。
rows
rows フィールドは、MySQL がクエリを実行するために検査する 必要があると考えているレコードの数を示します。
Extra
このフィールドは、MySQL がどのようにクエリを解決するかの追加情報 を含んでいます。ここで、このフィールドに現れ得る様々なテキスト文字列の説明 をします:
Distinct
MySQL will not continue searching for more rows for the current row combination after it has found the first matching row.
Not exists
MySQL はクエリの LEFT JOIN 最適化を行なうことができて、 LEFT JOIN 判定基準に適合する1つのレコードを見つけた後、前のレコード組 み合わせについてこのテーブルにそれ以上のレコードを検査しません。 Here is an example for this:
SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;
Assume that t2.id is defined with NOT NULL. In this case MySQL will scan t1 and look up the rows in t2 through t1.id. If MySQL finds a matching row in t2, it knows that t2.id can never be NULL, and will not scan through the rest of the rows in t2 that has the same id. In other words, for each row in t1, MySQL only needs to do a single lookup in t2, independent of how many matching rows there are in t2.
range checked for each record (index map: #)
MySQL は使用すべき本当に良いインデックスを見つけられませんでし た。先行するテーブル内に各レコードの結合の代わりに、テーブルからレコード を取り出すためにどのインデックスを使用するかチェックを行ないます。これは とても速いというわけではありませんが、もちろんインデックス無しでの結合を 行なわなければならないよりは速いです。
Using filesort
MySQL は、ソート順でレコードを取り出す方法を見つけ出すため、余 計なパスの実行が必要です。ソートは、join type に一致する全てのレ コードを通して行なわれ、WHERE に適合する全てのレコードについて、 ソートキーとレコードへのポインタを格納します。それから、キーがソートされま す。最後にレコードはソートされた順に取り出されます。
Using index
フィールド情報は、実際のレコードから読み込む追加シークを行なうことはせず に、インデックスツリー内の情報だけを使用するテーブルから取り出されます。 テーブルについての使用される全てのフィールドが同じインデックスの一部であ る時にこれが行なわれます。
Using temporary
クエリを解決できるように、MySQL は、結果を保持するための一時テー ブルを作成する必要があります。これは通常 GROUP BY が行なわれたも のとは別のフィールド上で ORDER BY を行なう場合に発生します。
Using where
どのレコードが次のテーブルに対して適合するか、またはクライアントに送られ るかを制限するために、WHERE 節が使用されます。この情報がなくて、 テーブルが型 ALLindex であれば、クエリ内に何か間違った ものがあります(テーブルから全てのレコードを fetch/examine しようとしてい るのでなければ)。
クエリを可能な限り速く得たい場合、Using filesortUsing temporary に注意すべきです。

EXPLAIN 出力の rows フィールド内のすべての値を増やすことによ り、join がどのように良くなるかの良い表示を得ることができます。これは、 MySQL がクエリ実行の検査をする必要があるレコードのおおよその数を 知らせます。この数は max_join_size 変数でのクエリを制限する時にも使 用します。 See section サーバーパラメーターのチューニング.

以下の例は、EXPLAIN が提供する情報を元に、いかに JOIN が最適化 できるかの例です。

以下のような EXPLAIN で検査する SELECT 構文があるとします:

EXPLAIN SELECT tt.TicketNumber, tt.TimeIn,
            tt.ProjectReference, tt.EstimatedShipDate,
            tt.ActualShipDate, tt.ClientID,
            tt.ServiceCodes, tt.RepetitiveID,
            tt.CurrentProcess, tt.CurrentDPPerson,
            tt.RecordVolume, tt.DPPrinted, et.COUNTRY,
            et_1.COUNTRY, do.CUSTNAME
        FROM tt, et, et AS et_1, do
        WHERE tt.SubmitTime IS NULL
            AND tt.ActualPC = et.EMPLOYID
            AND tt.AssignedPC = et_1.EMPLOYID
            AND tt.ClientID = do.CUSTNMBR;

この例では、以下のように仮定します:

最初、いかなる最適化も行われていない状態では、EXPLAIN 構文は 以下の情報を提示します:

table type possible_keys                key  key_len ref  rows  Extra
et    ALL  PRIMARY                      NULL NULL    NULL 74
do    ALL  PRIMARY                      NULL NULL    NULL 2135
et_1  ALL  PRIMARY                      NULL NULL    NULL 74
tt    ALL  AssignedPC,ClientID,ActualPC NULL NULL    NULL 3872
      range checked for each record (key map: 35)

それぞれのテーブルで、typeALL になっています。 これは MySQL が全てのテーブルを全結合することを示します! それぞれのテーブル内の行数分から作った物が調べられるので、とても長い時間がかかり ます! この場合、74 * 2135 * 74 * 3872 = 45,268,558,720 行調べることになります。 テーブルが肥大化したときにかかる時間を考えてください....

一つ問題があります。(まだ) MySQL がフィールドのインデックスを効果的に 使用できていません。 この例の場合では、VARCHARCHAR は、それらが同じ長さで定義されて いれば、変わりがありません。 tt.ActualPCCHAR(10) と定義されており、 et.EMPLOYIDCHAR(15) です。これらの長さは違います。

この不釣り合いを修正するにあたり、ALTER TABLE を使って ActualPC の長さを 10 文字から 15 文字にします:

mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15);

これで tt.ActualPC and et.EMPLOYID は両方とも VARCHAR(15) になりました。 EXPLAIN 構文を実行し直すと、以下を提示します:

table type   possible_keys   key     key_len ref         rows    Extra
tt    ALL    AssignedPC,ClientID,ActualPC NULL NULL NULL 3872    Using where
do    ALL    PRIMARY         NULL    NULL    NULL        2135
      range checked for each record (key map: 1)
et_1  ALL    PRIMARY         NULL    NULL    NULL        74
      range checked for each record (key map: 1)
et    eq_ref PRIMARY         PRIMARY 15      tt.ActualPC 1

まだ完全ではありませんが、よりよくなっています(rows 値の 生成量は 74 より小さくなります)。この場合、実行は数秒でしょう。

A second alteration can be made to eliminate the column length mismatches for the tt.AssignedPC = et_1.EMPLOYID and tt.ClientID = do.CUSTNMBR comparisons:

mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15),
    ->                MODIFY ClientID   VARCHAR(15);

これで EXPLAIN は以下を出力します:

table type   possible_keys   key      key_len ref           rows Extra
et    ALL    PRIMARY         NULL     NULL    NULL          74
tt    ref    AssignedPC,     ActualPC 15      et.EMPLOYID   52   Using where
             ClientID,
             ActualPC
et_1  eq_ref PRIMARY         PRIMARY  15      tt.AssignedPC 1
do    eq_ref PRIMARY         PRIMARY  15      tt.ClientID   1

これは ``ほとんど'' 最良に近いです。

残る問題は、デフォルトでは、MySQL は tt.ActualPC フィールド内の 値がまんべんなく分布していると想定しており、この tt テーブルの場合には 適合しません。 幸運にも、これを MySQL に教えるのはとても簡単です:

shell> myisamchk --analyze PATH_TO_MYSQL_DATABASE/tt
shell> mysqladmin refresh

これで join は ``完璧'' です。 EXPLAIN は以下の結果を示します:

table type   possible_keys key     key_len ref           rows Extra
tt    ALL    AssignedPC    NULL    NULL    NULL          3872 Using where
             ClientID,
             ActualPC
et    eq_ref PRIMARY       PRIMARY 15      tt.ActualPC   1
et_1  eq_ref PRIMARY       PRIMARY 15      tt.AssignedPC 1
do    eq_ref PRIMARY       PRIMARY 15      tt.ClientID   1

EXPLAIN の出力中の rows 項目は、 MySQL JOIN オプティマイ ザーによる、``推測'' です; クエリの最適化のために、この数値が実際に近いかどうかをチェックすべきです。 そうでなければ、SELECT ステートメントで STRAIGHT_JOIN を使用 し、FROM 節に異なる順でテーブルを並べることで、良いパフォーマンスを 得られます。

Estimating Query Performance

ほとんどの場合、ディスク・シークを数えることでだいたいのパフォーマンスを予測でき ます。 小さなテーブルでは、通常、1回のディスク・シークでレコードを見つけれるでしょう (インデックスがたぶんキャッシュされるので)。 大きなテーブルでは、 おおよその予測として、(B++ ツリーインデックスを使用している場合)、 log(row_count) / log(index_block_length / 3 * 2 / (index_length + data_pointer_length)) + 1 シーク、1レコードを見つけるのに必要となるでしょう。

MySQL では、インデックス・ブロックは通常 1024 バイトで、 データ・ポインターは通常 4 バイトです。 これは、 インデックス長が 3 (medium integer) 、データが 500,000 レコードあるテーブルでは、 log(500,000)/log(1024/3*2/(3+4)) + 1 = 4 シークとなります。

As the above index would require about 500,000 * 7 * 3/2 = 5.2M, (assuming that the index buffers are filled to 2/3, which is typical) you will probably have much of the index in memory and you will probably only need 1-2 calls to read data from the OS to find the row.

書き込み時には、上の場合、新しいインデックスを書き込める場所を 探し出すのに、4 シークかかり、さらに、通常、インデックスを更新し、 レコードを書くのに 2 シーク必要です。

Note that the above doesn't mean that your application will slowly degenerate by log N! As long as everything is cached by the OS or SQL server things will only go marginally slower while the table gets bigger. After the data gets too big to be cached, things will start to go much slower until your applications is only bound by disk-seeks (which increase by log N). To avoid this, increase the index cache as the data grows. See section サーバーパラメーターのチューニング.

SELECT クエリの速度

通常、遅い SELECT ... WHERE を速くするには、 まず最初にインデックスがあるかどうかをチェックします。 See section MySQL はどのようにインデックスを使用するか?. 違うテーブルを参照する場合には、普通はインデックスをともなうべきです。 EXPLAIN コマンドを使用すれば、SELECT でどのインデックスが 使用されているか確認できます。 See section EXPLAIN 構文 (SELECTについての情報を得る).

Some general tips:

MySQL はどのように WHERE 節を最適化するか?

WHERE の最適化は、WHERE がほとんど SELECT で使用されるため、 SELECT に置かれています。 しかし、同じ最適化は DELETEUPDATE 文でも使用されます。

このセクションの最適化の説明はまだ不十分です。 なぜなら、 MySQL はとても多くの最適化を行っており、 それら全てについての説明を書ける時間が、我々はとれません。

MySQLによる最適化のいくつかを以下に示します:

以下はとても速いクエリの例です:

mysql> SELECT COUNT(*) FROM tbl_name;
mysql> SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name;
mysql> SELECT MAX(key_part2) FROM tbl_name
    ->        WHERE key_part_1=constant;
mysql> SELECT ... FROM tbl_name
    ->        ORDER BY key_part1,key_part2,... LIMIT 10;
mysql> SELECT ... FROM tbl_name
    ->        ORDER BY key_part1 DESC,key_part2 DESC,... LIMIT 10;

以下のクエリはインデックスツリーのみを使用します(インデックス化されているフィー ルドは数値型と仮定します):

mysql> SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val;
mysql> SELECT COUNT(*) FROM tbl_name
    ->        WHERE key_part1=val1 AND key_part2=val2;
mysql> SELECT key_part2 FROM tbl_name GROUP BY key_part1;

以下のクエリは、ソートされた行の検索にインデックスを使用します:

mysql> SELECT ... FROM tbl_name
    ->            ORDER BY key_part1,key_part2,... ;
mysql> SELECT ... FROM tbl_name
    ->            ORDER BY key_part1 DESC,key_part2 DESC,... ;

How MySQL Optimizes DISTINCT

DISTINCT is converted to a GROUP BY on all columns, DISTINCT combined with ORDER BY will in many cases also need a temporary table.

When combining LIMIT # with DISTINCT, MySQL will stop as soon as it finds # unique rows.

If you don't use columns from all used tables, MySQL will stop the scanning of the not used tables as soon as it has found the first match.

SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;

In the case, assuming t1 is used before t2 (check with EXPLAIN), then MySQL will stop reading from t2 (for that particular row in t1) when the first row in t2 is found.

MySQL はどのように LEFT JOINRIGHT JOIN を最適化するか?

MySQL の A LEFT JOIN B は以下のように組みこまれています:

RIGHT JOIN is implemented analogously as LEFT JOIN.

The table read order forced by LEFT JOIN and STRAIGHT JOIN will help the join optimizer (which calculates in which order tables should be joined) to do its work much more quickly, as there are fewer table permutations to check.

Note that the above means that if you do a query of type:

SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key)
         WHERE b.key=d.key

MySQL will do a full scan on b as the LEFT JOIN will force it to be read before d.

The fix in this case is to change the query to:

SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key)
         WHERE b.key=d.key

How MySQL Optimises ORDER BY

In some cases MySQL can uses index to satisfy an ORDER BY or GROUP BY request without doing any extra sorting.

The index can also be used even if the ORDER BY doesn't match the index exactly, as long as all the unused index parts and all the extra are ORDER BY columns are constants in the WHERE clause. The following queries will use the index to resolve the ORDER BY / GROUP BY part:

SELECT * FROM t1 ORDER BY key_part1,key_part2,...
SELECT * FROM t1 WHERE key_part1=constant ORDER BY key_part2
SELECT * FROM t1 WHERE key_part1=constant GROUP BY key_part2
SELECT * FROM t1 ORDER BY key_part1 DESC,key_part2 DESC
SELECT * FROM t1 WHERE key_part1=1 ORDER BY key_part1 DESC,key_part2 DESC

Some cases where MySQL can not use indexes to resolve the ORDER BY: (Note that MySQL will still use indexes to find the rows that matches the WHERE clause):

In the cases where MySQL have to sort the result, it uses the following algorithm:

You can with EXPLAIN SELECT ... ORDER BY check if MySQL can use indexes to resolve the query. If you get Using filesort in the extra column, then MySQL can't use indexes to resolve the ORDER BY. See section EXPLAIN 構文 (SELECTについての情報を得る).

If you want to have a higher ORDER BY speed, you should first see if you can get MySQL to use indexes instead of having to do an extra sorting phase. If this is not possible, then you can do:

MySQL by default sorts all GROUP BY x,y[,...] queries as if you would have specified ORDER BY x,y[,...]. MySQL will optimise away any ORDER BY as above without any speed penalty. If you by in some cases don't want to have the result sorted you can specify ORDER BY NULL:

INSERT INTO foo SELECT a,COUNT(*) FROM bar GROUP BY a ORDER BY NULL;

MySQL はどのように LIMIT を最適化するか?

In some cases MySQL will handle the query differently when you are using LIMIT # and not using HAVING:

INSERT クエリの速度

レコードを挿入する時間はおおよそ次からなります:

ここで (数字) は比例時間です。これは、テーブルのオープンにかかる初期オーバーヘッ ド(これは同時に動作する各クエリ毎に1回行なわれます)は考慮されていません。

テーブルのサイズはインデックスの挿入を log N で遅くします (B-tree)。

INSERT を速くするいくつかの方法:

LOAD DATA INFILEINSERT を共に速くするためには、 キーバッファを増やします。 See section サーバーパラメーターのチューニング.

UPDATE クエリの速度

UPDATE クエリは SELECT クエリのように最適化されますが、 書き込みのオーバーヘッドが加わります。 書き込み速度は、更新されるデータの大きさ、更新されるインデックス数に 依ります。 変更されないインデックスは更新されません。

Also, another way to get fast updates is to delay updates and then do many updates in a row later. Doing many updates in a row is much quicker than doing one at a time if you lock the table.

Note that, with dynamic record format, updating a record to a longer total length may split the record. So if you do this often, it is very important to OPTIMIZE TABLE sometimes. See section OPTIMIZE TABLE 構文.

DELETE クエリの速度

If you want to delete all rows in the table, you should use TRUNCATE TABLE table_name. See section TRUNCATE 構文.

1レコードを削除する時間は、ちょうどインデックスの数に比例します。 より速くレコードを削除したいなら、インデックス・キャッシュを 増やします。 See section サーバーパラメーターのチューニング.

最適化に関するその他の助言

Unsorted tips for faster systems:

Locking Issues

MySQL はどのようにテーブルをロックするか

付録に、異なるロックする方法に関する議論があります。 See section Locking methods.

MySQL の全てのロックはデッドロックフリーです。(except for InnoDB and BDB type tables.) これは、常にクエ リ開始時に一度ロックを必要とする全てを要求し、常に同じ順でテーブルをロッ クすることで管理されます。

InnoDB type tables automatically acquire their row locks and BDB type tables their page locks during the processing of SQL statements, not at the start of the transaction.

MySQL が使用する WRITE ロックは次のように働きます:

MySQL の READ ロックは次のように動きます:

ロックが解放されたとき、最初に write ロックキュー内のスレッドに、その後 read ロックキュー内のスレッドにロックを与えます。

これは、同じテーブルで多くの更新をする場合、SELECT 構文は update がなくなるまで待たされることを意味します。

同じテーブルで多くの INSERT と多くの SELECT を行う場合、これを解決 するには、他のテーブルに行を挿入して、たまに、その一時テーブルから全ての レコードをもう一方のテーブルに update します。

これは次のコードで行えます:

mysql> LOCK TABLES real_table WRITE, insert_table WRITE;
mysql> INSERT INTO real_table SELECT * FROM insert_table;
mysql> TRUNCATE TABLE insert_table;
mysql> UNLOCK TABLES;

特定の場合での検索を優先的に行いたい場合、 LOW_PRIORITY オプションと共に INSERTUPDATEDELETE 構文、または HIGH_PRIORITY オプションと共に SELECT 構文を使用できます。 また、同様の動作を得るために、 --low-priority-updates オプション と共に mysqld を開始することができます。

SQL_BUFFER_RESULT の使用はさらにテーブル・ロックをより短くするために有効かもしれません。 See section SELECT 構文.

一つのキューだけを使用するように `mysys/thr_lock.c' 内のロックコードを変更 することもできます。この場合、いくつかのアプリケーションのために、 write ロックは read ロックと同じ優先順位にします。

テーブル・ロッキングの問題

MySQL のテーブル・ロッキングのコードはデッドロック・フリーです。

MySQL はとても速いロックスピードを得るために、 (レコードのロックやフィールドのロックの代わりに) テーブルのロックを使用します。 (except InnoDB and BDB tables) 大きなテーブルには、 テーブルのロックはレコードのロックよりはるかに良いですが、 いくつかの落とし穴があります。

BDBInnoDB のテーブルでは、 LOCK TABLES を使用して 明示的にテーブルをロックするか、 ALTER TABLE のようなテーブル中のすべて のレコードを修正するコマンドを実行した場合にのみ、MySQLはテーブル・ロッキングを使用 します。これらのテーブル・タイプについては、 LOCK TABLES を全く使用 しないことを推奨します。 because InnoDB uses automatic row level locking and BDB uses page level locking to ensure transaction isolation.

MySQL バージョン 3.23.7 以上では、 あるスレッドが MyISAM テーブルを読んでいる最中に、 同じテーブルにレコードを挿入する事ができます。 現在、これは挿入が行われる時に、テーブルのレコードを削除した後にホールがない場合にのみ 動作することに注意してください。すべてのホールが新しいデータで満たされた時に、 自動的に同時挿入が再び可能になります。

テーブルのロックはたくさんのスレッドが同時にあるテーブルから読み出すのを可能にし ますが、もしあるスレッドがあるテーブルに対し書込み要求を出す場合、 それはまず最初に排他的なアクセスを得なければなりません. その更新の間、更新が完了するまで、この特定のテーブルにアクセスしようとする 他の全てのスレッドが待たされることになります。

通常データベースの更新は SELECT よりも重要とされるため、 テーブルを更新する全てのスレッドが、テーブルから情報を検索するスレッドよりも 高い優先順位を持ちます。 これは ある特定のテーブルに対して、多くの重いクエリが発 行された場合に、 更新が不完全に終わらないことを確実にするためです。 (これは、 LOW_PRIORITY と共に更新を行うステートメントを用いるか、 HIGH_PRIORITY と共に SELECT ステートメントを用いることにより 変更が可能です。)

MySQL バージョン 3.23.7 から、max_write_lock_count 変数が使用で きます。 これは、一つのテーブルに対して、指定された回数だけ INSERT が行われた後に、 SELECT を発行するようにします。

テーブルロッキングは以下の場合にはあまり良くありません:

この問題のいくつかの可能な解決は以下の通りです:

Optimizing Database Structure

Design Choices

MySQL は、レコードのデータとインデックスを別のファイルに保存します。 他の多くの(ほとんど全て)データベースでは、同じファイルにデータとインデックスを 混在させて保存します。 我々は、最近のシステムには、MySQL の選択の方が 良いと信じています。

Another way to store the row data is to keep the information for each column in a separate area (examples are SDBM and Focus). This will cause a performance hit for every query that accesses more than one column. Because this degenerates so quickly when more than one column is accessed, we believe that this model is not good for general purpose databases.

The more common case is that the index and data are stored together (like in Oracle/Sybase et al). In this case you will find the row information at the leaf page of the index. The good thing with this layout is that it, in many cases, depending on how well the index is cached, saves a disk read. The bad things with this layout are:

可能な限りデータを小さくする

One of the most basic optimization is to get your data (and indexes) to take as little space on the disk (and in memory) as possible. This can give huge improvements because disk reads are faster and normally less main memory will be used. Indexing also takes less resources if done on smaller columns.

MySQL supports a lot of different table types and row formats. Choosing the right table format may give you a big performance gain. See section MySQL テーブル型.

以下に挙げるテクニックを使用すれば、テーブルでのパフォーマンスの向上、 保存領域の縮小化が可能でしょう:

MySQL はどのようにインデックスを使用するか?

Indexes are used to find rows with a specific value of one column fast. インデックスがない場合、MySQL は、そのレコードが見つかるまで、 最初のレコードからテーブルをなめていきます。 大きなテーブルでは多くの 手間がかかります。 もし問い合わせの中にインデックスを持ったフィールドが ある場合、MySQL は全てのデータをみることなく、データの途中の位置を速く 得ることができます。 もしあるテーブルが1000レコード持っていたとすると、 順番に頭からなめていくことに比べて、これは少なくとも100倍速いことに なります。 Note that if you need to access almost all 1000 rows it is faster to read sequentially because we then avoid disk seeks.

全ての MySQL インデックス, PRIMARY, UNIQUE そして INDEX() は B tree に格納されます。 文字列は自動的に始めと終りの空白が圧縮されます。 See section CREATE INDEX 構文.

Indexes are used to:

以下のような SELECT 文を発行したとします:

mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;

もし col1col2 に複数フィールドインデックスが定義されている場合、 すぐに思ったとおりの結果が得られます。 If separate single-column indexes exist on col1 and col2, the optimizer tries to find the most restrictive index by deciding which index will find fewer rows and using that index to fetch the rows.

もしテーブルが複数フィールドインデックスを持つなら、インデックスの接頭部一番左の 部分がレコードを見つけるための最適化に使用されます。例えば、3つのフィールド (col1,col2,col3) に対して一つのインデックスを持っていたとします。 すると、これは (col1), (col1,col2) , (col1,col2,col3) でインデックスがサーチされます。

もし一番左に指定しているフィールドがインデックスを作成していないなら、 MySQL は部分的なインデックスを使用しません。

以下のような SELECT 文を発行したとします:

mysql> SELECT * FROM tbl_name WHERE col1=val1;
mysql> SELECT * FROM tbl_name WHERE col2=val2;
mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

もしインデックスが (col1,col2,col3) にあるならば、 上に示した最初のクエリだけがインデックスを使用します。二番目三番目のクエリは インデックスを持つフィールドを発動しますが、 (col2)(col2,col3) は、(col1,col2,col3) の 接頭部一番左に指定されていません。

MySQL は、もし LIKE がワイルドカードから始まっていなくて、 ある種固定された文字で始まっているなら、 LIKE の評価にインデックスを使用します。 例えば、以下の SELECT 文はインデックスを使用します:

mysql> SELECT * FROM tbl_name WHERE key_col LIKE "Patrick%";
mysql> SELECT * FROM tbl_name WHERE key_col LIKE "Pat%_ck%";

一つ目の文は、"Patrick" <= key_col < "Patricl" となるレコードだけ、考慮さ れます。 二つ目の文は、"Pat" <= key_col < "Pau" となるレコードだけ、考慮されます。

以下の SELECT 文はインデックスを使用しません:

mysql> SELECT * FROM tbl_name WHERE key_col LIKE "%Patrick%";
mysql> SELECT * FROM tbl_name WHERE key_col LIKE other_col;

最初の文は、LIKE がワイルドカード文字で始まっています。 二つ目の文は、LIKE が定数ではありません。

MySQL 4.0 does another optimisation on LIKE. If you use ... LIKE "%string%" and string is longer than 3 characters, MySQL will use the Turbo Boyer-Moore algorithm to initialise the pattern for the string and then use this pattern to perform the search quicker.

Searching using column_name IS NULL will use indexes if column_name is an index.

MySQL は通常、一番少ないレコード数を見つけるインデックスを使用します。 インデックスは次に示す演算子を用いて比較できるフィールドに対して使用されます: =, >, >=, <, <=, BETWEEN そして 'something%' の様に頭にワイルドカードがない LIKE

WHERE 節内の全ての AND にかからないインデックスは、 全くクエリの最適化に使用されません。 In other words: To be able to use an index, a prefix of the index must be used in every AND group.

以下の WHERE 節はインデックスを使用します:

... WHERE index_part1=1 AND index_part2=2 AND other_column=3
... WHERE index=1 OR A=10 AND index=2      /* index = 1 OR index = 2 */
... WHERE index_part1='hello' AND index_part_3=5
          /* optimized like "index_part1='hello'" */
... WHERE index1=1 and index2=2 or index1=3 and index3=3;
          /* Can use index on index1 but not on index2 or index 3 */

以下の WHERE 節はインデックスを使用しません

... WHERE index_part2=1 AND index_part3=2  /* index_part_1 is not used */
... WHERE index=1 OR A=10                  /* Index is not used in
                                                        both AND parts */
... WHERE index_part1=1 OR index_part2=10  /* No index spans all rows  */

Note that in some cases MySQL will not use an index, even if one would be available. Some of the cases where this happens are:

Column Indexes

MySQL の全てのフィールドはインデックスを持つことができます。 適切なフィールドでのインデックスの使用は、SELECT の 性能を向上する最良の方法です。

キーの最大数と最大インデックス長は storage engine 毎に定義されます。 See section MySQL テーブル型。すべてのテーブルハンドラで少なくとも 16 個のキーと少な くとも合計 256 バイトのインデックス長を持つことができます。

CHARVARCHAR フィールドには接頭部にインデックスを持つことが できます。フィールド全体をインデックス化するより、 これははるかに早く、少ないディスク容量でできます。

CREATE TABLE 構文でフィールドにインデックスを作るには、 以下のようにします:

KEY index_name (col_name(length))

以下の例は name フィールドの最初の10文字にインデックスを創り出します:

mysql> CREATE TABLE test (
    ->        name CHAR(200) NOT NULL,
    ->        KEY index_name (name(10)));

BLOBTEXT フィールドでは、そのフィールドの頭の部分に インデックスを張らなくてはなりません。 フィールドの全体にインデックスは張れません。

MySQL バージョン 3.23.23 以降では、特殊な FULLTEXT イン デックスを生成することもできます。これは全文検索に使用されます。 MyISAM テーブル型だけが FULLTEXT インデックスをサポートしま す。これは CHAR, VARCHARTEXT フィールドだけに生成できます。イ ンデックスは常にフィールド全体に対して行なわれ、部分インデックスはサポート されません。詳細は section MySQL Full-text Search.

Multiple-Column Indexes

MySQL は異なるフィールドのセットに一つのインデックスを持つことができます。 インデックスは最大15個のコラムまで許されます。 (CHARVARCHAR フィールドの接頭部をインデックスとして使用できます)

複数フィールドインデックスは、 ソートされた配列(インデックス化されたフィールドの値が結合されている配列) を扱うことができます。

インデックス化されたコラムに対して、既知の値を WHERE 節で指定した時、 たとえ他のフィールドの値を指定しなくとも、 MySQL は複数フィールドインデックスを使用します。

以下のテーブルがあると仮定してください:

mysql> CREATE TABLE test (
    ->       id INT NOT NULL,
    ->       last_name CHAR(30) NOT NULL,
    ->       first_name CHAR(30) NOT NULL,
    ->       PRIMARY KEY (id),
    ->       INDEX name (last_name,first_name));

name インデックスは、last_namefirst_name にまたがるイン デックスです。 このインデックスは、last_name に対するクエリや、 name インデックスは以下のクエリで使われます:

mysql> SELECT * FROM test WHERE last_name="Widenius";

mysql> SELECT * FROM test WHERE last_name="Widenius"
    ->                    AND first_name="Michael";

mysql> SELECT * FROM test WHERE last_name="Widenius"
    ->                    AND (first_name="Michael" OR first_name="Monty");

mysql> SELECT * FROM test WHERE last_name="Widenius"
    ->                    AND first_name >="M" AND first_name < "N";

しかし name インデックスは以下のクエリでは使用されません:

mysql> SELECT * FROM test WHERE first_name="Michael";

mysql> SELECT * FROM test WHERE last_name="Widenius"
    ->                    OR first_name="Michael";

MySQL がクエリの性能を上げるためにどうインデックスを使用しているか、 より詳しい情報はこちら: section MySQL はどのようにインデックスを使用するか?.

何故そんなに多くのテーブルをオープンするのか?

mysqladmin status を実行すると、次のようなものが得られます:

Uptime: 426 Running threads: 1 Questions: 11082 Reloads: 1 Open tables: 12

確かにたった6個しかテーブルがないのに、このような結果が出るので少々戸惑われるか もしれません。

MySQL はマルチスレッドなので、同じテーブルで一度に多くのクエリを持て ます。 同じファイル上では2つスレッドはそれぞれ別の異なる状態を持つという 問題を最小化するため、テーブルは同時に動作する各スレッドにより個々に オープンされます。 これは少しメモリを食いますが、パフォーマンスは良くなります。 ISAMMyISAM テーブルでは、データファイルのために 一つのファイル記述子を使用します。 インデックスファイル記述子は全てのスレッド間で共有されます。

You can read more about this topic in the next section. See section MySQL はどのようにテーブルのオープン & クローズを行なうか?.

MySQL はどのようにテーブルのオープン & クローズを行なうか?

table_cache , max_connections , max_tmp_tables は サーバーが開いた状態にしておく事が出来るファイルの最大数に影響します。 もしこれらの変数のうちの一つ、あるいは複数を増加させるなら、 あなたのオペレーティング・システムの、1 プロセスあたりに開かれる ファイル・デスクリプタ の最大値を増やすことになるかもしれません。 多くのシステムではこの制限を増やすことが可能です。 これをどうやって行うかは、あなたの使用している OS のドキュメントを見てください。 制限値の変更方法は、システムによってまちまちだからです。

table_cachemax_connections に関連します。 例えば 200 のコネクションを同時に開けるなら、少なくとも 200 * n の テーブル・キャッシュが必要です。 ここで n は join におけるテーブルの 最大数です。 You also need to reserve some extra file descriptors for temporary tables and files.

Make sure that your operating system can handle the number of open file descriptors implied by the table_cache setting. If table_cache is set too high, MySQL may run out of file descriptors and refuse connections, fail to perform queries, and be very unreliable. You also have to take into account that the MyISAM storage engine needs two file descriptors for each unique open table. You can in increase the number of file descriptors available for MySQL with the --open-files-limit=# startup option. See section File Not Found.

オープンテーブルのキャッシュは最大で table_cache まで大きくなります(デ フォルトは 64, mysqld のオプション -O table_cache=# で変更可能)。 Note that in MySQL may temporarly open even more tables to be able to execute queries.

A not used table is closed and removed from the table cache under the following circumstances:

キャッシュがいっぱいになった場合、サーバーは以下の処置を取って キャッシュを使用できるように配置します:

テーブルは各同時アクセスに (再び) オープンされます。これは、同じテーブルで2つの スレッドが実行されている場合、または同じクエリで(AS で)テーブルを2回 アクセスする場合、テーブルは2回オープンする必要があることを意味します。 最初のテーブルのオープンは2つのファイル記述子を使用し、続くテーブルの各使用は 1つだけのファイル記述子を使用します。

If you are opening a table with the HANDLER table_name OPEN statement, a dedicated table object is allocated for the thread. This table object is not shared by other threads an will not be closed until the thread calls HANDLER table_name CLOSE or the thread dies. See section HANDLER Syntax. When this happens, the table is put back in the table cache (if it isn't full).

You can check if your table cache is too small by checking the mysqld variable Opened_tables. If this is quite big, even if you haven't done a lot of FLUSH TABLES, you should increase your table cache. See section SHOW STATUS.

Drawbacks to Creating Large Numbers of Tables in the Same Database

もしたくさんのファイルが一つのディレクトリにある場合、オープン、クローズ、 create 操作は遅くなるでしょう。 もし SELECT 文を多くのテーブルに対し 実行した場合、テーブルキャッシュが一杯ならば、このオーバーヘッドは多くなるでしょ う。 なぜなら、それぞれのテーブルにつきオープンし、クローズしなくてはならないからです。 このオーバーヘッドを緩和するには、テーブルキャッシュを大きくします。

Optimizing the MySQL Server

システム、コンパイル時、スタートパラメターのチューニング

We start with the system level things since some of these decisions have to be made very early. In other cases a fast look at this part may suffice because it not that important for the big gains. However, it is always nice to have a feeling about how much one could gain by changing things at this level.

使うべき OS はとても重要です! 複数の CPU を持つマシンでは、 Solaris (なぜなら、Solaris のスレッドはとても素晴らしく動作するから)、 あるいは、Linux ( kernel 2.2 は良い SMP をサポートしているから) を 使用すべきです。 32bit マシンの Linux では、2G bytes のファイルサイズの 制限があります。 これは新しいファイルシステム (XFS/ReiserFS) のリリース時に なくなって欲しいものです。 If you have a desperate need for files bigger than 2G on Linux-intel 32 bit, you should get the LFS patch for the ext2 file system.

Because we have not run MySQL in production on that many platforms, we advice you to test your intended platform before choosing it, if possible.

Other tips:

サーバーパラメーターのチューニング

mysqld サーバーが使用している現在のバッファサイズを次で得ることができます:

shell> mysqld --help

この結果、全ての mysqld オプションと次のようなコンフィグ可能変数のリスト を得られます。出力結果にはデフォルト値が含まれ、以下のように表示されます:

Possible variables for option --set-variable (-O) are:
back_log                 current value: 5
bdb_cache_size           current value: 1048540
binlog_cache_size        current value: 32768
connect_timeout          current value: 5
delayed_insert_timeout   current value: 300
delayed_insert_limit     current value: 100
delayed_queue_size       current value: 1000
flush_time               current value: 0
interactive_timeout      current value: 28800
join_buffer_size         current value: 131072
key_buffer_size          current value: 1048540
lower_case_table_names   current value: 0
long_query_time          current value: 10
max_allowed_packet       current value: 1048576
max_binlog_cache_size    current value: 4294967295
max_connections          current value: 100
max_connect_errors       current value: 10
max_delayed_threads      current value: 20
max_heap_table_size      current value: 16777216
max_join_size            current value: 4294967295
max_sort_length          current value: 1024
max_tmp_tables           current value: 32
max_write_lock_count     current value: 4294967295
myisam_sort_buffer_size  current value: 8388608
net_buffer_length        current value: 16384
net_retry_count          current value: 10
net_read_timeout         current value: 30
net_write_timeout        current value: 60
read_buffer_size         current value: 131072
record_rnd_buffer_size   current value: 131072
slow_launch_time         current value: 2
sort_buffer              current value: 2097116
table_cache              current value: 64
thread_concurrency       current value: 10
tmp_table_size           current value: 1048576
thread_stack             current value: 131072
wait_timeout             current value: 28800

Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own.

もし mysqld サーバーを走らせているなら、以下のコマンドでも変数の値を見る ことができます:

shell> mysqladmin variables

You can find a full description for all variables in the SHOW VARIABLES section in this manual. See section SHOW VARIABLES.

You can also see some statistics from a running server by issuing the command SHOW STATUS. See section SHOW STATUS.

MySQL はとてもスケーラブルなアルゴリズムを使用します。そのため 通常はとても少ないメモリで動作します。しかし MySQL に多くのメモリを 与えれば、より良い性能を得ることができます。

When tuning a MySQL server, the two most important variables to use are key_buffer_size and table_cache. You should first feel confident that you have these right before trying to change any of the other variables.

多くのメモリ(>=256M)と多くのテーブルを持っていて、適度のクライアント数で最大性能 を得たい場合、次のようなものを使用します:

shell> safe_mysqld -O key_buffer=64M -O table_cache=256 \
           -O sort_buffer=4M -O read_buffer_size=1M &

If you have only 128M and only a few tables, but you still do a lot of sorting, you can use something like:

shell> safe_mysqld -O key_buffer=16M -O sort_buffer=1M

多くの接続で少ないメモリしかない場合、次のようなものを使用します

shell> safe_mysqld -O key_buffer=512k -O sort_buffer=100k \
           -O read_buffer_size=100k &

or even:

shell> safe_mysqld -O key_buffer=512k -O sort_buffer=16k \
           -O table_cache=32 -O read_buffer_size=8k -O net_buffer_length=1K &

If you are doing a GROUP BY or ORDER BY on files that are much bigger than your available memory you should increase the value of record_rnd_buffer to speed up the reading of rows after the sorting is done.

When you have installed MySQL, the `support-files' directory will contain some different `my.cnf' example files, `my-huge.cnf', `my-large.cnf', `my-medium.cnf', and `my-small.cnf', you can use as a base to optimize your system.

もしとても多くの接続があり、mysqld が各接続に対して少ないメモリーで 動作するように設定されていれば、スワップの読み書きによるパフォーマンスの低下がお きます。 もちろん十分なメモリーがあれば、全ての接続にたいして mysqld のパフォーマ ンス良くなります。

mysqld へのオプションを変更する場合、そのサーバのインスタンスにだけに 有効であることに注意して下さい。

パラメータ変更の効果を見るには、このようにします:

shell> mysqld -O key_buffer=32m --help

--help オプションは最後につけてください。 その他のオプションを --help の後につけると、そのオプションは反映されません。

MySQL の速度に影響するコンパイルとリンク方法

次のテストの多くは Linux 上で MySQL ベンチマークで行われました。 しかし、これらは他の OS についてもいくつかの指標を与えます。

-static でのリンク時に最速の実行形式を得ます。

Linux では、pgcc-O3 でコンパイルした時に最速のコードを得られます。 このオプションで `sql_yacc.cc' をコンパイルすると、gcc/pgcc は 全ての関数をインラインにするために多くのメモリを必要とするので、200M のメモリが 必要です。 libstdc++ ライブラリの増加を避けるためには、 MySQL の configure 時に CXX=gcc も設定すべきです。 Note that with some versions of pgcc, the resulting code will only run on true Pentium processors, even if you use the compiler option that you want the resulting code to be working on all x586 type processors (like AMD).

より良いコンパイラー、そしてコンパイラーのオプションは、10-30% の 速度の向上をもたらします。 これはあなた自身が MySQL をコンパイルする 時に重要なことです!

我々は Cygnus CodeFusion と Fujitsu コンパイラーでもテストしましたが、 MySQL を最適化オプションでコンパイルするには、 どちらもまだ完全なバグ・フリーではありませんでした。

When you compile MySQL you should only include support for the character sets that you are going to use. (Option --with-charset=xxx). The standard MySQL binary distributions are compiled with support for all character sets.

Here is a list of some measurements that we have done:

The MySQL-Linux distribution provided by MySQL AB used to be compiled with pgcc, but we had to go back to regular gcc because of a bug in pgcc that would generate the code that does not run on AMD. We will continue using gcc until that bug is resolved. In the meantime, if you have a non-AMD machine, you can get a faster binary by compiling with pgcc. The standard MySQL Linux binary is linked statically to get it faster and more portable.

MySQL はどのようにメモリを使用するのか?

以下に mysqld サーバーがどのようにメモリーを使用するか、いくつか示します。 サーバーに与える変数名は、サーバーのメモリーの使用方に関連した名前となっています:

mysqld 実行時、ps や他のプログラムは、それが多くのメモリ を使用していると報告するでしょう。これは異なったメモリアドレス上のスレッ ドスタックによって発生します。例えば、Solaris ps はスタック間の未使用メ モリを使用メモリとして計算します。'swap -s' で有効なスワップをチェックす ることでこれを確かめられます。我々は市販のメモリリーク検出プログラムで mysqld をテストしました。そのため、メモリリークは全くありません。

How MySQL uses DNS

When a new thread connects to mysqld, mysqld will span a new thread to handle the request. This thread will first check if the hostname is in the hostname cache. If not the thread will call gethostbyaddr_r() and gethostbyname_r() to resolve the hostname.

If the operating system doesn't support the above thread-safe calls, the thread will lock a mutex and call gethostbyaddr() and gethostbyname() instead. Note that in this case no other thread can resolve other hostnames that is not in the hostname cache until the first thread is ready.

You can disable DNS host lookup by starting mysqld with --skip-name-resolve. In this case you can however only use IP names in the MySQL privilege tables.

If you have a very slow DNS and many hosts, you can get more performance by either disabling DNS lookop with --skip-name-resolve or by increasing the HOST_CACHE_SIZE define (default: 128) and recompile mysqld.

You can disable the hostname cache with --skip-host-cache. You can clear the hostname cache with FLUSH HOSTS or mysqladmin flush-hosts.

If you don't want to allow connections over TCP/IP, you can do this by starting mysqld with --skip-networking.

SET 構文

SET [GLOBAL | SESSION] sql_variable=expression, [[GLOBAL | SESSION] sql_variable=expression...]

SET OPTION はサーバやクライアントの操作に影響する様々なオプションを設定します. 現在のセッションが終わるか,またはあなたが異なった値にオプションを設定するまで, 設定されたオプション値は残っています.

SET sets various options that affect the operation of the server or your client.

The following examples shows the different syntaxes one can use to set variables:

In old MySQL versions we allowed the use of the SET OPTION syntax, but this syntax is now deprecated.

In MySQL 4.0.3 we added the GLOBAL and SESSION options and access to most important startup variables.

LOCAL can be used as a synonym for SESSION.

If you set several variables on the same command line, the last used GLOBAL | SESSION mode is used.

SET sort_buffer_size=10000;
SET @@local.sort_buffer_size=10000;
SET GLOBAL sort_buffer_size=1000000, SESSION sort_buffer_size=1000000;
SET @@sort_buffer_size=1000000;
SET @@global.sort_buffer_size=1000000, @@local.sort_buffer_size=1000000;

The @@variable_name syntax is supported to make MySQL syntax compatible with some other databases.

The different system variables one can set are described in the system variable section of this manual. See section System Variables.

If you are using SESSION (the default) the option you set remains in effect until the current session ends, or until you set the option to a different value. If you use GLOBAL, which require the SUPER privilege, the option is remembered and used for new connections until the server restarts. If you want to make an option permanent, you should set it in one of the MySQL option files. See section `my.cnf' オプションファイル.

To avoid wrong usage MySQL will give an error if you use SET GLOBAL with a variable that can only be used with SET SESSION or if you are not using SET GLOBAL with a global variable.

If you want to set a SESSION variable to the GLOBAL value or a GLOBAL value to the MySQL default value, you can set it to DEFAULT.

SET max_join_size=DEFAULT;

This is identical to:

SET @@session.max_join_size=@@global.max_join_size;

If you want to restrict the maximum value a startup option can be set to with the SET command, you can specify this by using the --maximum-variable-name command line option. See section mysqld コマンド行オプション.

You can get a list of most variables with SHOW VARIABLES. See section SHOW VARIABLES. You can get the value for a specific value with the @@[global.|local.]variable_name syntax:

SHOW VARIABLES like "max_join_size";
SHOW GLOBAL VARIABLES like "max_join_size";
SELECT @@max_join_size, @@global.max_join_size;

Here follows a description of the variables that uses a the variables that uses a non-standard SET syntax and some of the other variables. The other variable definitions can be found in the system variable section, among the startup options or in the description of SHOW VARIABLES. See section System Variables. See section mysqld コマンド行オプション. See section SHOW VARIABLES.

CHARACTER SET character_set_name | DEFAULT
これは指定されたマッピングに従って、すべての文字列をクライアントからクライアント にマップします. 現在、character_set_name に指定できるオプションは cp1251_koi8 だけですが, MySQL のソース中にある `sql/convert.cc' ファイルを編集することによって, 容易に新しいマッピングを加えることができます. 標準のマッピングに戻すには、 character_set_nameDEFAULT を指定します。 CHARACTER SET オプションを設定するための構文は、 他のオプションを設定する構文と異なっていることに注意してください.
PASSWORD = PASSWORD('some password')
現在のユーザのパスワードを設定します。いかなる非匿名のユーザも、 自分自身パスワードを変えることができます!
PASSWORD FOR user = PASSWORD('some password')
現在ログインしているホストの特定ユーザのパスワードを設定します。 mysql データベースにアクセスができるユーザーだけが実行できます。 ユーザは user@hostname 形式で与えなくてはなりません。 ここで userhostname は、mysql.user テーブルの User, Host フィールドに登録されていなくてはなりません。 例えば、UserHost フィールドが 'bob''%.loc.gov' ならば、以下のようにします:
mysql> SET PASSWORD FOR bob@"%.loc.gov" = PASSWORD("newpass");
Which is equivalent to:
mysql> UPDATE mysql.user SET password=PASSWORD("newpass")
    ->                   WHERE user="bob" AND host="%.loc.gov";
SQL_AUTO_IS_NULL = 0 | 1
1 (デフォルト) を設定すると、次のようにして、auto_increment レコー ドを持つテーブルで、最後に挿入されたレコードを見つけることができます: WHERE auto_increment_column IS NULL。これは、Access のようないくつ かの ODBC プログラムによって使用されます。
AUTOCOMMIT= 0 | 1
1 を設定すると、テーブルへのすべての変更はすぐに行なわれます。 複数コマンドトランザクションを開始するためには、BEGIN ステートメ ントを使用する必要があります。See section BEGIN/COMMIT/ROLLBACK 構文0 を設定すると、そのトランザクションを許可/破棄するために、 COMMIT / ROLLBACK を使用する必要があります。See section BEGIN/COMMIT/ROLLBACK 構文。 注意: 非 AUTOCOMMIT モードから AUTOCOMMIT モードに変更する時、 MySQL はすべてのオープントランザクションを自動的に COMMIT します。
BIG_TABLES = 0 | 1 (ver.4.0.3未満では SQL_BIG_TABLES)
0 の場合、全ての一時テーブルはメモリーではなくディスクに書き出されます。 これは少し遅くなりますが、多くの一時テーブルを必要とする大きな SELECT を 実行しても、The table tbl_name is full エラーが出なくなります。 新しい接続におけるこの値のデフォルト値は 1 (メモリーに一時テーブルを作る) です。
SQL_BIG_SELECTS = 0 | 1
1 の場合、とても時間のかかる SELECT が実行された場合、 MySQL はそれを中止します。 これはあまり芳しくない(間違った) WHERE 構文が発行されたときに役立ちます。 max_join_size 行以上を検討するような SELECT が 大きなクエリと定義されます。 新しい接続におけるこの値のデフォルト値は 0 です。 (全ての SELECT 構文を許します)
SQL_BUFFER_RESULT = 0 | 1
SQL_BUFFER_RESULT は一時ファイルに置かれる SELECT からの結果 を強制的に置きます。これは MySQL がテーブルロックを早く解放する手 助けをし、クライアントへ結果セットを送信するために長い時間が掛かる場合に役 立ちます。
LOW_PRIORITY_UPDATES = 0 | 1
1 の場合、全ての INSERT, UPDATE, DELETE, LOCK TABLE WRITE構文は、 対象となるテーブルを処理中の SELECTLOCK TABLE READ がなくなるまで待ちます。 ver.4.0.3 未満では SQL_LOW_PRIORITY_UPDATES オプションになります.
MAX_JOIN_SIZE = value | DEFAULT
おそらく value よりも多いレコードの組合せを試験する必要があるような SELECT を許可しません。この値を設定することで、キーが使用されないで あろう SELECT と長い時間が掛かるであろう SELECT を捕捉できま す。これを DEFAULT 以外の値に設定すると、SQL_BIG_SELECTS フ ラグをリセットします。SQL_BIG_SELECTS フラグを再び設定すると、 SQL_MAX_JOIN_SIZE 変数は無視されます。-O max_join_size=#mysqld を起動することで、この変数のデフォルト値を設定できます。T ver.4.0.3 未満では SQL_MAX_JOIN_SIZE オプションになります. Note that if the result of the query is already in the query cache, the above check will not be made. Instead, MySQL will send the result to the client. Since the query result is already computed and it will not burden the server to send the result to the client.
QUERY_CACHE_TYPE = OFF | ON | DEMAND
QUERY_CACHE_TYPE = 0 | 1 | 2
Set query cache setting for this thread.
Option Description
0 or OFF Don't cache or retrieve results.
1 or ON Cache all results except SELECT SQL_NO_CACHE ... queries.
2 or DEMAND Cache only SELECT SQL_CACHE ... queries.
SQL_SAFE_UPDATES = 0 | 1
1 に設定すると、WHERE 節内でキーや LIMIT を使用しない で UPDATE または DELETE を行なおうとした場合に MySQL がアボートします。これは、手で SQL コマンドを生成する時の間 違った更新の捕捉を可能にします。
SQL_SELECT_LIMIT = value | DEFAULT
SELECT 構文から返されるレコードの最大値。 もし SELECTLIMIT 節を使用している場合、LIMITSQL_SELECT_LIMIT の値より優先されます。 新しい接続におけるこの値の標準値は ``unlimited''. もしリミットを変えているならば、SQL_SELECT_LIMITDEFAULT を指定することにより、標準値に戻すことができます。
SQL_LOG_OFF = 0 | 1
この値が 1 の場合、もしクライアントが SUPER 権限 (version4.0.2以上。それ未満では PROCESS権限) を持っているならば、 このクライアントのログが行われません。 これは更新ログに影響しません!
SQL_LOG_UPDATE = 0 | 1
0 の場合、もしクライアントが SUPER 権限 (version4.0.2以上。それ未満では PROCESS権限) を持っているならば、 このクライアントの更新ログの記録は行われません。 これは通常のログには影響しません!
SQL_QUOTE_SHOW_CREATE = 0 | 1
If set to 1, SHOW CREATE TABLE will quote table and column names. This is on by default, for replication of tables with fancy column names to work. section SHOW CREATE TABLE.
TIMESTAMP = timestamp_value | DEFAULT
クライアントに時間を設定します。 もしレコードのリストアに更新ログを使用する場合、オリジナルのタイムスタンプを得る ために使用します。 timestamp_value should be a UNIX Epoch timestamp, not a MySQL timestamp.
LAST_INSERT_ID = #
LAST_INSERT_ID() からの返り値を設定します。 テーブルを更新するコマンド中に LAST_INSERT_ID() を使用した場合、 これは更新ログに保存されます。
INSERT_ID = #
AUTO_INCREMENT 値を挿入する時、 INSERT , ALTER TABLE コマンドに従って使用される値をセットします。 これは更新ログによって使用されます。

Disk の問題

シンボリックリンクの使用

テーブルとデータベースのファイルを MySQL のデータベースディレクトリーから 違う場所に移動し、 それに対してシンボリックリンクを張ることができます。例 えば、もっと空き容量のあるファイルシステムへデータベースを移すため、あるい はテーブルを異なるディスクに広げることでシステムのスピードを増加するために これを行ないたくなるでしょう。

The recommended way to do this, is to just symlink databases to a different disk and only symlink tables as a last resort.

Using Symbolic Links for Databases

The way to symlink a database is to first create a directory on some disk where you have free space and then create a symlink to it from the MySQL database directory.

shell> mkdir /dr1/databases/test
shell> ln -s /dr1/databases/test mysqld-datadir

MySQL は一つのディレクトリを複数のデータベースにリンクすることは サポートしていません。シンボリックリンクを持つデータベースディレクトリの複 製は、データベース間のシンボリックリンクを作成しなければ、正常に動作します。 MySQL データディレクトリに db1 データベースがあるとして、 db1 を指すシンボリックリンク db2 を作成します。

shell> cd /path/to/datadir
shell> ln -s db1 db2

すると、db1 中の tbl_a テーブルは db2tbl_a テー ブルとして見えます。 もしあるスレッドが db1.tbl_a を更新し、他のスレッドが db2.tbl_a を 更新した場合、 問題が発生します。

こういった使用をどうしてもしたい場合、`mysys/mf_format.c' を以下のように変 更します:

if (flag & 32 || (!lstat(to,&stat_buff) && S_ISLNK(stat_buff.st_mode)))

to

if (1)

On Windows you can use internal symbolic links to directories by compiling MySQL with -DUSE_SYMDIR. This allows you to put different databases on different disks. See section Windows 上で、異なるディスクにデータを分割する.

Using Symbolic Links for Tables

Before MySQL 4.0 you should not symlink tables, if you are not very careful with them. The problem is that if you run ALTER TABLE, REPAIR TABLE or OPTIMIZE TABLE on a symlinked table, the symlinks will be removed and replaced by the original files. This happens because the above command works by creating a temporary file in the database directory and when the command is complete, replace the original file with the temporary file.

You should not symlink tables on systems that don't have a fully working realpath() call. (At least Linux and Solaris support realpath())

In MySQL 4.0 symlinks are fully supported only for MyISAM tables. For other table types you will probably get strange problems when doing any of the above mentioned commands.

The handling of symbolic links in MySQL 4.0 works the following way (this is mostly relevant only for MyISAM tables).

Things that are not yet supported:

MySQL Language Reference

MySQL has a very complex, but intuitive and easy to learn SQL interface. This chapter describes the various commands, types, and functions you will need to know in order to use MySQL efficiently and effectively. This chapter also serves as a reference to all functionality included in MySQL. In order to use this chapter effectively, you may find it useful to refer to the various indexes.

Language Structure

文字列と数値をどのように書くか?

この節は MySQL で文字列と数値を記述するさまざまな方法を説明します。 MySQL でのこれらの基本型の取り扱い時に、出会うであろうさまざまな ニュアンスと ``了解'' もカバーします。

文字列

文字列は文字の並びです。引用符(`'')または二重引用符(`"')で括ら れます(後者は ANSI モードで実行していない場合のみ)。 例:

'a string'
"another string"

文字列中では、いくつかのシーケンスは特別な意味を持ちます。これらのシーケ ンスのそれぞれはエスケープ文字として知られるバックスラッシュ (`\')で始まります。MySQL は次のエスケープシーケンスを認識 します。

\0
ASCII 0 (NUL) 文字。
\'
引用符(`'')。
\"
二重引用符(`"')。
\b
バックスペース文字。
\n
改行文字。
\r
リターン文字。
\t
タブ文字。
\z
ASCII(26) (Control-Z)。この文字は、ASCII(26) が Windows では END-OF-FILE であるという問題を回避するために、コード化できます。(ASCII(26) は mysql database < filename を使用しようとする場合に問題になります)。
\\
バックスラッシュ(`\')文字。
\%
`%' 文字。これは `%' がワイルドカード文字として解釈される文脈 で、`%' そのものを検索するために使用されます。 See section String Comparison Functions.
\_
_ 文字。これは `_' がワイルドカード文字として解釈される文脈 で、_ そのものを検索するために使用されます。 See section String Comparison Functions.

いくつかの文字列文脈で `\%' または `\_' を使用すると、これらは文 字列 `%'`_' ではなく、`\%'`\_' を返します。

文字列中に引用符を含める方法はいくつかあります:

次の SELECT ステートメントは、クォートとエスケープがどのように働 くかを示します:

mysql> SELECT 'hello', '"hello"', '""hello""', 'hel''lo', '\'hello';
+-------+---------+-----------+--------+--------+
| hello | "hello" | ""hello"" | hel'lo | 'hello |
+-------+---------+-----------+--------+--------+

mysql> SELECT "hello", "'hello'", "''hello''", "hel""lo", "\"hello";
+-------+---------+-----------+--------+--------+
| hello | 'hello' | ''hello'' | hel"lo | "hello |
+-------+---------+-----------+--------+--------+

mysql> SELECT "This\nIs\nFour\nlines";
+--------------------+
| This
Is
Four
lines |
+--------------------+

バイナリデータを BLOB フィールドに挿入したい場合、次の文字をエスケープ シーケンスで表す必要があります:

NUL
ASCII 0。`\0' (バックスラッシュと ASCII `0' 文字) に置き換える べきです。
\
ASCII 92, バックスラッシュ。`\\' と表記してください。
'
ASCII 39, 引用符。`\'' と表記してください。
"
ASCII 34, 二重引用符。`\"' と表記してください。

C コードを書く場合、INSERT 節で文字をエスケープするために、C API 関数 mysql_real_escape_string() を使用できます。See section C API 関数概要. Perl では、DBI パッケージの quote メソッドを使 用して、特殊文字を適当なエスケープシーケンスに変換できます。See section The DBI Interface.

上記の特殊文字のどれかを含む可能性のある全ての文字列について、エスケープ 関数を使用すべきです!

Alternatively, many MySQL APIs provide some sort of placeholder capability that allows you to insert special markers into a query string, and then bind data values to them when you issue the query. In this case, the API takes case of escaping special characters in the values for you automatically.

数値

整数は数字の並びで表現されます。 浮動小数点は `.' で小数を分割します。 どちらの型も負数を表すために `-' を前につけます。

正当な数値の例:

1221
0
-32

有効な浮動小数点の例:

294.42
-32032.6809e+10
148.00

整数が浮動小数点の文脈で使用されるかもしれません; この場合、浮動小数点に 変換されます。

16進法の値

MySQL は16進法の値をサポートします。 数値の文脈では、これらは整数(64ビット精度)のように振る舞います。 文字列の文脈では、hexの桁のそれぞれのペアが文字に変換された バイナリー文字のように振る舞います。

mysql> SELECT x'4D7953514C';
         -> MySQL
mysql> SELECT 0xa+0;
       -> 10
mysql> select 0x5061756c;
       -> Paul

The x'hexstring' syntax (new in 4.0) is based on ANSI SQL and the 0x syntax is based on ODBC. 16進数表記は、ODBC において BLOB の値を与えるためにしばしば使用されます。 You can convert a string or a number to hexadecimal with the HEX() function.

NULL

NULL は ``no data'' を意味し、数値型の 0 や文字列型の空文 字列とは異なることに注意してください。 See section NULL 値での問題.

テキストファイルの読み込みや書き出し時に、NULL\N で 表現されます。 (LOAD DATA INFILE, SELECT ... INTO OUTFILE). See section LOAD DATA INFILE 構文.

データベース名、テーブル名、インデックス名、フィールド名、エイリアス名

データベース名、テーブル名、インデックス名、フィールド名、エイリアス名は MySQL では全て同じ規則に基づきます:

注意: 規則は MySQL 3.23.6 で変更されました。それは識別子(データベー ス名、テーブル名、フィールド名)の ``' でのクォートを導入した時です (ANSI モードで実行する場合は、" も識別子をクォートするために働きま す)。

識別子 最大長 許される文字
データベース 64 ディレクトリ名として許されるすべての文字。/, `\', `.' を除く。
テーブル 64 ファイル名として許されるすべての文字。/. を除く。
フィールド 64 すべての文字
エイリアス 255 すべての文字

注意: 上記に加え、識別子内には ASCII(0) と ASCII(255) を持てません。

注意: 識別子が制限された単語であったり特殊文字を含む場合は、それを使用する 時には常に ` (バッククォート) でクォートする必要があります:

mysql> SELECT * FROM `select` WHERE `select`.id > 100;

See section Is MySQL Picky About Reserved Words?.

MySQL 3.23.6 より前のバージョンでは、名前の規則は次に従います:

1e のような名前は使用しないことを勧めます。1e+1 のような式が あいまいだからです。これは、式 1e + 1 として、または数値 1e+1 として解釈されます。

MySQL では次の形式のいずれかを使用してフィールドを参照できます:

フィールドの参照方法 意味
col_name クエリ中で使用されるテーブル内に存在している col_name という名前のフィールド
tbl_name.col_name 現在のデータベースのテーブル tbl_name 内のフィールド col_name
db_name.tbl_name.col_name データベース db_name のテーブル tbl_name 内のフィールド col_name。この形式は バージョン 3.22 以降で有効です。
`column_name` キーワードであったり特殊文字を含むフィールド。

参照が曖昧でないならば、ステートメント中のフィールド参照の前に tbl_name または db_name.tbl_name を記述する必要はありません。例えば、テー ブル t1t2 がそれぞれフィールド c を含み、t1t2 の両方を使用する SELECT ステートメントで c を取 り出すとします。この場合、c はステートメントで使用されるテーブル 間で唯一でないので曖昧です。そのため、t1.c または t2.c と 記述するこよによりどちらのテーブルを意味するかを示す必要があります。同様 に、データベース db1 のテーブル t とデータベース db2 のテーブル t から取り出す場合、これらのテーブル中の項 目は、db1.t.col_namedb2.t.col_name として参照する必要 があります。

構文 .tbl_name は現在のデータベース内のテーブル tbl_name を意味します。この構文はいくつかの ODBC が `.' 文字をテーブル名の前 に置くために許されています。

名前のケース依存性

MySQL では、データベースとテーブルは、ディレクトリと そのディレクトリ中のファイルに対応します。そのため、下で動作するオペレー ティングシステムのケース依存性は、データベースとテーブル名のケース依存性を決定します。 データベース名とテーブル名は UNIX ではケース依存で、Windows ではケース非依 存です。One prominent exception here is Mac OS X, when the default HFS+ file system is being used. However Mac OS X also supports UFS volumes, those are case sensitive on Mac OS X just like they are on any Unix. See section MySQL の ANSI SQL92 に対する拡張.

注意: Windows ではデータベース名とファイル名はケース非依存ですが、 同じクエリ内で、データベースやテーブルを異なるケースを使用して参照すべき ではありません。 以下のクエリは動きません。なぜなら my_tableMY_TABLE の両方を 参照しているからです:

mysql> SELECT * FROM my_table WHERE MY_TABLE.col=1;

フィールド名とフィールドの別名は全ての場合でケース非依存です。

テーブルの別名はケース依存です。 以下のクエリは動きません。なぜなら aA のエイリアスを両方 参照しているからです:

mysql> SELECT col_name FROM tbl_name AS a
    ->                 WHERE a.col_name = 1 OR A.col_name = 2;

テーブル名に使用されたケースを覚えておくことに問題があるなら、常にデータベー スとテーブルに小文字の名前をつけるというような、一貫した慣習を採用してくだ さい。

この問題を回避する一つの方法は、mysqld-O lower_case_table_names=1 をつけて起動することです。デフォルトではこのオプ ションは Windows では 1 で UNIX では 0 です。

lower_case_table_names が 1 の場合、MySQL はディスク上のす べてのテーブル名を小文字に変換して検索します。 (From version 4.0.2, this option also applies to database names.) 注意: このオプションを変更し た場合、mysqld を起動する前に、最初に古いテーブル名を小文字に変換す ることが必要です。

If you move MyISAM files from a Windows to a Unix disk, you may in some cases need to use the `mysql_fix_extensions' tool to fix-up the case of the file extensions in each specified database directory (lowercase `.frm', uppercase `.MYI' and `.MYD'). `mysql_fix_extensions' can be found in the `scripts' subdirectory.

ユーザー変数

MySQL は、@variablename 構文で接続固有の変数をサポー トします。変数名は現在の文字セットのアルファベットと数字、それに `_'`$'`.' 文字からなります。デフォルト文字セットは ISO-8859-1 Latin1 です。 これは mysqld--default-character-set オプションを 与えることで変更できます. (3.23.14 以上の場合のみ。 それ以前のバージョンでは MySQL 再コンパイルが必要) See section データとソートに使用されるキャラクター・セット.

変数は初期化する必要はありません。デフォルトでは NULL であり、整数 値、実数値、文字列値を格納できます。すべてのスレッド変数は、スレッドが終了 すると自動的に解放されます。

SET 構文で変数を設定できます:

SET @variable= { integer expression | real expression | string expression }
[,@variable= ...].

SET 構文で、式中で変数を設定することも可能です。 However, in this case the assignment operator is := rather than =, because = is reserved for comparisons in non-SET statements:

mysql> SELECT @t1:=(@t2:=1)+@t3:=4,@t1,@t2,@t3;
+----------------------+------+------+------+
| @t1:=(@t2:=1)+@t3:=4 | @t1  | @t2  | @t3  |
+----------------------+------+------+------+
|                    5 |    5 |    1 |    4 |
+----------------------+------+------+------+

(我々は := 構文を使用する必要がありました。= は比較のために 予約されていたからです。)

ユーザー変数は式が許される場所で使用できます。注意: これは現在、 SELECT ステートメントの LIMIT 節、LOAD DATA ステート メントの IGNORE number LINES 節のように、数値が明示的に要求される文 脈での使用を含みません。

注意: SELECT ステートメントでは、それぞれの式はクライアン トに送られた時にだけ評価されます。これは、SELECT 部で設定された変数 を必要とする式を参照する HAVING, GROUP BY, ORDER BY 節ができないことを意味します。例えば、次のステートメントは期待通りには動作 しません:

mysql> SELECT (@aa:=id) AS a, (@aa+3) AS b FROM table_name HAVING b=5;

この理由は、@aa が現在のレコードの値ではなく、前に受け取ったレコー ドの id の値になるからです。

The rule is to never assign and use the same variable in the same statement.

System Variables

Starting from MySQL 4.0.3 we provide better access to a lot of system and connection variables. One can change most of them without having to take down the server.

There are two kind of system variables: Thread-specific (or connection-specific) variables that are unique to the current connection and global variables that are used to configure global events. Global variables also are used to set up the initial values of the corresponding thread-specific variables for new connections.

When mysqld starts, all global variables are initialised from command line arguments and option files. You can change the value with the SET GLOBAL command. When a new thread is created, the thread-specific variables are initialised from the global variables and they will not change even if you issue a new SET GLOBAL command.

To set the value for a GLOBAL variable, you should use one of the following syntaxes: (Here we use sort_buffer_size as an example variable)

SET GLOBAL sort_buffer_size=value;
SET @@global.sort_buffer_size=value;

To set the value for a SESSION variable, you can use one of the following syntaxes:

SET SESSION sort_buffer_size=value;
SET @@session.sort_buffer_size=value;
SET sort_buffer_size=value;

If you don't specify GLOBAL or SESSION then SESSION is used. See section SET 構文.

LOCAL is a synonym for SESSION.

To retrieve the value for a GLOBAL variable you can use one of the following commands:

SELECT @@global.sort_buffer_size;
SHOW GLOBAL VARIABLES like 'sort_buffer_size';

To retrieve the value for a SESSION variable you can use one of the following commands:

SELECT @@session.sort_buffer_size;
SHOW SESSION VARIABLES like 'sort_buffer_size';

When you retrieve a variable value with the @@variable_name syntax and you don't specify GLOBAL or SESSION then MySQL will return the thread-specific (SESSION) value if it exists. If not, MySQL will return the global value.

The reason for requiring GLOBAL for setting GLOBAL only variables but not for retrieving them is to ensure that we don't later run into problems if we later would introduce a thread-specific variable with the same name or remove a thread-specific variable. In this case, you could accidentally change the state for the server as a whole, rather than just for your own connection.

The following is a full list of all variables that you change and retrieve and if you can use GLOBAL or SESSION with them.

Variable name Value type Type
autocommit bool SESSION
big_tables bool SESSION
binlog_cache_size num GLOBAL
bulk_insert_buffer_size num GLOBAL | SESSION
concurrent_insert bool GLOBAL
connect_timeout num GLOBAL
convert_character_set string SESSION
delay_key_write OFF | ON | ALL GLOBAL
delayed_insert_limit num GLOBAL
delayed_insert_timeout num GLOBAL
delayed_queue_size num GLOBAL
error_count num LOCAL
flush bool GLOBAL
flush_time num GLOBAL
foreign_key_checks bool SESSION
identity num SESSION
insert_id bool SESSION
interactive_timeout num GLOBAL | SESSION
join_buffer_size num GLOBAL | SESSION
key_buffer_size num GLOBAL
last_insert_id bool SESSION
local_infile bool GLOBAL
log_warnings bool GLOBAL
long_query_time num GLOBAL | SESSION
low_priority_updates bool GLOBAL | SESSION
max_allowed_packet num GLOBAL | SESSION
max_binlog_cache_size num GLOBAL
max_binlog_size num GLOBAL
max_connect_errors num GLOBAL
max_connections num GLOBAL
max_error_count num GLOBAL | SESSION
max_delayed_threads num GLOBAL
max_heap_table_size num GLOBAL | SESSION
max_join_size num GLOBAL | SESSION
max_sort_length num GLOBAL | SESSION
max_tmp_tables num GLOBAL
max_user_connections num GLOBAL
max_write_lock_count num GLOBAL
myisam_max_extra_sort_file_size num GLOBAL | SESSION
myisam_max_sort_file_size num GLOBAL | SESSION
myisam_sort_buffer_size num GLOBAL | SESSION
net_buffer_length num GLOBAL | SESSION
net_read_timeout num GLOBAL | SESSION
net_retry_count num GLOBAL | SESSION
net_write_timeout num GLOBAL | SESSION
query_cache_limit num GLOBAL
query_cache_size num GLOBAL
query_cache_type enum GLOBAL
read_buffer_size num GLOBAL | SESSION
read_rnd_buffer_size num GLOBAL | SESSION
rpl_recovery_rank num GLOBAL
safe_show_database bool GLOBAL
server_id num GLOBAL
slave_compressed_protocol bool GLOBAL
slave_net_timeout num GLOBAL
slow_launch_time num GLOBAL
sort_buffer_size num GLOBAL | SESSION
sql_auto_is_null bool SESSION
sql_big_selects bool SESSION
sql_big_tables bool SESSION
sql_buffer_result bool SESSION
sql_log_binlog bool SESSION
sql_log_off bool SESSION
sql_log_update bool SESSION
sql_low_priority_updates bool GLOBAL | SESSION
sql_max_join_size num GLOBAL | SESSION
sql_quote_show_create bool SESSION
sql_safe_updates bool SESSION
sql_select_limit bool SESSION
sql_slave_skip_counter num GLOBAL
sql_warnings bool SESSION
table_cache num GLOBAL
table_type enum GLOBAL | SESSION
thread_cache_size num GLOBAL
timestamp bool SESSION
tmp_table_size enum GLOBAL | SESSION
tx_isolation enum GLOBAL | SESSION
version string GLOBAL
wait_timeout num GLOBAL | SESSION
warning_count num LOCAL
unique_checks bool SESSION

Variables that are marked with num can be given a numerical value. Variables that are marked with bool can be set to 0, 1, ON or OFF. Variables that are of type enum should normally be set to one of the available values for the variable, but can also be set to the number that correspond to the enum value. (The first enum value is 0).

Here is a description of some of the variables:

Variable Description
identity Alias for last_insert_id (Sybase compatiblity)
sql_low_priority_updates Alias for low_priority_updates
sql_max_join_size Alias for max_join_size
delay_key_write_for_all_tables If this and delay_key_write are set, then all new MyISAM tables that are opened will use delayed key writes.
version Alias for VERSION() (Sybase (?) compatability)

A description of the other variable definitions can be found in the startup options section, the description of SHOW VARIABLES and in the SET section. See section mysqld コマンド行オプション. See section SHOW VARIABLES. See section SET 構文.

コメント 構文

MySQL は # 行末まで , -- 行末まで そして /* 行中または複数行 */ コメント書式をサポートします:

mysql> SELECT 1+1;     # このコメントは行末まで続く
mysql> SELECT 1+1;     -- このコメントは行末まで続く
mysql> SELECT 1 /* これは行中コメント */ + 1;
mysql> SELECT 1+
/*
これは
複数行コメント
*/
1;

-- コメントスタイルは -- の後ろに最低一つのスペースが 必要であることに注意!

サーバーはコメント構文を理解しますが、 mysql クライアントが /* ... */ コメントを分析するにはいくつか制限があります:

これらの制限は mysql を対話モードで実行している場合と、 mysql にファイルを読み込ませている場合 ( mysql < some-file ) の 両方で現れます。

MySQL は ANSI SQL コメントの `--' をサポートしません。 See section コメント開始としての `--'.

Is MySQL Picky About Reserved Words?

共通の問題は、フィールドの名前を、 TIMESTAMP とか GROUP とかの MySQL に埋め込まれているデータ型や関数名と同名にして、 テーブルを作った場合に起こります。 このようなことは行えます(例えば ABS はフィールド名にできます)。 しかし、関数として使用する場合、 この名前がフィールド名として使用されているなら、 関数名と `(' の間の空白は許されません。

以下の語は MySQL に予約されています。 これらのほとんどは、 ANSI SQL92 によって、 テーブル、フィールド名としての使用は禁止されています。(例えば GROUP)。 またいくつかの語は MySQL が必要とし、 yacc パーサーで 使用しているので予約されています。

Word Word Word
ADD ALL ALTER
ANALYZE AND AS
ASC ASENSITIVE AUTO_INCREMENT
BDB BEFORE BERKELEYDB
BETWEEN BIGINT BINARY
BLOB BOTH BY
CALL CASCADE CASE
CHANGE CHAR CHARACTER
CHECK COLLATE COLUMN
COLUMNS CONDITION CONNECTION
CONSTRAINT CONTINUE CREATE
CROSS CURRENT_DATE CURRENT_TIME
CURRENT_TIMESTAMP CURSOR DATABASE
DATABASES DAY_HOUR DAY_MICROSECOND
DAY_MINUTE DAY_SECOND DEC
DECIMAL DECLARE DEFAULT
DELAYED DELETE DESC
DESCRIBE DETERMINISTIC DISTINCT
DISTINCTROW DIV DOUBLE
DROP ELSE ELSEIF
ENCLOSED ESCAPED EXISTS
EXIT EXPLAIN FALSE
FETCH FIELDS FLOAT
FOR FORCE FOREIGN
FOUND FRAC_SECOND FROM
FULLTEXT GRANT GROUP
HAVING HIGH_PRIORITY HOUR_MICROSECOND
HOUR_MINUTE HOUR_SECOND IF
IGNORE IN INDEX
INFILE INNER INNODB
INOUT INSENSITIVE INSERT
INT INTEGER INTERVAL
INTO IO_THREAD IS
ITERATE JOIN KEY
KEYS KILL LEADING
LEAVE LEFT LIKE
LIMIT LINES LOAD
LOCALTIME LOCALTIMESTAMP LOCK
LONG LONGBLOB LONGTEXT
LOOP LOW_PRIORITY MASTER_SERVER_ID
MATCH MEDIUMBLOB MEDIUMINT
MEDIUMTEXT MIDDLEINT MINUTE_MICROSECOND
MINUTE_SECOND MOD NATURAL
NOT NO_WRITE_TO_BINLOG NULL
NUMERIC ON OPTIMIZE
OPTION OPTIONALLY OR
ORDER OUT OUTER
OUTFILE PRECISION PRIMARY
PRIVILEGES PROCEDURE PURGE
READ REAL REFERENCES
REGEXP RENAME REPEAT
REPLACE REQUIRE RESTRICT
RETURN REVOKE RIGHT
RLIKE SECOND_MICROSECOND SELECT
SENSITIVE SEPARATOR SET
SHOW SMALLINT SOME
SONAME SPATIAL SPECIFIC
SQL SQLEXCEPTION SQLSTATE
SQLWARNING SQL_BIG_RESULT SQL_CALC_FOUND_ROWS
SQL_SMALL_RESULT SQL_TSI_DAY SQL_TSI_FRAC_SECOND
SQL_TSI_HOUR SQL_TSI_MINUTE SQL_TSI_MONTH
SQL_TSI_QUARTER SQL_TSI_SECOND SQL_TSI_WEEK
SQL_TSI_YEAR SSL STARTING
STRAIGHT_JOIN STRIPED TABLE
TABLES TERMINATED THEN
TIMESTAMPADD TIMESTAMPDIFF TINYBLOB
TINYINT TINYTEXT TO
TRAILING TRUE UNDO
UNION UNIQUE UNLOCK
UNSIGNED UPDATE USAGE
USE USER_RESOURCES USING
UTC_DATE UTC_TIME UTC_TIMESTAMP
VALUES VARBINARY VARCHAR
VARCHARACTER VARYING WHEN
WHERE WHILE WITH
WRITE XOR YEAR_MONTH
ZEROFILL

The following symbols (from the table above) are disallowed by ANSI SQL but allowed by MySQL as column/table names. This is because some of these names are very natural names and a lot of people have already used them.

フィールド型

MySQLは多くのフィールド型をサポートしており、それらは3つのカテゴリに グループ化されます: 数値型、日付及び時間型、そして文字列(文字)型。 この章ではまず、利用できる型の概要から始まり、それから各カテゴリの各フィールド 型の所要記憶容量の要約と、型の属性についてのより詳細な情報を提供します。 概要は意図的に簡潔にまとめています。値として指定できる書式のようなフィールド 型固有の付加情報は、詳細の説明部にて調べて下さい。

MySQLでサポートされるフィールド型は以下に示す通りです。 後に続く文字の意味は説明のために使われます:

M
最大表示サイズを意味します。最大の表示桁数は 255.
D
浮動小数点数型に適用され、小数点以下の桁数を表します。 最大の値は 30 ですが、これは M-2 より大きくなってはいけません。

中カッコ(`['及び`]')は型定義の一部であり、それがオプションであることを 表します。

もしあるフィールドに ZEROFILL を指定した場合、 MySQL は自動で UNSIGNED 属性をそのフィールドに 追加します。

Warning: you should be aware that when you use subtraction between integer values where one is of type UNSIGNED, the result will be unsigned! See section Cast Functions.

TINYINT[(M)] [UNSIGNED] [ZEROFILL]
とても小さい整数。符号つきの範囲は -128127。符号なしの範囲は 0255
BIT
BOOL
These are synonyms for TINYINT(1).
SMALLINT[(M)] [UNSIGNED] [ZEROFILL]
小さい整数。符号つきの範囲は -3276832767。 符号なしの範囲は 065535
MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL]
中間の整数。符号ありの範囲は -83886088388607。 符号なしの範囲は 016777215
INT[(M)] [UNSIGNED] [ZEROFILL]
通常の整数。符号ありの範囲は -21474836482147483647。符号なしの範 囲は 04294967295
INTEGER[(M)] [UNSIGNED] [ZEROFILL]
これは、INTの同義語です。
BIGINT[(M)] [UNSIGNED] [ZEROFILL]
大きい整数。 符号ありの範囲は -92233720368547758089223372036854775807。 符号なしの範囲は 018446744073709551615BIGINT フィールドについて意識すべきことのいくつか:
FLOAT(precision) [UNSIGNED] [ZEROFILL]
浮動小数点数。Version 4.0 未満では符号なしにはできません。単精度浮動小数点数では precision<=24 で、倍精度浮動小数点数では 25〜53 の間です。 これらの型は次で述べるFLOATDOUBLE型に似ています。 FLOAT(X)は、FLOAT及びDOUBLE型に一致する同じ範囲を持っていま すが、 表示サイズや小数点以下桁数が定義されません。 MySQL バージョン 3.23 では、これは正しい浮動小数点です。前の MySQL バージョンでは, FLOAT(precision) は常に小数部は2桁で した。 注意: FLOAT の使用は、MySQL での全ての演算が double 精度で行 なわれるため、いくつかの予期しない問題が起こり得ます。 See section Solving Problems with No Matching Rows. この構文は ODBC 互換です。
FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
小さい浮動小数点数。Version 4.0 未満では符号なしにはできません。 範囲は -3.402823466E+38-1.175494351E-3801.175494351E-383.402823466E+38です。 Version 4.0 以上では、If UNSIGNED is specified, negative values are disallowed. M は表示幅で D は小数部桁数です。引数が無いか引数が24以下の FLOAT は単精度浮動小数点数を意味します。
DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
通常の浮動小数点数。Version 4.0 未満では符号なしにはできません。 範囲は -1.7976931348623157E+308-2.2250738585072014E-30802.2250738585072014E-3081.7976931348623157E+308です。 Version 4.0 以上では、If UNSIGNED is specified, negative values are disallowed. M は表示幅で D は小数部桁数です。引数が無いか DOUBLE か、 25 <= X <= 53 である FLOAT(X) は倍精度浮動小数点数を意味します。
DOUBLE PRECISION[(M,D)] [UNSIGNED] [ZEROFILL]
REAL[(M,D)] [UNSIGNED] [ZEROFILL]
これらはDOUBLEの同義語です。
DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]
パック無し浮動小数点数。Version 4.0 未満では符号なしにはできません。CHARフィールドのように振 舞います。`パック無し'は、数値が文字列として格納されることを意味し、数値のそれぞ れの桁、小数点、及び負数での`-'符号に1文字使用します。 Dが0の時、値は小数点や小数部を持ちません。DECIMAL値の最大範囲は DOUBLEと同じですが、実際の範囲はDECIMALフィールドに与えられたM 及びDの選択に強制されます。 Version 4.0 以上では、If UNSIGNED is specified, negative values are disallowed. D を省略した場合は 0 に設定されます。M を省略した場合は 10 に設定されます。 MySQL 3.22 以下では、 M 引数は符号や小数点を含みます。
DEC[(M[,D])] [UNSIGNED] [ZEROFILL]
NUMERIC[(M[,D])] [UNSIGNED] [ZEROFILL]
DECIMALと同じ。
DATE
日付。サポートされる範囲は'1000-01-01'から'9999-12-31'まで。 MySQL は'YYYY-MM-DD'の書式でDATE値を表示しますが、DATE フィールドへの値の割当ては、文字列もしくは数値のいずれかの使用が許されます。 See section DATETIME, DATE, TIMESTAMP.
DATETIME
日付と時刻の組み合わせ。サポートされる範囲は'1000-01-01 00:00:00''9999-12-31 23:59:59'です。MySQLはDATETIME値を 'YYYY-MM-DD HH:MM:SS'という書式で表示しますが、DATETIMEフィールド への値の割当ては、文字列もしくは数値のいずれかの使用が許されます。 See section DATETIME, DATE, TIMESTAMP.
TIMESTAMP[(M)]
タイムスタンプ。範囲は'1970-01-01 00:00:00'2037年末までです。 MySQL はTIMESTAMP値をYYYYMMDDHHMMSSYYMMDDHHMMSSYYYYMMDD又はYYMMDDという書式で表示し、それはM14(もし くは誤ってそれ以上の値を指定した時)、128又は6のいずれが指 定されたかに依存します。しかしながらTIMESTAMPフィールドへの値の割当ては、 文字列もしくは数値のいずれかの使用が許されます。 TIMESTAMPフィールドは、最後に操作された時刻を自動的に設定するので、 INSERTUPDATE操作の時刻を記録するのに役立ちます。 NULL値を与えることによっても、現在時刻を設定できます。 See section 日付と時間の型. TIMESTAMP は常に 4 バイトで格納されます。M 引数は TIMESTAMP フィールドがどのように表示されるかだけに影響します。 注意: X が 8 または 14 である TIMESTAMP(X) フィールドは数値として報 告されます。他の TIMESTAMP(X) フィールドは文字列として報告されます。 これは、これらの型を持ったテーブルを確実にダンプとリストアできるようにする ためです! See section DATETIME, DATE, TIMESTAMP.
TIME
時間。範囲は'-838:59:59''838:59:59'です。 MySQL はTIME値を'HH:MM:SS'という書式で表示しますが、TIME フィールドへの値の割当ては、文字列もしくは数値のいずれかの使用が許されます。 See section TIME.
YEAR[(2|4)]
年。2桁または4桁形式(デフォルトは4桁)。許される値は、4桁形式では 19012155, 0000 で、2桁形式(70〜69)では 1970〜2069 です。MySQL は YEAR 値を YYYY 形式で表示しますが、 YEAR フィールドへの値の割り当ては文字列と数字のどちらでも使用できま す。(YEAR は MySQL バージョン 3.22 以上での新しい型です。) See section YEAR.
[NATIONAL] CHAR(M) [BINARY]
固定長文字列で、格納時には必ず指定された長さまで右側に空白を埋めます。 Mの範囲は 0 から 255 文字です。 (MySQL Version 3.23 までは 1 から 255 です。) 後続の空白は値の取り出し時に削除され ます。BINARY キーワードが与えられない場合、CHAR 値のソートと 比較は、デフォルト文字セットに従ってケース非依存の方法で行なわれます。 NATIONAL CHAR (短い形式は NCHAR) は、ANSI SQL で、CHAR フィー ルドがデフォルト文字セットを使用することを定義する方法です。これは MySQL ではデフォルトです。 CHARCHARACTER の略記です。 MySQL は CHAR(0) 型のフィールドの生成を許します。これは主 に、実際にはもう値が使われていないフィールドが存在することに依存しているよ うないくつかの古いアプリケーションに対応する必要がある時に便利です。2つの 値だけを取ることができるフィールドを必要とする時にもとても良いことです: NOT NULL として定義されていない CHAR(0) は1ビットだけを占有 し、2つの値だけを取ることができます: NULL または ""。 See section CHAR 型と VARCHAR.
CHAR
This is a synonym for CHAR(1).
[NATIONAL] VARCHAR(M) [BINARY]
可変長文字列。 注意: 後続の空白は格納時に削除されます(これは ANSI SQL 仕様と異なります)。 Mの範囲は 0 から 255 文字です。 (MySQL Version 4.0.2 未満では 1 から 255 です) BINARY キーワードが与えられない場合、ソートと比較はケースに依存しません。 See section 暗黙のフィールド定義変更. VARCHARCHARACTER VARYING の略記です。 See section CHAR 型と VARCHAR.
TINYBLOB
TINYTEXT
最大長 255 (2^8 - 1) 文字の TEXT/BLOB。 See section 暗黙のフィールド定義変更. See section BLOBTEXT.
BLOB
TEXT
最大長 65535 (2^16 - 1) 文字の TEXT/BLOB。 See section 暗黙のフィールド定義変更. See section BLOBTEXT.
MEDIUMBLOB
MEDIUMTEXT
最大長 16777215 (2^24 - 1) 文字の TEXT/BLOB。 See section 暗黙のフィールド定義変更. See section BLOBTEXT.
LONGBLOB
LONGTEXT
最大長 4294967295 (2^32 - 1) 文字の TEXT/BLOB。 See section 暗黙のフィールド定義変更。注意: サーバ/クライアントプロトコルと MyISAM テーブルは、通信パケット単位 / テーブルレコードで、現在 16M の制限 があるため、この型の範囲全体はまだ使用できません。See section BLOBTEXT
ENUM('value1','value2',...)
列挙。 対象となる文字列は、値を一つだけ持ち、値リスト'value1', 'value2',...(又は NULL)から選ばれます。ENUMは最大65535個の固有値を持つことができます 。 See section ENUM.
SET('value1','value2',...)
組。 対象となる文字列は0以上の値を持ち、それぞれ値リスト'value1', 'value2',... から選ばれなければなりません。 SETは、最大 64個の要素を持つことができます。See section SET.

数値型

MySQL は ANSI/ISO SQL92 数値型をすべてサポートします。これらの型 は正確な数値データ型(NUMERIC, DECIMAL, INTEGER, SMALLINT)、近似数値型(FLOAT, REAL, DOUBLE PRECISION)を含みます。キーワード INTINTEGER の同義語で、 DECDECIMAL の同義語です。

MySQL では NUMERICDECIMAL 型は、SQL92 標準で許 されているように同じ型として実装されています。これらは正確な精度を維持する ことが重要な値(例えば金銭データ)に使用されます。これらの型の一つのフィール ドを宣言する時、精度と大きさが指定できます(通常はそうします); 例えば:

    salary DECIMAL(5,2)

この例では、5 (precisoin) は値を格納する重要な数値の桁数を表 します。そして 2 (scale) は小数点に続いて格納される桁数を表 します。従って、この場合 salary フィールドに格納することができる値 の範囲は、-99.99 から 99.99 です。 (MySQL can actually store numbers up to 999.99 in this column because it doesn't have to store the sign for positive numbers)

ANSI/ISO SQL92 では、構文 DECIMAL(p)DECIMAL(p,0) と等しいです。同様に、 構文 DECIMALDECIMAL(p,0) と等しいです。ここで p の値の決定は実装に許されてます。DECIMAL/NUMERIC データ型のこ れらの異なる形式は、MySQL は現在サポートしていません。この型の主 な利益は精度と大きさの両方を明示的に制御する機能から引き出されるので、これ は通常深刻な問題ではありません。

DECIMALNUMERIC 値は、値の小数の精度を維持するため、バイ ナリ浮動小数点数としてではなく、文字列として格納されます。1文字は値のそれ ぞれの桁(scale > 0 の場合)と `-' 記号(負数の場合)に使用されま す。scale が 0 の場合、DECIMALNUMERIC 値は小数点 と小数部を含みません。

DECIMALNUMERIC 値の最大範囲は DOUBLE と同じです。 しかし DECIMALNUMERIC フィールドに与えられる実際の範囲は フィールドに与えられた precisionscale によって強制されま す。このフィールドに、指定された scale で許されるよりも多い桁の小数 部を持つ数値が割り当てられた場合、値はその scale に丸められます。 DECIMALNUMERIC フィールドに、指定された(またはデフォルト の) precisionscale で示された範囲を超えた大きさの値を割 り当てた時、MySQL はその範囲の対応する最大値を表す値を格納します。

ANSI/ISO SQL92 標準に対する拡張として、上の表にリストしたように、 MySQL は整数型 TINYINT, MEDIUMINT, BIGINT も サポートします。MySQL によってサポートされる他の拡張として、オプ ションで、型の基本キーワードに続けて括弧内に指定する整数値の表示幅(例えば INT(4))があります。このオプションの幅指定は、フィールドに指定された 幅よりも少ない幅の値の表示の左側を埋めるために使用されます。しかしフィール ドに格納することができる値の範囲や、フィールドに指定された幅を超える幅の値 について表示される桁数は制約されません。オプションの拡張属性 ZEROFILL を指定して使用された場合、デフォルトの埋められる空白は 0 で置き換えられます。例えば、INT(5) ZEROFILL として宣言されたフィー ルドでは、値 40004 として取り出されます。注意: 整数フィー ルド内に表示幅よりも大きい値を格納する場合、MySQL が複雑な join のために一時テーブルを生成する時に、問題を体験するでしょう。この場合 MySQL はデータがオリジナルのフィールド幅に合っていることを信用す るためです。

すべての整数型はオプションの(非標準)属性 UNSIGNED を持つことができ ます。符合無しの値はフィールド内に正の数だけを許可したくて、フィールドに対 して少し大きい数値の範囲が必要な時に使用できます。

As of MySQL 4.0.2, floating-point types also can be UNSIGNED. As with integer types, this attribute prevents negative values from being stored in the column. Unlike the integer types, the upper range of column values remains the same.

FLOAT 型は近似数データ型を表すために使用されます。ANSI/ISO SQL92 標 準は、FLOAT キーワードに続く括弧中にオプションの精度(指数の範囲では ない)の指定を許しています。MySQL 実装はこのオプションの精度指定も サポートしています。キーワード FLOAT が精度の指定無しでフィールド型 として使用された時は、MySQL は値を格納するために4バイトを使用しま す。FLOAT キーワードに続く括弧中に2つの数値を与える構文もサポートさ れます。このオプションでの、最初の数値は値に必要な容量をバイトで表します。 2番目の数値は、格納、表示される小数部の桁数を指定します(DECIMALNUMERIC と同様)。MySQL がフィールドに指定されたよりも大き い小数部の桁数を持つ数値をこのフィールドに格納する時、値の格納時に余計な桁 を取り除くように値が丸められます。

REALDOUBLE PRECISION 型は精度指定を許しません。 ANSI/ISO SQL92 標準に対する拡張として、MySQL は DOUBLEDOUBLE PRECISION 型の同義語として認識します。REAL の精度は DOUBLE PRECISION の指定よりも小さいことを要求する標準と異なり、 MySQL はどちらも8バイトの倍精度小数点の値として実装しています (非"ANSI モード"で実行した場合)。移植性を最大にするためには、近似数値 データ値の格納を要求するコードは、精度や小数部桁数の指定無しの FLOATDOUBLE PRECISION を使用すべきです。

フィールドの型の値の許容範囲を超えた数値を代入しようとすると、MySQL は その値を許容範囲いっぱいに切り詰め、その結果を代わりに代入します。

例えば、 INT フィールドの範囲は -2147483648 から 2147483647 です。 もし -9999999999INT フィールドに挿入しようとすると、値は範囲の 最低値に修正され、 -2147483648 が代わりに代入されます。同様に、 9999999999 の場合、 2147483647 が代わりに代入されます。

そして、INT フィールドが符号無しの場合、フィールドの範囲の大きさは 同じですが、限界値は 04294967296 になります。 もし -99999999999999999999 を代入しようとすると、 値は 04294967296 として代入されます。

ALTER TABLE, LOAD DATA INFILE, UPDATE または multi-row INSERT 時、これらの変換は `警告' として得られます。

Type Bytes From To
TINYINT 1 -128 127
SMALLINT 2 -32768 32767
MEDIUMINT 3 -8388608 8388607
INT 4 -2147483648 2147483647
BIGINT 8 -9223372036854775808 9223372036854775807

日付と時間の型

日付と時間の型は DATETIME, DATE, TIMESTAMP, TIME, YEAR です. これらはそれぞれ値に適正な範囲があり、 ``zero'' はあなたが間違った値を指定した場合に用いられます。注意: MySQL は 確実に '厳密でない' 正しい日付の値、例えば 1999-11-31 を格納するこ とができます。この理由は、日付をチェックする処理の責任はアプリケーションに あり、SQL サーバにはないと考えているからです。日付を'速く'チェックするため に、MySQL は月が 0〜12 の範囲であるかと日が 0〜31 の範囲であるか だけをチェックします。上述の範囲は、MySQL が DATE または DATETIME フィールドに、日または月日が 0 である日付を格納できるため に定義されています。これは、正確な日付を知らない誕生日を登録する必要がある アプリケーションに非常に有用です。この場合、1999-00-001999-01-00 のような日付を単純に登録できます(もちろん、このような日 付を DATE_SUB()DATE_ADD のような関数で使用して、正しい値 が返ることは期待できません)。

これは、日付と時間型で作業する場合に、一般的に考慮しなければならないことです:

西暦2000年問題とデータ型

MySQL 自体は2000年問題に対して安全です(see section 2000 年対応)が、 MySQL に提示される入力値に関してはそうではありません。2桁の 年の入力は何世紀なのかわからないので全て曖昧です。このような値は MySQL が内部で年に4桁を使っていることから4桁の形式に変換されてしまいます。

MySQL は曖昧な日付を DATETIME, DATE, TIMESTAMP および YEAR 型に関して、以下の ルールに従って解釈します。

これらのルールはデータが何を意味しているかに対して妥当な推定を与えるに 過ぎないことに注意してください。この MySQL 発見的手法が正しい値を生成し ない場合は曖昧でない4桁の年を含む入力を与えるべきです。

ORDER BY は2桁の YEAR/DATE/DATETIME 型を正しくソートされます。

注意: MIN()MAX() のようないくつかの関数は TIMESTAMP/DATE を数値に変換します。これは年が2桁のタイムスタンプはこれらの関数で正しく動作しな いことを意味します。この場合の修復は、TIMESTAMP/DATE を4桁の年の形 式に変換するか、MIN(DATE_ADD(timestamp,INTERVAL 0 DAYS)) のような何 かを使用することです。

DATETIME, DATE, TIMESTAMP

DATETIME, DATE, TIMESTAMP型はお互いに関連しています。このセ クションではそれらの特徴と、それぞれがどう同じでどう違うかを示します。

DATETIME 型は日付と時刻の情報を含む値が必要な場合に使います。MySQL は DATETIME 値を 'YYYY-MM-DD HH:MM:SS' のフォーマットで取り出し、 表示します。 サポートされる範囲は '1000-01-01 00:00:00' から '9999-12-31 23:59:59' です。 (「サポートされる」とはさらに過去の値でも動くかも知れませんが保証の限りではない という意味です)

DATE 型は時刻の部分なしで日付の値のみが必要な場合に使います。MySQL は DATE 値を'YYYY-MM-DD' のフォーマットで取り出し、表示します。サポ ートされる範囲は '1000-01-01' から '9999-12-31' です。

TIMESTAMP タイプは INSERTUPDATE 操作に自動的に 現在の日付と時刻をマークする場合に提供される型です。 もし複数の TIMESTAMP フィールドがある場合には最初 の一つだけが自動的に更新されます。

最初の TIMESTAMP フィールドの自動更新は以下のいずれかの条件で起こります:

最初以外の TIMESTAMP フィールドも現在の日付と時刻にすることができます。そ れらのフィールドをNULL または NOW() にすることです。

どの TIMESTAMP フィールドも明示的に望む値をセットすることで現在の日時でな い値にすることができます。それは最初の TIMESTAMP フィールドについても同じ です。この特性は例えば TIMESTAMP フィールドをあるレコードが生成された時の 日時にし、その後その行が更新されても変化しないようにしたいというようなときに使え ます。

一方、この手法は DATATIME フィールドを行生成時に NOW() で初期化し 、以降の更新時に それをほうっておくのと同じように簡単であるとわかるでしょう。

TIMESTAMP の値は 1970 年の最初から 2037 年のどこかの時点ま での範囲で有効で、 1秒の時間分解能を持ちます。値は数値として表示されます。

MySQL が TIMESTAMP 値を取り出したり表示するのに使うフォーマット は以下の表 に示すようにその表示サイズに依存します。「目一杯の」 TIMESTAMP フォーマッ トは14桁ですが、 TIMESTAMP フィールドはより短い表示サイズで生成することも できます:

フィールド型 表示フォーマット
TIMESTAMP(14) YYYYMMDDHHMMSS
TIMESTAMP(12) YYMMDDHHMMSS
TIMESTAMP(10) YYMMDDHHMM
TIMESTAMP(8) YYYYMMDD
TIMESTAMP(6) YYMMDD
TIMESTAMP(4) YYMM
TIMESTAMP(2) YY

全ての TIMESTAMP フィールドは表示サイズに関係なく同じ格納サイズを持ちます。 もっとも一般的な表示サイズは 6 , 8 , 12 および 14 です。表示サイズはテーブル生成 時に任意の値に指定できますが、 0 および 14 以上の値は強制的に 14 になります。1 から 13 までの奇数のサイズは強制的に一つ大きい偶数になります。

DATETIME, DATE, TIMESTAMP 値は以下の共通フォーマットセット のいずれかを使って指定できます:

無効な DATETIME , DATE , TIMESTAMP の値は適切な「ゼロ」値に 変換されます('0000-00-00 00:00:00' , '0000-00-00' または 00000000000000 )。

日時の部分に区切りを持つ文字列で指定される値で、月、日の値が10未満の場 合は2桁で指定しなくてもかまいません。 '1979-6-9''1979-06-09' と等価です。同様に時刻の部分に区切りを持つ文字列で指定される値で、時、分、秒が 10 未満の場合は2桁で指定しなくてもかまいません。 '1979-10-30 1:2:3''1979-10-30 01:02:03' と等価です。

数値でしていされる値は 6, 8, 12 または 14 桁である必要があります。もしその数 値が 8 または 14 桁の長さの時はそれぞれ YYYYMMDD および YYYYMMDDHHMMSS フォーマットで、最初の 4 桁で年が与えられるものと仮定 されます。もしその数値が 6または12桁の長さの時は YYMMDD および YYMMDDHHMMSS フォーマットで最初の2桁で年が与えられるものと仮定されます。 これら以外の長さの数値はあとに 0 が追加されてこれらのうちのもっとも近い 長さのものと解釈されます。

区切りなしの文字列で与えられる値はそれ自身の長さを使って解釈されます。 もし文字列が8または14文字ならば年は最初の4文字で与えられると仮定されま す。そうでなければ最初の2文字で与えられると仮定されます。文字列は左か ら右に年、月、日、時、分、秒と文字列中に表現されている分だけ順に解釈さ れます。つまり6文字以下の文字列は使ってはいけないということです。例え ば1999年3月を指定するつもりで '9903' を指定した場合、MySQL は「ゼロ」日付 をテーブルに挿入します。これは年と月の部分は 9903 ですが日の部 分が欠けている(ゼロ)ために値が有効な日付でないために起こります。

TIMESTAMP フィールドは有効な値を、表示サイズに関係なく指定された値を最高 精度の時間分解能で格納します。このことはいくつかの意味合いを持ちます。

年の値が二桁で指定された場合、世紀の部分がないので曖昧な値となります。 MySQL は二桁の年の値を以下に示す規則にそって変換します:

ある日付型を他の日付型のオブジェクトに拡張して指定することができます。 しかしそれは値の変化や情報の欠落を起こす可能性があります。

日付の値を指定するときの落とし穴に注意してください

TIME

MySQL は TIME の値を 'HH:MM:SS' (時の部分が大きい場合は 'HHH:MM:SS') というフォーマットで扱い、また表示します。 (時の部分が大きい場合は 'HHH:MM:SS')。 TIME 値の範囲は '-838:59:59' から '838:59:59' の範囲です。 時の部分がこんなに大きいのは、TIME 型は一日すなわち24時間以内 の時刻を表現するのに用いられるだけではなく経過時間や二つの事象の間隔 (どちらも24時間を越えたり、負の数になる場合もあります)を表現すること もあるからです。

TIME 値は様々なフォーマットで指定可能です:

文字列で時刻の各部の区切りを含む TIME の値については、時、分、秒が 10 以下の場合、2桁の数字を指定する必要はありません。'8:3:2''08:03:02' と同じです。

「短い」 TIME 値を TIME フィールドとして指定する場合は要注意です。 コロンなしでは、MySQL はその値のもっとも右端の桁は秒を表すと仮定して解 釈します。 (MySQL は TIME の値を一日のうちの時刻としてより経過時間として 解釈します)。例えば '11:12','1112', 1112'11:12:00' (11時12分)を表しているつもりでいても、 MySQL はこれらを '00:11:12' (11分12秒)として解釈します。 同様に '12' および 12'00:00:12' と解釈します。

TIME の範囲外にある値で値以外は正しいものは範囲の端の値の適当な方にクリッ プされます。例えば '-850:00:00' および '850:00:00' は それぞれ '-838:59:59' および '838:59:59' になります。

無効な TIME 値は '00:00:00' に変換されます。 ここで '00:00:00' 自体は有効な TIME 値なので、 テーブル内に保存された'00:00:00'という値からそれがもとも と '00:00:00' と指定された値なのか無効なために変換された結果なのかを区 別する方法はないことに注意してください。

YEAR

YEAR 型は年を表現するのに使われる1バイトの値です。

MySQL は YEAR の値を YYYY というフォーマットで扱い、 また表示します。範囲は 1901 から 2155 です。

YEAR 型は様々なフォーマットで指定可能です:

無効な YEAR 値は 0000 に変換されます。

文字列型

文字列型はCHAR, VARCHAR, BLOB, TEXT, ENUM, SET です。このセクションは、それらの型がどのように動作 するかと、要求されるサイズと、クエリ内での使用方法を説明します。

Type Max.size Bytes
TINYTEXT or TINYBLOB 2^8-1 255
TEXT or BLOB 2^16-1 (64K-1) 65535
MEDIUMTEXT or MEDIUMBLOB 2^24-1 (16M-1) 16777215
LONGBLOB 2^32-1 (4G-1) 4294967295

CHAR 型と VARCHAR

CHAR 型と VARCHAR 型はよく似ていますが格納、取り出しの手順に違いが あります。

CHAR フィールドの長さはテーブルを生成するときに宣言した長さに固定されます。 長さは 1 から 255 までの値を取ります。CHAR が格納されるときには指定された 長さになるように右側に空白が詰められます。CHAR の値が取り出された場合には 右側(後続)の空白は取り除かれます。

VARCHAR フィールドの値は可変長文字列です。 VARCHAR フィールドは CHAR フィールド と同じく 1 から 255 までの長さに宣言できます。 (MySQL バージョン 3.23 では, CHAR の長さは 0 から 255 まで許され ています.) しかし CHAR 型と異なり VARCHAR 型の値は必要な文字数の分に 長さを記録する1 バイトを足した領域に格納されます。値には桁合わせのための空白はつ けられません。後続の空白は値の格納時に取り除かれます。(この空白の除去は ANSI SQL仕様とは違っています。)

もし CHAR または VARCHAR フィールドに、フィールドの最大長を 越える長さの値を与えた場合は、適合するように切り詰められます。

以下の表はこれらの二つのフィールド型の違いを、CHAR(4) および VARCHA R(4) に様々な文字列値を格納した結果を示すことで表しています。

CHAR(4) 必要な格納域 @code {VARCHAR(4)} 必要な格納域
'' ' ' 4 バイト '' 1 バイト
'ab' 'ab ' 4 バイト 'ab' 3 バイト
'abcd' 'abcd' 4 バイト 'abcd' 5 バイト
'abcdefgh' 'abcd' 4 バイト 'abcd' 5 バイト

CHAR(4) フィールドの後続の空白は取り出し時にとりのぞかれるので、CHAR(4)お よび VARCHAR(4) から取り出される値はどの場合でも同じです。

CHAR および VARCHAR フィールドの値はテーブルの生成時に BINARY 属性が つけられない限り、大文字と小文字を区別しないでソート・比較されます。BINARY 属性は その列の値が大文字、小文字を区別して、MySQLサーバを実行しているマシンのASCII順に ソート・比較されることを意味します。 BINARY はフィールドがどのように格納されるか、どのように取り出される かには影響しません。

BINARY 属性は「固定的」です。つまり、もし BINARY であると指定された フィールドが式の中にあると式全体が BINARY の値として比較されるのです。

MySQL はテーブル生成時に何も断らずにCHAR または VARCHAR 型のフィールドを変更する事があります。 See section 暗黙のフィールド定義変更.

BLOBTEXT

BLOB は大きなバイナリ型のオブジェクトで、可変長のデータを保持できます。 4 つの BLOB 型、すなわち TINYBLOB, BLOB, MEDIUMBLOBLONGBLOB は保持できるデータの最大長が違うだけです。 See section 各フィールド型の所要容量.

4 つの TEXT 型、すなわち TINYTEXT, TEXT, MEDIUMTEXTLONGTEXT は 4 つの BLOB 型に対応し、同じ最大長と 格納条件を持っています。 TEXTBLOB の違いは、 TEXT はケースに依存しないでソートと比較され、 BLOB はケースに依存して(文字コードで)比較されることだけです。 いうならば、TEXT は、ケースに依存しない BLOB です。

もし BLOBTEXT フィールドにそれらの最大長以上の値が与えられた 場合、その値はきっちり収まるように切り落とされます。

ほとんどの点で、TEXT フィールドを VARCHAR の大きい物と見なすことが 出来ます。 同様に、BLOB フィールドは VARCHAR BINARY フィールドの大きくなった 物です。 違いは、

MyODBCBLOBLONGVARBINARY として、 TEXTLONGVARCHAR として定義します。

BLOBTEXT フィールドは極端に長いので、それらを使用する際には、 いくつかの困った事にでくわすかもしれません:

それぞれの BLOB, TEXT フィールドは、一意のアロケートされたオブジェ クトによって、内部では表されることに注意してください.。 これはテーブルが開かれるときに一度だけアロケートされる他のフィールドとは対照的で す。

ENUM

ENUM はストリングオブジェクトで、 その値は、通常、テーブル作成時のフィールド定義で列挙された値の中から選ばれます。

値はある状況下では 空文字 ("") か NULL を取ることがあります:

列挙されたそれぞれの値はインデックスを持ちます:

たとえば、フィールドが ENUM("one", "two", "three") と定義されたなら、 以下に示す値をとります。 それぞれのインデックス値も示します。

インデックス
NULL NULL
"" 0
"one" 1
"two" 2
"three" 3

列挙は最大 65535 個の要素まで可能です。

Starting from 3.23.51 trailing spaces are automatically deleted from ENUM values when the table is created.

ENUM フィールドに値を与える場合は大文字小文字は無関係です。 しかし、後でフィールドから検索される値は、大文字小文字をもちます。 これはテーブル作成時に与えられたリストの値です。

もし ENUM を数値の文脈で検索した場合、そのメンバーを前から数えた 時の順番が数値で返ってきます。 たとえば、ENUM フィールドから次のようにして数値を取り出すことができ ます:

mysql> SELECT enum_col+0 FROM tbl_name;

もし ENUM に数値を代入しようとした場合、その数値の位置にある メンバーが代入されます。 (しかし、これは LOAD DATA では働きません。これはすべての入力を文字 列として扱います。) It's not advisable to store numbers in an ENUM string because it will make things confusing.

ENUM 値は列挙メンバがフィールド指定にリストされた順に従ってソートさ れます。(つまり、ENUM 値はインデックス値に従ってソートされます。) 例えば、ENUM("a", "b") ならば "a""b" の前にソートされ、 ENUM("b", "a") ならば "b""a" の前にソートされます。 空文字列は空ではない文字の前にソートされ、 NULL は他の列挙の前に並びます。 To prevent unexpected results, specify the ENUM list in alphabetical order. You can also use GROUP BY CONCAT(col) to make sure the column is sorted alphabetically rather than by index number.

ENUM フィールドで指定可能な値のリストを全て取りたいならば、 次のようにします: SHOW COLUMNS FROM table_name LIKE enum_column_name そして二番目のフィールドの ENUM 定義を分析します。

SET

SET は文字型オブジェクトでゼロかそれ以上を値持ちます。 テーブル作成時には、それぞれの値はリストから選ばれるべきです。 SET 型のフィールドの値は、コンマ(`,') 区切りで並べられた複数のメンバーで構成されています。 これは、 SET メンバーの値中にコンマを含むことが出来ない、 ということです。

例えば、 SET("one", "two") NOT NULL と指定されたフィールドは以下の値をとります:

""
"one"
"two"
"one,two"

SET は最大 64 個の異なったメンバーがもてます。

Starting from 3.23.51 trailing spaces are automatically deleted from SET values when the table is created.

MySQL は SET の値を数値として代入します。代入された 値の最下位のビットが最初のメンバーに対応します。もし SET 値を 数値の文脈で検索した場合、検索される値はフィールドの値に対応します。 たとえば、SET フィールドから次のようにして数値を取り出すことができ ます:

mysql> SELECT set_col+0 FROM tbl_name;

もし数値が SET フィールドに代入された場合、 二進数で表される数値のビットによって、メンバーが決定されます。 SET("a","b","c","d") とフィールドが定義されたとします。 メンバーは以下の2進数の値を持ちます:

SET member 10進数 2進数値
a 1 0001
b 2 0010
c 4 0100
d 8 1000

もしこのフィールドに 9 を与えた場合、これは2進数で 1001 ですから、 1 番目と 4 番目の SET メンバーである "a""d" が 選択され、結果、 "a,d" となります。

1つ以上の SET 要素を含む値においては,あなたが値を挿入するとき,要素がどん な 順序で記載されているのかは重要ではありません. また,何回要素が与えられたのかは 重要ではありません. 後で値が検索されるとき, 値の中のそれぞれの要素は ただ一回だけ表れます。そのとき、テーブル作成時に与えられた順に要素は並びます。 例えば、フィールドが SET("a","b","c","d") と設定されていたなら、 "a,d", "d,a", "d,a,a,d,d" は検索されると "a,d" と なります。

If you set a SET column to an unsupported value, the value will be ignored.

SET 値は数値として代入されます。 NULL 値は非 NULL SET 値の前にソートされます。

通常、LIKEFIND_IN_SET() を使用して SET フィールド の SELECT を行います:

mysql> SELECT * FROM tbl_name WHERE set_col LIKE '%value%';
mysql> SELECT * FROM tbl_name WHERE FIND_IN_SET('value',set_col)>0;

しかし、以下も動作します:

mysql> SELECT * FROM tbl_name WHERE set_col = 'val1,val2';
mysql> SELECT * FROM tbl_name WHERE set_col & 1;

最初の文は完全一致するものを探します。 二つ目は第一番目のメンバーを含む値を探します。

もし SET フィールドで設定可能なすべてのメンバーを知りたい場合: SHOW COLUMNS FROM table_name LIKE set_column_name とし、 2番目にあらわされる SET 定義を分析します。

正しいフィールド型の選択

もっとも効率よく格納するには、全てにおいて一番正確な型を使用することです。 例えば、1-99999 の整数 には、MEDIUMINT UNSIGNED が最良の型です。

良くある問題は、貨幣の値の正確な表現です。MySQL では DECIMAL 型を使用すべきです。これは文字列として格納し、正確さのロ スは発生しません。正確さが重要でない場合は DOUBLE 型でも十分良い です。

高精度のため、常に BITINT に格納される固定小数点型に変換できます。 これは、全ての計算を整数で行なうようにし、結果だけを浮動小数点に変換して 戻します。

他のデータベースエンジンのフィールド型の使用

ほかのベンダーからSQLを簡単に書けれるように、 MySQL は以下の表に しめすフィールド型をサポートします。これらは、テーブルの定義を、 他のデータベースエンジンから MySQL に簡単に移行させてくれます:

Other vendor type MySQL type
BINARY(NUM) CHAR(NUM) BINARY
CHAR VARYING(NUM) VARCHAR(NUM)
FLOAT4 FLOAT
FLOAT8 DOUBLE
INT1 TINYINT
INT2 SMALLINT
INT3 MEDIUMINT
INT4 INT
INT8 BIGINT
LONG VARBINARY MEDIUMBLOB
LONG VARCHAR MEDIUMTEXT
MIDDLEINT MEDIUMINT
VARBINARY(NUM) VARCHAR(NUM) BINARY

もし他のベンダーの型を使用してテーブルを作ろうとすると、 テーブル作成時のフィールドの型のマッピングが発生し、 DESCRIBE tbl_name 構文を発行します。 そして MySQL は、使用された型と等価な MySQL の型を用いて テーブルを構成したことを告げます。

各フィールド型の所要容量

MySQLがサポートする各フィールドタイプ毎の所要容量を、カテゴリ別に以下に 記述します。

数値タイプの保存容量

フィールドタイプ 所要容量
TINYINT 1 byte
SMALLINT 2 bytes
MEDIUMINT 3 bytes
INT 4 bytes
INTEGER 4 bytes
BIGINT 8 bytes
FLOAT(X) X <= 24 の場合 4、25 <= X <= 53 の場合 8
FLOAT 4 bytes
DOUBLE 8 bytes
DOUBLE PRECISION 8 bytes
REAL 8 bytes
DECIMAL(M,D) D > 0 の場合 M+2, D = 0 の場合 M+1 bytes (M < D の場合 D+2)
NUMERIC(M,D) D > 0 の場合 M+2, D = 0 の場合 M+1 bytes (M < D の場合 D+2)

日付と時間タイプの保存容量

フィールドタイプ 所要容量
DATE 3 bytes
DATETIME 8 bytes
TIMESTAMP 4 bytes
TIME 3 bytes
YEAR 1 byte

文字列タイプの保存容量

フィールドタイプ 所要容量
CHAR(M) M bytes, 1 <= M <= 255
VARCHAR(M) L+1 bytes, where L <= M and 1 <= M <= 255
TINYBLOB, TINYTEXT L+1 bytes,where L < 2^8
BLOB, TEXT L+2 bytes,where L < 2^16
MEDIUMBLOB, MEDIUMTEXT L+3 bytes,where L < 2^24
LONGBLOB, LONGTEXT L+4 bytes,where L < 2^32
ENUM('value1','value2',...) 1 or 2 bytes, 列挙値の数に依存 (最大値は 65535 )
SET('value1','value2',...) 1, 2, 3, 4 or 8 bytes, 要素の数に依存 (最大要素 64 )

VARCHARBLOB、及びTEXT型は可変長型であり、所要容量は、フィ ールドのとり得る最大サイズというよりはむしろフィールド値の実際の長さに依存します (前の表でLと表しました)。 例えば、VARCHAR(10)フィールドは、最大10文字分の長さの文字列を保持すること が出来ます。実際の所要容量は、文字列の長さ(L)と、その長さを記録するための 1バイトを加えます。文字列'abcd'においては、Lは4で、所要容量は5 バイトです。

BLOBTEXT型は、フィールド値の長さを記録するのに、1、2、3、又は 4バイト必要とし、型のとり得る最大の長さに依存します。See section BLOBTEXT.

テーブルが可変長フィールド型を含む場合、そのレコードフォーマットもまた可変長とな るでしょう。 テーブルが作成された時、MySQLは確かな条件の下、フィールドを可変長タイプ から固定長タイプへ変更し、副作用を起こすことに注意して下さい。 See section 暗黙のフィールド定義変更.

ENUMオブジェクトのサイズは、異なる列挙値の数によって決められます。 列挙する数が255以内では、1バイトが使用されます。 列挙する数が65535以内では、2バイトが使用されます。See section ENUM.

SETオブジェクトのサイズは、異なる要素の数によって決められます。 組のサイズをNとすると、オブジェクトは(N+7)/8バイトを占有し、 1、2、3、4又は8バイトに切上げられます。 1つのSETは、最大64要素を持つことができます。See section SET.

SELECTWHERE 節で使用する関数

SQL ステートメント中の select_expression または where_definition は後述の関数を使用した任意の式からなります。

演算と関数を式の中で呼ぶ時、本ドキュメントに示しているもの以外の、 NULL を含む式は常に NULL 値を生成します

注意: 関数名とそれに続く語句の間には、空白はありません。 これは関数の呼び出しと、関数と同名のテーブル(かフィールド)の参照を、 MySQL パーサが区別するのを助けます。

mysqld--ansi をつけて起動するか、 CLIENT_IGNORE_SPACEmysql_connect() に使用すれば、 MySQL が関数名の後の空白を許すようになりますが、その場合、すべて の関数名が予約語になります。See section Running MySQL in ANSI Mode

次の例では、mysql プログラムの出力は短くなっています。つまり:

mysql> SELECT MOD(29,9);
1 rows in set (0.00 sec)

+-----------+
| mod(29,9) |
+-----------+
|         2 |
+-----------+

これは次に変換されています:

mysql> SELECT MOD(29,9);
        -> 2

Non-Type-Specific Operators and Functions

The maximum size of a row in a MyISAM table is 65534 bytes. Each BLOB and TEXT column accounts for only 5-9 bytes towards this size.

Parentheses

( ... )

Use parentheses to force the order of evaluation in an expression. For example:

mysql> SELECT 1+2*3;
        -> 7
mysql> SELECT (1+2)*3;
        -> 9

比較演算子

1 (TRUE), 0 (FALSE) または NULL を返します。 これらの関数は数値と文字列の両方で働きます。 必要ならば、文字は自動的に数字に変換され、数字は文字に変換されます。 (Perlがおこなっているみたいに)

MySQL は以下の規則で比較を行います:

文字列の比較は、ケースに依存せず、標準のキャラクターセットに従って 行われます。(ISO-8859-1 Latin1 がデフォルトです。これは English です)

以下は、比較のために文字が数値へ変換されている例です:

mysql> SELECT 1 > '6x';
         -> 0
mysql> SELECT 7 > '6x';
         -> 1
mysql> SELECT 0 > 'x6';
         -> 0
mysql> SELECT 0 = 'x6';
         -> 1
=
等しい:
mysql> SELECT 1 = 0;
        -> 0
mysql> SELECT '0' = 0;
        -> 1
mysql> SELECT '0.0' = 0;
        -> 1
mysql> SELECT '0.01' = 0;
        -> 0
mysql> SELECT '.01' = 0.01;
        -> 1
<>
!=
等しくない:
mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1
<=
より小さいか等しい:
mysql> SELECT 0.1 <= 2;
        -> 1
<
より小さい:
mysql> SELECT 2 < 2;
        -> 0
>=
より大きいか等しい:
mysql> SELECT 2 >= 2;
        -> 1
>
より大きい:
mysql> SELECT 2 > 2;
        -> 0
<=>
等しい(NULL 安全):
mysql> SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL;
        -> 1 1 0
IS NULL
IS NOT NULL
値が NULL とであるかどうかのテスト:
mysql> SELECT 1 IS NULL, 0 IS NULL, NULL IS NULL;
        -> 0 0 1
mysql> SELECT 1 IS NOT NULL, 0 IS NOT NULL, NULL IS NOT NULL;
        -> 1 1 0
To be able to work good with other programs, MySQL supports the following extra features when using IS NULL:
expr BETWEEN min AND max
もし exprmin 以上、 max 以下なら 1を返します。 そうでないなら 0 を返します。 これは 全ての引数が同じ型ならば、(min <= expr AND expr <= max) と同じです。 Otherwise type conversion takes place, according to the rules above, but applied to all the three arguments. Note that before 4.0.5 arguments were converted to the type of expr instead.
mysql> SELECT 1 BETWEEN 2 AND 3;
        -> 0
mysql> SELECT 'b' BETWEEN 'a' AND 'c';
        -> 1
mysql> SELECT 2 BETWEEN 2 AND '3';
        -> 1
mysql> SELECT 2 BETWEEN 2 AND 'x-3';
        -> 0
expr NOT BETWEEN min AND max
Same as NOT (expr BETWEEN min AND max).
expr IN (value,...)
もし exprIN リストにある値のどれかならば、1 を返します 。 そうでなければ 0 を返します。 もし全ての値が定数なら、すべての値が expr の型に従って評価され、 ソートされます。この検索にはバイナリサーチが使用されます。 これは IN リストに定数を与えた場合、IN が速くなることを意味します。 もし expr がケース依存の文字式なら、ケース依存のやり方で比較されます。
mysql> SELECT 2 IN (0,3,5,'wefwf');
        -> 0
mysql> SELECT 'wefwf' IN (0,3,5,'wefwf');
        -> 1
From 4.1 (in line with the SQL-99 standard), IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.
expr NOT IN (value,...)
NOT (expr IN (value,...)) と同じ。
ISNULL(expr)
exprNULL なら 1 を、そうでなければ 0 を返します
mysql> SELECT ISNULL(1+1);
        -> 0
mysql> SELECT ISNULL(1/0);
        -> 1
NULL の値を = を使用して比較した場合は常に偽(false) となることに 注意してください!
COALESCE(list)
list 中の、最初に現れた 非-NULL 要素を返します。
mysql> SELECT COALESCE(NULL,1);
        -> 1
mysql> SELECT COALESCE(NULL,NULL,NULL);
        -> NULL
INTERVAL(N,N1,N2,N3,...)
もし N < N1 なら 0 を返します。 もし N < N2 なら 1 を返します。 全ての引数は整数として扱われます。 これは N1 < N2 < N3 < ... < Nnを正しく動作さ せるために 必要なことです。これはバイナリ検索が使用されます(速いです)
mysql> SELECT INTERVAL(23, 1, 15, 17, 30, 44, 200);
        -> 3
mysql> SELECT INTERVAL(10, 1, 10, 100, 1000);
        -> 2
mysql> SELECT INTERVAL(22, 23, 30, 44, 200);
        -> 0

If you are comparing case-insensitive strings with any of the standard operators (=, <>..., but not LIKE) trailing whitespace (spaces, tabs and newlines) will be ignored.

mysql> SELECT "a" ="A \n";
        -> 1

論理演算

全ての論理関数は 1 (TRUE) か 0 (FALSE) か NULL を返します。 (unknown は多くの場合 FALSE と同じです):

NOT
!
論理否定。引数が 0 なら 1 を返し、そうでなければ 0 を返しま す。 例外: NOT NULLNULL を返します:
mysql> SELECT NOT 1;
        -> 0
mysql> SELECT NOT NULL;
        -> NULL
mysql> SELECT ! (1+1);
        -> 0
mysql> SELECT ! 1+1;
        -> 1
最後の例は 1 を返します。なぜなら、式の評価が (!1)+1 と同じだからです。
AND
&&
論理積。 全ての引数が 非0 または 非NULL であれば 1 を返します。 引数のどれかが 0 ならば 0 を返します。 それ以外は NULL を返します。
mysql> SELECT 1 && 1;
        -> 1
mysql> SELECT 1 && 0;
        -> 0
mysql> SELECT 1 && NULL;
        -> NULL
mysql> SELECT 0 && NULL;
        -> 0
mysql> SELECT NULL && 0;
        -> 0
Please note that MySQL versions prior to 4.0.5 stop evaluation when a NULL is encountered, rather than continuing the process to check for possible 0s. This means that in these versions, SELECT (NULL AND 0) returns NULL instead of 0. In 4.0.5 the code has been re-engineered so that the result will always be as prescribed by ANSI while still using the optimisation wherever possible.
OR
||
論理和。 Evaluates to 1 if any operand is non-zero, to NULL if any operand is NULL, otherwise 0 is returned.
mysql> SELECT 1 || 1;
        -> 1
mysql> SELECT 1 || 0;
        -> 1
mysql> SELECT 0 || 0;
        -> 0
mysql> SELECT 0 || NULL;
        -> NULL
mysql> SELECT 1 || NULL;
        -> 1
XOR
Logical XOR. Returns NULL if either operand is NULL. For non-NULL operands, evaluates to 1 if an odd number of operands is non-zero, otherwise 0 is returned.
mysql> SELECT 1 XOR 1;
        -> 0
mysql> SELECT 1 XOR 0;
        -> 1
mysql> SELECT 1 XOR NULL;
        -> NULL
mysql> SELECT 1 XOR 1 XOR 1;
        -> 1
a XOR b is mathematically equal to (a AND (NOT b)) OR ((NOT a) and b). XOR was added in version 4.0.2.

フロー制御関数

IFNULL(expr1,expr2)
expr1NULL でない場合は expr1 を、そうでなければ expr2 を返します。 IFNULL() はどの文脈で使用されたかにより数値か文字を返します:
mysql> SELECT IFNULL(1,0);
        -> 1
mysql> SELECT IFNULL(NULL,10);
        -> 10
mysql> SELECT IFNULL(1/0,10);
        -> 10
mysql> SELECT IFNULL(1/0,'yes');
        -> 'yes'
In 4.0.6 and above the default result value of IFNULL(expr1,expr2) is the more 'general' of the two expressions, in the order STRING, REAL or INTEGER.The difference to earlier MySQL versions are mostly notable when you create a table based on expressions or MySQL has to internally store a value from IFNULL() in a temporary table.
CREATE TABLE foo SELECT IFNULL(1,"test") as test;
In MySQL 4.0.6 the type for column 'test' is CHAR(4) while in earlier versions you would get BIGINT.
NULLIF(expr1,expr2)
expr1 = expr2 が真なら、NULL を返し、そうでなければ expr1 を返します。 これは CASE WHEN x = y THEN NULL ELSE x END と同じです:
mysql> SELECT NULLIF(1,1);
        -> NULL
mysql> SELECT NULLIF(1,2);
        -> 1
注意: 引数が等しくない場合、expr1 は MySQL 内部では2回評価されます。
IF(expr1,expr2,expr3)
expr1 が真 (expr1 <> 0 and expr1 <> NULL) の場合 expr2 を返し、そうでなければ expr3 を返します。 IF() はどの文脈で使用されたかにより数値か文字を返します:
mysql> SELECT IF(1>2,2,3);
        -> 3
mysql> SELECT IF(1<2,'yes','no');
        -> 'yes'
mysql> SELECT IF(STRCMP('test','test1'),'no','yes');
        -> 'no'
If expr2 or expr3 is explicitely NULL then the result type of the IF() function is the type of the not NULL column. (This behaviour is new in MySQL 4.0.3). expr1INTEGER として評価されます。これは浮動小数点を使用する 場合、比較演算も使用すべきであることを意味します:
mysql> SELECT IF(0.1,1,0);
        -> 0
mysql> SELECT IF(0.1<>0,1,0);
        -> 1
上の最初の例では、 IF(0.1)0 を返します。なぜなら 0.1 は 整数値として変換され IF(0) になり、それをもとにしたテスト結果が 返るからです。 これはあなたの期待に添わないかもしれません。 二番目の場合、 比較は、元の浮動小数点値が非ゼロかどうかテストします。 比較結果は整数として使用されます。 IF() のデフォルトの戻り値型(一時テーブルに格納される時に問題となり ます)は MySQL バージョン 3.23 では次のように計算されます:
Expression Return value
expr2 または expr3 が文字列を返す 文字列
expr2 または expr3 が浮動小数点値を返す 浮動小数点
expr2 または expr3 が整数を返す 整数
If expr2 and expr3 are strings, then the result is case-insensitive if both strings are case-insensitive. (Starting from 3.23.51)
CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END
最初の式は value=compare-value ならば result を返します。 二つ目の式では、最初の条件[condition] が真ならば、 result を返します。 もしマッチする result の値がなければ、 ELSE 以下の result が返ります。 もし ELSE 部分がなければ、 NULL が返ります:
mysql> SELECT CASE 1 WHEN 1 THEN "one"
           WHEN 2 THEN "two" ELSE "more" END;
       -> "one"
mysql> SELECT CASE WHEN 1>0 THEN "true" ELSE "false" END;
       -> "true"
mysql> SELECT CASE BINARY "B" WHEN "a" THEN 1 WHEN "b" THEN 2 END;
       -> NULL

戻り値の型(INTEGER, DOUBLE, STRING)は最初に返される値 (最初の THEN の後の式)の型と同じです。

文字列関数

サーバー側のパラメター max_allowed_packet よりも結果の長さが大きい場合、 文字列関数は NULL を返します。 See section サーバーパラメーターのチューニング.

文字の位置を扱う関数においては、一番最初の位置は数字の 1 です。

ASCII(str)
str の左端の文字の ASCII コード値を返します。 str が空文字の場合は 0 を返します。 strNULL の場合は NULL を返します:
mysql> SELECT ASCII('2');
        -> 50
mysql> SELECT ASCII(2);
        -> 50
mysql> SELECT ASCII('dx');
        -> 100
See also the ORD() function.
ORD(str)
文字列 str の左端の文字がマルチバイト文字の場合、文字のASCII コード値を次 の形式で返すことにより、マルチバイト文字のコードを返します: ((first byte ASCII code)*256+(second byte ASCII code))[*256+third byte ASCII code...]. 左端の文字がマルチバイト文字でない場合は、ASCII() 関数と同じ値を返 します:
mysql> SELECT ORD('2');
        -> 50
CONV(N,from_base,to_base)
数字を、進数の違う数字に変換します。 数 Nfrom_base 進数から to_base 進数に 変換した場合の、文字表現を返します。 もし引数が NULL なら NULL を返します。 引数 N は整数として解釈されますが、整数か文字列で指定します。 最小の進数は 2 で、最大は 36 です。 to_base が負数なら、N は符号付きの数になります。 CONV は 64-bit 精度で動作します:
mysql> SELECT CONV("a",16,2);
        -> '1010'
mysql> SELECT CONV("6E",18,8);
        -> '172'
mysql> SELECT CONV(-17,10,-18);
        -> '-H'
mysql> SELECT CONV(10+"10"+'10'+0xa,10,10);
        -> '40'
BIN(N)
N を二進数にした値を返します。N は longlong 数値です。 これは CONV(N,10,2) と同じです。 NNULL なら NULL を返します:
mysql> SELECT BIN(12);
        -> '1100'
OCT(N)
N の8進数値を表す文字列を返します。N は longlong 数値です。 これは CONV(N,10,8) と同じです。NNULL の場合は NULL を返します:
mysql> SELECT OCT(12);
        -> '14'
HEX(N_or_S)
If N_OR_S is a number, returns a string representation of the hexadecimal value of N, ここで N は longlong(BIGINT) 数値です。これは CONV(N,10,16) と同じです。 If N_OR_S is a string, returns a hexadecimal string of N_OR_S where each character in N_OR_S is converted to 2 hexadecimal digits. This is the invers of the 0xff strings.
mysql> SELECT HEX(255);
        -> 'FF'
mysql> SELECT HEX("abc");
        -> 616263
mysql> SELECT 0x616263;
        -> "abc"
CHAR(N,...)
引数の ASCII コード値によって与えられた文字からなる文字列を返します。 NULL は飛ばされます:
mysql> SELECT CHAR(77,121,83,81,'76');
        -> 'MySQL'
mysql> SELECT CHAR(77,77.3,'77.3');
        -> 'MMM'
CONCAT(str1,str2,...)
引数を結合した結果を返します。引数が NULL なら NULL を返します. 2個以上の引数を必要とします。 数値の引数は等価の文字列形式に変換されます:
mysql> SELECT CONCAT('My', 'S', 'QL');
        -> 'MySQL'
mysql> SELECT CONCAT('My', NULL, 'QL');
        -> NULL
mysql> SELECT CONCAT(14.3);
        -> '14.3'
CONCAT_WS(separator, str1, str2,...)
CONCAT_WS() は区切り文字つき CONCAT (CONCAT With Separator) を意味 し、CONCAT() の特殊な形式です。最初の引数は、残りの引数の区切り文字 です。区切り文字は残りの引数と同じような文字列です。区切り文字が NULL の場合、結果は NULL になります。関数は区切り文字より後 の NULL と空文字列を飛ばします。区切り文字は結合される文字列の間に 追加されます:
mysql> SELECT CONCAT_WS(",","First name","Second name","Last Name");
       -> 'First name,Second name,Last Name'
mysql> SELECT CONCAT_WS(",","First name",NULL,"Last Name");
       -> 'First name,Last Name'
LENGTH(str)
OCTET_LENGTH(str)
CHAR_LENGTH(str)
CHARACTER_LENGTH(str)
文字列 str の長さ:
mysql> SELECT LENGTH('text');
        -> 4
mysql> SELECT OCTET_LENGTH('text');
        -> 4
注意: CHAR_LENGTH()CHARACTER_LENGTH() については、マルチバイト文字は一度だけしかカウントされません。
BIT_LENGTH(str)
Returns the length of the string str in bits:
mysql> SELECT BIT_LENGTH('text');
        -> 32
LOCATE(substr,str)
POSITION(substr IN str)
str 内にある substr 文字列の位置を返します。最初の位置は 1 です。 str 内に substr がない時は 0 を返します:
mysql> SELECT LOCATE('bar', 'foobarbar');
        -> 4
mysql> SELECT LOCATE('xbar', 'foobar');
        -> 0
この関数はマルチバイトでも安全です。 In MySQL 3.23 this function is case sensitive, while in 4.0 it's only case-sensitive if either argument is a binary string.
LOCATE(substr,str,pos)
文字列 str 中に最初に顕れた substr 文字の位置を返します。 pos は検索を開始する位置です。 strsubstr がなければ 0 を返します:
mysql> SELECT LOCATE('bar', 'foobarbar',5);
        -> 7
この関数はマルチバイトでも安全です。 In MySQL 3.23 this function is case sensitive, while in 4.0 it's only case-sensitive if either argument is a binary string.
INSTR(str,substr)
文字列 str 内の最初の文字列 substr の位置を返します。 これは引数が入れ替わっていることをのぞいて、 2つの引数を与えた LOCATE と同じです:
mysql> SELECT INSTR('foobarbar', 'bar');
        -> 4
mysql> SELECT INSTR('xbar', 'foobar');
        -> 0
この関数はマルチバイトでも安全です。 In MySQL 3.23 this function is case sensitive, while in 4.0 it's only case-sensitive if either argument is a binary string.
LPAD(str,len,padstr)
str の長さが len になるまで文字列 str の始めに padstr を埋めます。 strlen よりも長い場合は、len 文字に短くされます。
mysql> SELECT LPAD('hi',4,'??');
        -> '??hi'
RPAD(str,len,padstr)
str の長さが len になるまで文字列 str の終わりに padstr を埋めます。 strlen よりも長い場合は、len 文字に短くされます。
mysql> SELECT RPAD('hi',5,'?');
        -> 'hi???'
LEFT(str,len)
文字列 str の最初から len 個の文字を得ます:
mysql> SELECT LEFT('foobarbar', 5);
        -> 'fooba'
この関数はマルチバイトでも安全です。
RIGHT(str,len)
文字列 str の最後から len 個の文字を得ます:
mysql> SELECT RIGHT('foobarbar', 4);
        -> 'rbar'
この関数はマルチバイトでも安全です。
SUBSTRING(str,pos,len)
SUBSTRING(str FROM pos FOR len)
MID(str,pos,len)
strpos 位置から len 文字数分の文字列を返します。 FROM の違いは ANSI SQL 92 構文です:
mysql> SELECT SUBSTRING('Quadratically',5,6);
        -> 'ratica'
この関数はマルチバイトでも安全です。
SUBSTRING(str,pos)
SUBSTRING(str FROM pos)
文字列 str の 位置 pos 以降の文字を返します:
mysql> SELECT SUBSTRING('Quadratically',5);
        -> 'ratically'
mysql> SELECT SUBSTRING('foobarbar' FROM 4);
        -> 'barbar'
この関数はマルチバイトでも安全です。
SUBSTRING_INDEX(str,delim,count)
str から、区切り文字 delimcount 個現れた位置から前の 文字列を返します。count が正の場合は文字列は左から検索され、 count が負の場合は文字列は右から検索されます:
mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
        -> 'www.mysql'
mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
        -> 'mysql.com'
この関数はマルチバイトでも安全です。
LTRIM(str)
文字列 str の最初から空白文字を削除します:
mysql> SELECT LTRIM('  barbar');
        -> 'barbar'
RTRIM(str)
文字列 str の最後から空白文字を削除します:
mysql> SELECT RTRIM('barbar   ');
        -> 'barbar'
この関数はマルチバイトでも安全です。
TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str)
全ての remstr プレフィックスまたはサフィックスを str から削除した 文字列を返します。BOTH, LEADING そして TRAILING が 使用されない場合、BOTH が適用されます。remstr が与えられないと、 空白が削除されます:
mysql> SELECT TRIM('  bar   ');
        -> 'bar'
mysql> SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx');
        -> 'barxxx'
mysql> SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx');
        -> 'bar'
mysql> SELECT TRIM(TRAILING 'xyz' FROM 'barxxyz');
        -> 'barx'
This function is multi-byte safe. In MySQL 3.23 this function is case insensitive, while in 4.0 it's only case insensitive if either argument is a binary string.
SOUNDEX(str)
str からの soundex 文字列を返します。発音が``大体同じ''2つの文字列 は同じ soundex 文字列を持ちます。``標準の'' soundex 文字列は4文字長ですが、 SOUNDEX() 関数は任意の長さの文字列を返します。SUBSTRING() を 結果に使用して、``標準の'' soundex 文字列を得ることができます。与えられた 文字列中の非アルファベット文字は無視されます。A-Z の半以外のすべての国際的 なアルファベット文字は母音とみなされます:
mysql> SELECT SOUNDEX('Hello');
        -> 'H400'
mysql> SELECT SOUNDEX('Quadratically');
        -> 'Q36324'
SPACE(N)
N 個の空白文字を返します:
mysql> SELECT SPACE(6);
        -> '      '
REPLACE(str,from_str,to_str)
文字列 str 内の全ての文字列 from_strto_str に 置き換えます:
mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
        -> 'WwWwWw.mysql.com'
この関数はマルチバイトでも安全です。
REPEAT(str,count)
strcount 回繰り返します。count <= 0 の場合は 空の文字列を返します。str または countNULL または、LENGTH(str)*count > max_allowed_packet の場合は NULL を返します:
mysql> SELECT REPEAT('MySQL', 3);
        -> 'MySQLMySQLMySQL'
REVERSE(str)
文字列 str を反転します:
mysql> SELECT REVERSE('abc');
        -> 'cba'
この関数はマルチバイトでも安全です。
INSERT(str,pos,len,newstr)
str 中の pos 位置から len 長の文字列を newstr で置き換えます。str 内の最初の位置は1です:
mysql> SELECT INSERT('Quadratic', 3, 4, 'What');
        -> 'QuWhattic'
この関数はマルチバイトでも安全です。
ELT(N,str1,str2,str3,...)
N = 1 なら str1 を、N = 2 なら str2 を 返します。 N1 より小さい場合、または引数の数より大きい場合は NULL が返されます。 ELT()FIELD() の逆です:
mysql> SELECT ELT(1, 'ej', 'Heja', 'hej', 'foo');
        -> 'ej'
mysql> SELECT ELT(4, 'ej', 'Heja', 'hej', 'foo');
        -> 'foo'
FIELD(str,str1,str2,str3,...)
str1, str2, str3, ... リスト内の str のインデ ックスを 返します。str が見つからなければ 0 を返します。 FIELD()ELT() の逆です:
mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 2
mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 0
FIND_IN_SET(str,strlist)
strstrlist 中にあれば、値 1 から N を返します。 strlist は、それぞれの異なる値が ',' で分割された文字列です。最初の 引数が定数文字列で2番目が SET 型のフィールドの場合FIND_IN_SET は ビット演算を使用して最適化されます! strlist が空文字なら 0 を返します。 どちらかの引数が NULL なら NULL を返します. この関数は最初の引数が ',' を含んだ場合、うまく動かないでしょう:
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
        -> 2
MAKE_SET(bits,str1,str2,...)
bits に指定されたビットに対応する文字列のセットを返します。 (文字列が複数の場合、 `,' で区切られます) str1 が ビット 0 に対応し、str2 が ビット 1 に対応し、 str3 が ビット 2 に対応し... となります。 str1, str2, ... 中に含まれている NULL 文字は 結果には追加されません:
mysql> SELECT MAKE_SET(1,'a','b','c');
        -> 'a'
mysql> SELECT MAKE_SET(1 | 4,'hello','nice','world');
        -> 'hello,world'
mysql> SELECT MAKE_SET(0,'a','b','c');
        -> ''
EXPORT_SET(bits,on,off,[separator,[number_of_bits]])
'bits' に与えられた数値に対し、 全てのセットされているビットを 'on' で指定された文字で表し、 リセットされているビットを 'off' で指定された文字で表した文字列を返します。 それぞれの文字は 'separator' (デフォルト',') で示された文字で区切られ、 'number_of_bits' (default 64) に与えられた桁数だけのビットを表示します:
mysql> SELECT EXPORT_SET(5,'Y','N',',',4)
        -> Y,N,Y,N
LCASE(str)
LOWER(str)
str を現在のキャラクターセットマッピング (デフォルト ISO-8859-1 Latin1) にしたがって小文字に変換します:
mysql> SELECT LCASE('QUADRATICALLY');
        -> 'quadratically'
This function is multi-byte safe. In MySQL 3.23 this function is case insensitive, while in 4.0 it's only case insensitive if either argument is a binary string.
UCASE(str)
UPPER(str)
str を現在のキャラクターセットマッピング (デフォルト ISO-8859-1 Latin1) にしたがって大文字に変換します:
mysql> SELECT UCASE('Hej');
        -> 'HEJ'
This function is multi-byte safe. In MySQL 3.23 this function is case insensitive, while in 4.0 it's only case insensitive if either argument is a binary string.
LOAD_FILE(file_name)
ファイルを読み込み、ファイルの中身を文字として返します。 ファイルは サーバー上になくてはならず、ファイルをフルパスで指定しなければなりません。 そして、 FILE 権限がなければなりません。 ファイルは全員に 読み込み可能でなければならず、そして、 max_allowed_packet より 小さいサイズでなければなりません。 このうちどれかの理由で、もしファイルが存在しないか読み込めない場合、 この関数は NULL を返します:
mysql> UPDATE tbl_name
           SET blob_column=LOAD_FILE("/tmp/picture")
           WHERE id=1;
MySQL 3.23 を使用していない場合、あなたのアプリケーション内部でファ イルを読み込んで、ファイル情報でデータベースを更新するための INSERT ステートメントを生成する必要があります。これを行なう一つの方 法は、MySQL++ ライブラリを使用する場合、 http://www.mysql.com/documentation/mysql++/mysql++-examples.html で 見つけられます。
QUOTE(str)
Quotes a string to produce a result that can be used as a properly-escaped data value in a SQL statement. The string is returned surrounded by single quotes and with each instance of single quote (`''), backslash (`\'), ASCII NUL, and Control-Z preceded by a backslash. If the argument is NULL, the return value is the word ``NULL'' without surrounding single quotes.
mysql> SELECT QUOTE("Don't");
        -> 'Don\'t!'
mysql> SELECT QUOTE(NULL);
        -> NULL

String Comparison Functions

MySQL は必要とあらば数値を文字列に変換します。 逆も同様に行います:

mysql> SELECT 1+"1";
        -> 2
mysql> SELECT CONCAT(2,' test');
        -> '2 test'

明示的に数値を文字列に変換したければ、CONCAT() に引数として渡して下 さい。

文字列関数は引数としてバイナリ文字列が与えられると、結果の文字列もバイナリ 文字列になります。文字列に変換された数値はバイナリ文字列とみなされます。こ れは比較にだけ影響します。

通常、比較される表現がケース依存でない場合、比較はケース非依存で行われます。

expr LIKE pat [ESCAPE 'escape-char']
SQL の簡単な正規表現比較です。1 (TRUE) または 0 (FALSE) を返します 。 LIKE には2つのワイルドカードがあります:
Char Description
% 任意の数の文字(0文字も含む)に適合します。
_ 厳密に1つの文字に適合します。
mysql> SELECT 'David!' LIKE 'David_';
        -> 1
mysql> SELECT 'David!' LIKE '%D%v%';
        -> 1
ワイルドカード文字のテストをするためには、エスケープ文字より先行しておこなって ください。 ESCAPE を指定しない場合は、文字 `\' が使われます:
String Description
\% 1つの % に適合します。
\_ 1つの _ に適合します。
mysql> SELECT 'David!' LIKE 'David\_';
        -> 0
mysql> SELECT 'David_' LIKE 'David\_';
        -> 1
違うエスケープ文字を指定するには、 ESCAPE 節を使用します:
mysql> SELECT 'David_' LIKE 'David|_' ESCAPE '|';
        -> 1
次の2つのステートメントは、オペランドの一つがバイナリ文字列でなければ、文 字列比較がケース非依存であることを示しています:
mysql> SELECT 'abc' LIKE 'ABC';
        -> 1
mysql> SELECT 'abc' LIKE BINARY 'ABC';
        -> 0
LIKE は数値表現でも許されます! (これは MySQL の、ANSI SQL LIKE に対する拡張です) 注意: MySQL は文字列中に C のエスケープ文字を使用しているので(e.g., `\n'), LIKE の指定文字列として使用するには `\' を 二倍しなくてはなりません。 例えば、 `\n' を探すには、`\\n' と 記述します。 `\' を探すには、 `\\\\' (バックスラッシュは、 一つはパーサーに取り除かれ、パターンマッチが行われる際にもうひとつ 取り除かれ、一致を探すために残った一つのバックスラッシュが使用されます)
expr NOT LIKE pat [ESCAPE 'escape-char']
NOT (expr LIKE pat [ESCAPE 'escape-char']) と同じ
expr SOUNDS LIKE expr
Same as SOUNDEX(expr)=SOUNDEX(expr) (available only in version 4.1 or later).
expr REGEXP pat
expr RLIKE pat
パターン pat に対し、文字式 expr のパターンマッチを行います。 パターン pat は正規表現の拡張が使用できます。See section MySQL の正規表現. もし exprpat にマッチするなら 1 を返し、 でなければ 0 を返します。 RLIKEREGEXP と同義で、mSQL 互換を提供します。 注意: MySQL は C エスケープ構文を文字中に使用しており(\n)、 REGEXP 中で使用される '\' 文字はすべて、二重に書かなければ なりません。 MySQL 3.23.4 REGEXP は、普通の文字 (not binary) はケース非依存で す:
mysql> SELECT 'Monty!' REGEXP 'm%y%%';
        -> 0
mysql> SELECT 'Monty!' REGEXP '.*';
        -> 1
mysql> SELECT 'new*\n*line' REGEXP 'new\\*.\\*line';
        -> 1
mysql> SELECT "a" REGEXP "A", "a" REGEXP BINARY "A";
        -> 1  0
mysql> SELECT "a" REGEXP "^[a-d]";
        -> 1
REGEXP and RLIKE は、文字の型を決定する場合、 カレントのキャラクターセットを使用します。 (ISO-8859-1 Latin1 がデフォルト)
expr NOT REGEXP pat
expr NOT RLIKE pat
NOT (expr REGEXP pat) と同じ.
STRCMP(expr1,expr2)
STRCMP() 文字列が同じなら 0 を返します。そうでなければ、最初の引数がソート順で小 さければ -1 を返します。そうでなければ 1 を返します:
mysql> SELECT STRCMP('text', 'text2');
        -> -1
mysql> SELECT STRCMP('text2', 'text');
        -> 1
mysql> SELECT STRCMP('text', 'text');
        -> 0
MATCH (col1,col2,...) AGAINST (expr)
MATCH ... AGAINST() は全文検索に使用され、妥当性を返します。フィー ルド (col1,col2,...) 内のテキストとクエリ expr との間の類似 点を評価します。妥当性は正の浮動小数点数です。妥当性 0 は類似点なしを意味 します。MATCH ... AGAINST() が動作するためには、最初に FULLTEXT インデックスが作成する必要があります。 See section CREATE TABLE 構文MATCH ... AGAINST() は MySQL 3.23.23 以上のバージョンで有 効です。 IN BOOLEAN MODE extension was added in version 4.0.1. 詳細と使用例は section MySQL Full-text Search.

Case-Sensitivity

BINARY
BINARY 演算子は、これ以降に続く文字をバイナリにキャストします。 これはたとえフィールドが BINARYBLOB 定義でなくても、 ケース依存でフィールドを比較することが出来る簡単な方法です:
mysql> SELECT "a" = "A";
        -> 1
mysql> SELECT BINARY "a" = "A";
        -> 0
BINARY string is a shorthand for CAST(string AS BINARY). See section Cast Functions. BINARY は MySQL 3.23.0 で登場しました。 注意: いくつかの文脈では、インデックスされたフィールドを BINARY に キャストした時、MySQL はインデックスを効率よく使用できません。

BLOB をケース非依存で比較したい場合、比較を行なう前に BLOB を常に大文字に 変換します:

SELECT 'A' LIKE UPPER(blob_col) FROM table_name;

より柔軟に文字列を比較するために、我々は間もなく異なる文字セット間のキャス トを導入する予定です。

Numeric Functions

算術演算

普通の算術演算が有効です。 -, +, * は、二つの引数が正数ならば BIGINT (64bit精度) で計算されることに注意してください! If one of the argument is an unsigned integer, and the other argument is also an integer, the result will be an unsigned integer. See section Cast Functions.

+
足し算:
mysql> SELECT 3+5;
        -> 8
-
引き算:
mysql> SELECT 3-5;
        -> -2
*
掛け算:
mysql> SELECT 3*5;
        -> 15
mysql> SELECT 18014398509481984*18014398509481984.0;
        -> 324518553658426726783156020576256.0
mysql> SELECT 18014398509481984*18014398509481984;
        -> 0
最後の式の結果は不当です。なぜなら結果は BIGINT の 64 ビットを超えた整数だからです。
/
割り算:
mysql> SELECT 3/5;
        -> 0.60
0 で割った場合、NULL になります。
mysql> SELECT 102/(1-1);
        -> NULL
演算結果が整数になる場合にだけ、 BIGINT を用いて割り算は計算されます。

数学関数

すべての数学関数はエラーの場合 NULL を返します。

-
符号。引数の符号を変更します:
mysql> SELECT - 2;
        -> -2
このオペレーターが BIGINT とともに使用された場合、 返り値は BIGINT であることに注意してください! これは -2^63 の値を 持つかもしれない整数を、 - で使用してはならないことを意味します!
ABS(X)
Returns the absolute value of X:
mysql> SELECT ABS(2);
        -> 2
mysql> SELECT ABS(-32);
        -> 32
この関数は BIGINT 値とともに使用されると安全です。
SIGN(X)
X が負数、ゼロ、整数によって、 -1, 0 or 1 を 返します:
mysql> SELECT SIGN(-32);
        -> -1
mysql> SELECT SIGN(0);
        -> 0
mysql> SELECT SIGN(234);
        -> 1
MOD(N,M)
%
剰余 ( C の % 演算子のような ). NM で割ったときの余りが返ります:
mysql> SELECT MOD(234, 10);
        -> 4
mysql> SELECT 253 % 7;
        -> 1
mysql> SELECT MOD(29,9);
        -> 2
この関数は BIGINT 値でも安全に使用できます。
FLOOR(X)
X より大きくならない整数のうち、最大の整数値を返します:
mysql> SELECT FLOOR(1.23);
        -> 1
mysql> SELECT FLOOR(-1.23);
        -> -2
返り値は BIGINT に変換されていることに注意!
CEILING(X)
X より小さくならない整数のうち、最小の整数値を返します.
mysql> SELECT CEILING(1.23);
        -> 2
mysql> SELECT CEILING(-1.23);
        -> -1
返り値は BIGINT に変換されていることに注意!
ROUND(X)
X を整数に丸めた値(四捨五入)を返します:
mysql> SELECT ROUND(-1.23);
        -> -1
mysql> SELECT ROUND(-1.58);
        -> -2
mysql> SELECT ROUND(1.58);
        -> 2
引数が2つの整数間の半分時の ROUND() の振る舞いは、C ライブラリの実 装に依存します。いくつかは、近い偶数値、常に上、常に下、または常に0方向に 丸めます。丸めの種類の一つを必要とする場合は、TRUNCATE() または FLOOR() のようなはっきりと定義された関数を代わりに使用すべきです。
ROUND(X,D)
XD で指定した少数桁に丸めた値(四捨五入)を返します。 もし D0 なら, 結果は小数点無しになるか 少数部分になるでしょう:
mysql> SELECT ROUND(1.298, 1);
        -> 1.3
mysql> SELECT ROUND(1.298, 0);
        -> 1
EXP(X)
指数関数 : e (自然対数の底) の X 乗:
mysql> SELECT EXP(2);
        -> 7.389056
mysql> SELECT EXP(-2);
        -> 0.135335
LN(X)
Returns the natural logarithm of X:
mysql> SELECT LN(2);
        -> 0.693147
mysql> SELECT LN(-2);
        -> NULL
This function was added in MySQL version 4.0.3. It is synonymous with LOG(X) in MySQL.
LOG(X)
LOG(B,X)
自然対数 X: If called with one parameter, this function returns the natural logarithm of X:
mysql> SELECT LOG(2);
        -> 0.693147
mysql> SELECT LOG(-2);
        -> NULL
任意の底 B に対する X の対数を得たければ、公式 LOG(X)/LOG(B) を使用してください。 If called with two parameters, this function returns the logarithm of X for an arbitary base B:
mysql> SELECT LOG(2,65536);
        -> 16.000000
mysql> SELECT LOG(1,100);
        -> NULL
The arbitrary base option was added in MySQL version 4.0.3. LOG(B,X) is equivalent to LOG(X)/LOG(B).
LOG2(X)
Returns the base-2 logarithm of X:
mysql> SELECT LOG2(65536);
        -> 16.000000
mysql> SELECT LOG2(-100);
        -> NULL
LOG2() is useful for finding out how many bits a number would require for storage. This function was added in MySQL version 4.0.3. In earlier versions, you can use LOG(X)/LOG(2) instead.
LOG10(X)
常用対数(10を底とした対数) X:
mysql> SELECT LOG10(2);
        -> 0.301030
mysql> SELECT LOG10(100);
        -> 2.000000
mysql> SELECT LOG10(-100);
        -> NULL
POW(X,Y)
POWER(X,Y)
XY 乗:
mysql> SELECT POW(2,2);
        -> 4.000000
mysql> SELECT POW(2,-2);
        -> 0.250000
SQRT(X)
X の非負の平方根を返します:
mysql> SELECT SQRT(4);
        -> 2.000000
mysql> SELECT SQRT(20);
        -> 4.472136
PI()
π の値を返します。デフォルトの表示桁数は 5 ですが、MySQL 内部で は π に完全な倍精度を使用します。
mysql> SELECT PI();
        -> 3.141593
mysql> SELECT PI()+0.000000000000000000;
        -> 3.141592653589793116
COS(X)
コサイン XX はラジアン:
mysql> SELECT COS(PI());
        -> -1.000000
SIN(X)
サイン XX はラジアン:
mysql> SELECT SIN(PI());
        -> 0.000000
TAN(X)
タンジェント XX はラジアン:
mysql> SELECT TAN(PI()+1);
        -> 1.557408
ACOS(X)
X のアークコサインを返します。これはコサインが X である値で す。X-1 から 1 の範囲にない場合は NULL を 返します:
mysql> SELECT ACOS(1);
        -> 0.000000
mysql> SELECT ACOS(1.0001);
        -> NULL
mysql> SELECT ACOS(0);
        -> 1.570796
ASIN(X)
X のアークサインを返します。これはサインが X である値です。 X-1 から 1 の範囲にない場合は NULL を返し ます:
mysql> SELECT ASIN(0.2);
        -> 0.201358
mysql> SELECT ASIN('foo');
        -> 0.000000
ATAN(X)
X のアークタンジェントを返します。これはタンジェントが X で ある値です:
mysql> SELECT ATAN(2);
        -> 1.107149
mysql> SELECT ATAN(-2);
        -> -1.107149
ATAN(Y,X)
ATAN2(Y,X)
2つの変数 XY のアークタンジェントを返します。両方の引数 の符号が結果の象限を決定するために使用されることを除いて、Y / X の アークタンジェントの計算と同様です:
mysql> SELECT ATAN(-2,2);
        -> -0.785398
mysql> SELECT ATAN2(PI(),0);
        -> 1.570796
COT(X)
X のコタンジェントを返します:
mysql> SELECT COT(12);
        -> -1.57267341
mysql> SELECT COT(0);
        -> NULL
RAND()
RAND(N)
0 から 1.0 間のランダムな浮動小数点数値を返します。 もし N に整数を与えた場合、シードとしてこの値が使用されます:
mysql> SELECT RAND();
        -> 0.9233482386203
mysql> SELECT RAND(20);
        -> 0.15888261251047
mysql> SELECT RAND(20);
        -> 0.15888261251047
mysql> SELECT RAND();
        -> 0.63553050033332
mysql> SELECT RAND();
        -> 0.70100469486881
RAND() 値を持つフィールドは ORDER BY 節で使用できません。 ORDER BY はフィールドを複数回評価するためです。 しかし MySQL バージョン 3.23 では, 次が可能です: SELECT * FROM table_name ORDER BY RAND() これは SELECT * FROM table1,table2 WHERE a=b AND c<d ORDER BY RAND() LIMIT 1000 のセットからランダムなサンプルを得るのに便利です。 注意: WHERE 節の RAND()WHERE が実行する度に再評価 されます。 RAND() is not meant to be a perfect random generator, but instead a fast way to generate ad hoc random numbers that will be portable between platforms for the same MySQL version.
LEAST(X,Y,...)
二つ以上の引数を取り、引数中、最小の値を返します。 引数は以下の規則に従って比較されます:
mysql> SELECT LEAST(2,0);
        -> 0
mysql> SELECT LEAST(34.0,3.0,5.0,767.0);
        -> 3.0
mysql> SELECT LEAST("B","A","C");
        -> "A"
バージョン 3.22.5 以前の MySQL では、MIN()LEAST の代 わりに使用できます。
GREATEST(X,Y,...)
二つ以上の引数を取り、引数中、最大の値を返します。 引数は LEAST の時と同じように比較されます。
mysql> SELECT GREATEST(2,0);
        -> 2
mysql> SELECT GREATEST(34.0,3.0,5.0,767.0);
        -> 767.0
mysql> SELECT GREATEST("B","A","C");
        -> "C"
バージョン 3.22.5 以前の MySQL では、MAX()GREATEST の 代わりに使用できます。
DEGREES(X)
引数 X をラジアンから度に変換して返します:
mysql> SELECT DEGREES(PI());
        -> 180.000000
RADIANS(X)
引数 X を度からラジアンに変換して返します:
mysql> SELECT RADIANS(90);
        -> 1.570796
TRUNCATE(X,D)
少数点以下 D 桁で X を切り捨てた値を返します。 D0 の場合、結果は小数部や微小部を持ちません:
mysql> SELECT TRUNCATE(1.223,1);
        -> 1.2
mysql> SELECT TRUNCATE(1.999,1);
        -> 1.9
mysql> SELECT TRUNCATE(1.999,0);
        -> 1
mysql> SELECT TRUNCATE(-1.999,1);
        -> -1.9
Starting from MySQL 3.23.51 all numbers are rounded towards zero. If D is negative, then the whole part of the number is zeroed out:
mysql> SELECT TRUNCATE(122,-2);
       -> 100
注意: コンピュータでは小数点数は正確な数値としては格納されず、double 値と して格納されます。次の結果によってだまされるでしょう:
mysql> SELECT TRUNCATE(10.28*100,0);
       -> 1027
上記は 10.28 は実際には 10.2799999999999999 のようなものとして格納さえるた めに発生します。

日付と時刻関数

それぞれの型がもつ値の範囲と日と時間の値が記述される有効な形式については section 日付と時間の型.

日付関数を使用する例: date_col が最新の30日である全てのレコードを選択します:

mysql> SELECT something FROM table
           WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 30;
DAYOFWEEK(date)
Returns the weekday index date の曜日を得ます (1 = 日曜日, 2 = 月曜日, ... 7 = 土曜日) これは ODBC 標準に従います:
mysql> SELECT DAYOFWEEK('1998-02-03');
        -> 3
WEEKDAY(date)
date の曜日を得ます (0 = 月曜日, 1 = 火曜日, ... 6 = 日曜日):
mysql> SELECT WEEKDAY('1998-02-03 22:23:00');
        -> 1
mysql> SELECT WEEKDAY('1997-11-05');
        -> 2
DAYOFMONTH(date)
月の日を返します (1 - 31):
mysql> SELECT DAYOFMONTH('1998-02-03');
        -> 3
DAYOFYEAR(date)
年の日を返します (1-366): 366:
mysql> SELECT DAYOFYEAR('1998-02-03');
        -> 34
MONTH(date)
月を返します (1 - 12):
mysql> SELECT MONTH('1998-02-03');
        -> 2
DAYNAME(date)
曜日の名前を返します:
mysql> SELECT DAYNAME("1998-02-05");
        -> 'Thursday'
MONTHNAME(date)
月の名前を返します:
mysql> SELECT MONTHNAME("1998-02-05");
        -> 'February'
QUARTER(date)
date についての年の四半期を返します。範囲は 1 から 4 です:
mysql> SELECT QUARTER('98-04-01');
        -> 2
WEEK(date)
WEEK(date,first)
引数が一つの場合、date についての週を返します。範囲は 0 から 53 (そう、53週の最初というのもありえます)で、日曜日が週の 最初の日です。 引数が二つの形式の WEEK() は、週の開始を日曜日か月曜日か指定できます。 それぞれの場合の返り値は 0-531-52 です。 Here is a table for how the second arguments work:
Value Meaning
0 Week starts on Sunday and return value is in range 0-53
1 Week starts on Monday and return value is in range 0-53
2 Week starts on Sunday and return value is in range 1-53
3 Week starts on Monday and return value is in range 1-53 (ISO 8601)
mysql> SELECT WEEK('1998-02-20');
        -> 7
mysql> SELECT WEEK('1998-02-20',0);
        -> 7
mysql> SELECT WEEK('1998-02-20',1);
        -> 8
mysql> SELECT WEEK('1998-12-31',1);
        -> 53
Note: in Version 4.0, WEEK(#,0) was changed to match the calendar in the USA. Note that if a week is the last week of the previous year, MySQL will return 0 if you don't use 2 or 3 as the optional argument:
mysql> SELECT YEAR('2000-01-01'), WEEK('2000-01-01',0);
        -> 2000, 0
mysql> SELECT WEEK('2000-01-01',2);
        -> 52
One could argue that MySQL should return 52 for the WEEK() function as the given date is actually the 52 second week of 1999. We decided to return 0 instead as we want the function to return 'the week number in the given year'. This makes the usage of the WEEK() function reliable when combined with other functions that extracts a date part from a date. If you would prefer to know the correct year-week, then you should use the 2 or 3 as the optional argument or use the YEARWEEK() function:
mysql> SELECT YEARWEEK('2000-01-01');
        -> 199952
mysql> SELECT MID(YEARWEEK('2000-01-01'),5,2);
        -> 52
YEAR(date)
年を返します (1000 - 9999):
mysql> SELECT YEAR('98-02-03');
        -> 1998
YEARWEEK(date)
YEARWEEK(date,first)
データの年と週を返します。第2引数は WEEK() の第2引数とまったく同じ ように働きます。注意: 年の最初と最後の週では、年が date 引数内の年とは異な ることがあります!
mysql> SELECT YEARWEEK('1987-01-01');
        -> 198653
Note that the week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year.
HOUR(time)
時を返します (0 - 23):
mysql> SELECT HOUR('10:05:03');
        -> 10
MINUTE(time)
分を返します (0-59):
mysql> SELECT MINUTE('98-02-03 10:05:03');
        -> 5
SECOND(time)
秒を返します (0 to 59)
mysql> SELECT SECOND('10:05:03');
        -> 3
PERIOD_ADD(P,N)
N 月を期間 P (型 YYMM または YYYYMM) に追加 します。YYYYMM を返します。 注意: 期間引数 P は日付値では ありません
mysql> SELECT PERIOD_ADD(9801,2);
        -> 199803
PERIOD_DIFF(P1,P2)
期間 P1P2 の差の月を返します。P1P2 は形 式 YYMM または YYYYMM です。 注意: 期間引数 P1P2 は日付値では ありません
mysql> SELECT PERIOD_DIFF(9802,199703);
        -> 11
DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
ADDDATE(date,INTERVAL expr type)
SUBDATE(date,INTERVAL expr type)
これら関数は日付の演算に使用します。 これらは MySQL バージョン 3.22 の 新しい機能です。 ADDDATE()SUBDATE()DATE_ADD() , DATE_SUB() と同義です。 MySQL バージョン 3.23 では, +-DATE_ADD() , DATE_SUB() の代わりに使用できます. (See example below.) date には、DATETIMEDATE 型の値を指定します。 この値から演算が開始されます。 expr には、date から増減させる値を指定します。 expr`-' から始まっていれば、負数を示します。 type はどれぐらいの期間かを示すキーワードです。 EXTRACT(type FROM date) 関数は、date から 'type' の部分を返します。 以下の表に、typeexpr の関連を示します:
type value Expected expr format
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
MONTH MONTHS
YEAR YEARS
MINUTE_SECOND "MINUTES:SECONDS"
HOUR_MINUTE "HOURS:MINUTES"
DAY_HOUR "DAYS HOURS"
YEAR_MONTH "YEARS-MONTHS"
HOUR_SECOND "HOURS:MINUTES:SECONDS"
DAY_MINUTE "DAYS HOURS:MINUTES"
DAY_SECOND "DAYS HOURS:MINUTES:SECONDS"
MySQL は、 expr フォーマット内のいかなる句読点区切りをも許します。 上の表中の区切り文字は提案する区切り文字です。 もし date 引数が DATE 値で、YEAR, MONTH, DAY の部分のみを含む 計算をするなら、結果は DATE 値が返ります。 それ以外なら DATETIME 値が返ります:
mysql> SELECT "1997-12-31 23:59:59" + INTERVAL 1 SECOND;
        -> 1998-01-01 00:00:00
mysql> SELECT INTERVAL 1 DAY + "1997-12-31";
        -> 1998-01-01
mysql> SELECT "1998-01-01" - INTERVAL 1 SECOND;
       -> 1997-12-31 23:59:59
mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
    ->                 INTERVAL 1 SECOND);
        -> 1998-01-01 00:00:00
mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
    ->                 INTERVAL 1 DAY);
        -> 1998-01-01 23:59:59
mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
    ->                 INTERVAL "1:1" MINUTE_SECOND);
        -> 1998-01-01 00:01:00
mysql> SELECT DATE_SUB("1998-01-01 00:00:00",
    ->                 INTERVAL "1 1:1:1" DAY_SECOND);
        -> 1997-12-30 22:58:59
mysql> SELECT DATE_ADD("1998-01-01 00:00:00",
    ->                 INTERVAL "-1 10" DAY_HOUR);
        -> 1997-12-30 14:00:00
mysql> SELECT DATE_SUB("1998-01-02", INTERVAL 31 DAY);
        -> 1997-12-02
もしあなたの指定する interval 値が短すぎるなら( type キーワードから 類推される値を含んでいない場合)、 MySQL は interval 値の一番 左の部分を指定し忘れたものだと仮定します。 例えば、もし typeDAY_SECOND に指定した場合、 expr の値は 日、時、分、秒 からなる物と期待されます。 ここであなたが "1:10" のような値を指定していたなら、 MySQL は、日、時 の部分が忘れ去られて、分、秒 が与えられたと 推定します。 つまり、 "1:10" DAY_SECOND"1:10" MINUTE_SECOND で あると理解されるのです。 これは、MySQL が TIME 値を時刻ではなく経過時間の表現と解釈 する方法に類似しています。 注意: 時刻部を含む何かに対して、日付値の加算や減算を行なう場合、日付値は自 動的に日時値に変換されます:
mysql> SELECT DATE_ADD("1999-01-01", INTERVAL 1 DAY);
       -> 1999-01-02
mysql> SELECT DATE_ADD("1999-01-01", INTERVAL 1 HOUR);
       -> 1999-01-01 01:00:00
もし、不正な値が使用されたなら、結果は NULL です. もし MONTHYEAR_MONTHYEAR を足し算して、 結果となる日付が新しい月の最大日よりも大きい日になるようなら、 その日は、新しい月の最大日に修正されます。
mysql> SELECT DATE_ADD('1998-01-30', Interval 1 month);
        -> 1998-02-28
例のように、INTERVALtype キーワードは ケース依存ではありません.
EXTRACT(type FROM date)
The EXTRACT() function uses the same kinds of interval type specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic.
mysql> SELECT EXTRACT(YEAR FROM "1999-07-02");
       -> 1999
mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03");
       -> 199907
mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:02:03");
       -> 20102
TO_DAYS(date)
日付 date を与えると、0年からの日数を返します。
mysql> SELECT TO_DAYS(950501);
        -> 728779
mysql> SELECT TO_DAYS('1997-10-07');
        -> 729669
TO_DAYS() はグレゴリオ歴の開始(1582)より前の値での使用を意図されて いません。歴が変更された時に失われた日を考慮に入れてないからです。
FROM_DAYS(N)
与えられた日数 N から DATE 値を返します:
mysql> SELECT FROM_DAYS(729669);
        -> '1997-10-07'
FROM_DAYS() はグレゴリオ歴の開始(1582)より前の値での使用を意図され ていません。歴が変更された時に失われた日を考慮に入れてないからです。
DATE_FORMAT(date,format)
date 値を format 文字列に従って整形します。次の指定が format 文字列で使用できます:
Specifier Description
%M 月名 (January..December)
%W 曜日 (Sunday..Saturday)
%D 英語サフィックス付き月の日 (0th, 1st, 2nd, 3rd, etc.)
%Y 4桁の年
%y 2桁の年
%X 週の年。週の最初の日は日曜日。4桁の数値。'%V' と共に使用されます
%x 週の年。週の最初の日は月曜日。4桁の数値。'%v' と共に使用されます
%a 省略された曜日名 (Sun..Sat)
%d 月の日, 数値 (00..31)
%e 月の日, 数値 (0..31)
%m 月, 数値 (00..12)
%c 月, 数値 (0..12)
%b 省略された月名 (Jan..Dec)
%j 年の日 (001..366)
%H 時 (00..23)
%k 時 (0..23)
%h 時 (01..12)
%I 時 (01..12)
%l 時 (1..12)
%i 分, 数値 (00..59)
%r 時刻, 12時間 (hh:mm:ss [AP]M)
%T 時刻, 24時間 (hh:mm:ss)
%S 秒 (00..59)
%s 秒 (00..59)
%p AM or PM
%w 週の日 (0=Sunday..6=Saturday)
%U 週 (00..53), 週のはじまりを 日曜とした場合
%u 週 (00..53), 週のはじまりを 月曜とした場合
%V 週 (01..53), 週のはじまりは日曜日。'%X' と共に使用されます
%v 週 (01..53), 週のはじまりは月曜日。'%x' と共に使用されます
%% リテラル `%'
他の全ての文字は解釈されずに結果にコピーされます:
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
        -> 'Saturday October 1997'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%H:%i:%s');
        -> '22:23:00'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
                          '%D %y %a %d %m %b %j');
        -> '4th 97 Sat 04 10 Oct 277'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
                          '%H %k %I %r %T %S %w');
        -> '22 22 10 10:23:00 PM 22:23:00 00 6'
mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
        -> '1998 52'
MySQL バージョン 3.23 では、 % 文字はフォーマット文字の前に必ず 必要とされます。 それより前のバージョンでは、 % 文字はオプションでした。 The reason the ranges for the month and day specifiers begin with zero is that MySQL allows incomplete dates such as '2004-00-00' to be stored as of MySQL 3.23.
TIME_FORMAT(time,format)
これは上記の DATE_FORMAT() のように使用されますが、 format オプションでは、時,分,秒だけを操作できます。 他のオプションは NULL or 0 を与えます。
CURDATE()
CURRENT_DATE
今日の日付を返します。日付の形式は、CURDATE() が数値または文字列のどち らの文脈で使用されたかに依存して YYYYMMDD または 'YYYY-MM-DD' で返 されます:
mysql> SELECT CURDATE();
        -> '1997-12-15'
mysql> SELECT CURDATE() + 0;
        -> 19971215
CURTIME()
CURRENT_TIME
現在の時刻を HHMMSS または 'HH:MM:SS' の形式で返します。こ れは CURTIME() が数値または文字列のどちらの文脈で使用されたかに依 存します:
mysql> SELECT CURTIME();
        -> '23:50:26'
mysql> SELECT CURTIME() + 0;
        -> 235026
NOW()
SYSDATE()
CURRENT_TIMESTAMP
現在の時刻を返します。数値または文字列のどちらの文脈で使用されたかに依存して YYYYMMDDHHMMSS または 'YYYY-MM-DD HH:MM:SS' 形式で返されます:
mysql> SELECT NOW();
        -> '1997-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 19971215235026
Note that NOW() is only evaluated once per query, namely at the start of query execution. This means that multiple references to NOW() within a single query will always give the same time.
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
引数なしで呼び出された場合は、UNIX timestamp (GMT '1970-01-01 00:00:00' からの秒数) です。If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' GMT. date はローカル時刻での DATE 文字列、DATETIME 文字列、TIMESTAMP, または YYMMDD または YYYYMMDD 形式の数値です:
mysql> SELECT UNIX_TIMESTAMP();
        -> 882226357
mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');
        -> 875996580
UNIX_TIMESTAMPTIMESTAMP フィールドに使用された場合、 この関数は、暗黙の ``文字から UNIX タイムスタンプ'' 変換をすることなく、 値を得ます。 If you pass an out-of-range date to UNIX_TIMESTAMP() it will return 0, but please note that only basic checking is performed (year 1970-2037, month 01-12, day 01-31). If you want to subtract UNIX_TIMESTAMP() columns, you may want to cast the result to signed integers. See section Cast Functions.
FROM_UNIXTIME(unix_timestamp)
文脈(数値/文字列)に依存して、'YYYY-MM-DD HH:MM:SS' または YYYYMMDDHHMMSS 形式の timestamp 文字列を返します:
mysql> SELECT FROM_UNIXTIME(875996580);
        -> '1997-10-04 22:23:00'
mysql> SELECT FROM_UNIXTIME(875996580) + 0;
        -> 19971004222300
FROM_UNIXTIME(unix_timestamp,format)
format に従って整形された UNIX timestamp 文字列を返します。 formatDATE_FORMAT() 関数のエントリに一覧されたのと同じ指 定子を含むことができます:
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
                            '%Y %D %M %h:%i:%s %x');
        -> '1997 23rd December 03:43:30 1997'
SEC_TO_TIME(seconds)
seconds 引数を時分秒に変換して返します。関数が文字列文脈または数値 文脈のどちらで使用されたかに依存して、'HH:MM:SS' または HHMMSS 形式で値を返します:
mysql> SELECT SEC_TO_TIME(2378);
        -> '00:39:38'
mysql> SELECT SEC_TO_TIME(2378) + 0;
        -> 3938
TIME_TO_SEC(time)
time を秒に変換します。
mysql> SELECT TIME_TO_SEC('22:23:00');
        -> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
        -> 2378

Cast Functions

The syntax of the CAST function is:

CAST(expression AS type)

or

CONVERT(expression,type)

Where type is one of:

CAST() is ANSI SQL99 syntax and CONVERT() is ODBC syntax.

The cast function is mainly useful when you want to create a column with a specific type in a CREATE ... SELECT:

CREATE TABLE new_table SELECT CAST('2000-01-01' AS DATE);

CAST(string AS BINARY is the same thing as BINARY string. CAST(expr AS CHAR threats expression to be a string with the default character set.

To cast a string to a numeric value, you don't normally have to do anything; just use the string value as it would be a number:

mysql> SELECT 1+'1';
       -> 2

If you use a number in string context the number will automatically be converted to a BINARY string.

mysql> SELECT CONCAT("hello you ",2);
       ->  "hello you 2"

MySQL supports arithmetic with both signed and unsigned 64-bit values. If you are using an numerical operations (like +) and one of the operands are unsigned integer, then the result will be unsigned. You can override this by using the SIGNED and UNSIGNED cast operators, which will cast the operation to a signed or unsigned 64-bit integer, respectively.

mysql> SELECT CAST(1-2 AS UNSIGNED)
        -> 18446744073709551615
mysql> SELECT CAST(CAST(1-2 AS UNSIGNED) AS SIGNED);
        -> -1

Note that if either operation is a floating-point value (In this context DECIMAL() is regarded as a floating-point value) the result will be a floating-point value and is not affected by the above rule.

mysql> SELECT CAST(1 AS UNSIGNED) -2.0
        -> -1.0

If you are using a string in an arithmetic operation, this is converted to a floating-point number.

The CAST() and CONVERT() functions were added in MySQL 4.0.2.

The handing of unsigned values was changed in MySQL 4.0 to be able to support BIGINT values properly. If you have some code that you want to run in both MySQL 4.0 and 3.23 (in which case you probably can't use the CAST function), you can use the following trick to get a signed result when subtracting two unsigned integer columns:

SELECT (unsigned_column_1+0.0)-(unsigned_column_2+0.0);

The idea is that the columns are converted to floating-point before doing the subtraction.

If you get a problem with UNSIGNED columns in your old MySQL application when porting to MySQL 4.0, you can use the --sql-mode=NO_UNSIGNED_SUBTRACTION option when starting mysqld. Note however that as long as you use this, you will not be able to make efficient use of the UNSIGNED BIGINT column type.

その他の関数

ビット関数

これらは最大 64 ビットの範囲を持ちます。MySQL は BIGINT (64-bit) 演算を使用するためです。

|
ビット演算 OR
mysql> SELECT 29 | 15;
        -> 31
The result is an unsigned 64-bit integer.
&
ビット演算 AND
mysql> SELECT 29 & 15;
        -> 13
The result is an unsigned 64-bit integer.
^
Bitwise XOR
mysql> SELECT 1 ^ 1;
        -> 0
mysql> SELECT 1 ^ 0;
        -> 1
mysql> SELECT 11 ^ 3;
        -> 8
The result is an unsigned 64-bit integer. XOR was added in version 4.0.2.
<<
左に longlong (BIGINT) number 分、ビットをシフトします:
mysql> SELECT 1 << 2;
        -> 4
The result is an unsigned 64-bit integer.
>>
右に longlong (BIGINT) number 分、ビットをシフトします:
mysql> SELECT 4 >> 2;
        -> 1
The result is an unsigned 64-bit integer.
~
Invert all bits:
mysql> SELECT 5 & ~1;
        -> 4
The result is an unsigned 64-bit integer.
BIT_COUNT(N)
引数 N がいくつビットを持っているか(2進数表記したときの1の数):
mysql> SELECT BIT_COUNT(29);
        -> 4

その他の関数

DATABASE()
現在のデータベース名を返します
mysql> SELECT DATABASE();
        -> 'test'
もしデータベースが選択されていないなら、DATABASE() は空文字を返します。
USER()
SYSTEM_USER()
SESSION_USER()
Returns the current MySQL user name:
mysql> SELECT USER();
        -> 'davida@localhost'
MySQL バージョン 3.22.11 以降では、この関数はユーザー名とクライアントの ホスト名を含みます。 ユーザー名の部分だけ取り出すには次のようにします。 (これはホスト名が含まれていなくとも動くでしょう):
mysql> SELECT substring_index(USER(),"@",1);
        -> 'davida'
CURRENT_USER()
Returns the user name, current session was authentificated as:
mysql> SELECT USER();
        -> 'davida@localhost'
mysql> SELECT * FROM mysql.user;
        -> ERROR 1044: Access denied for user: '@localhost' to database 'mysql'
mysql> SELECT CURRENT_USER();
        -> '@localhost'
PASSWORD(str)
OLD_PASSWORD(str)
プレーンテキストのパスワード str からパスワード文字列を計算します。 これは user 許可テーブルの Password フィールドに、 暗号化された MySQL パスワードを保存する際に使用されます:
mysql> SELECT PASSWORD('badpwd');
        -> '7f84554057dd964b'
PASSWORD() 暗号は不可逆です。 PASSWORD() は UNIX のパスワードが暗号化するのと同じ方法で 暗号化を行うわけではありません。 ENCRYPT() 参照。 注意: PASSWORD() 関数は MySQL サーバー内の認証システムで使用されます。 その関数をあなたの独自アプリケーションでは使用すべきではありません。 そうしたければ、代わりに MD5()SHA1() を使用します。 Also see RFC-2195 for more information about handling passwords and authentication securely in your application.
ENCRYPT(str[,salt])
UNIX の crypt() システムコールで str を暗号化します。 salt は2文字の文字列です。 (MySQL バージョン 3.22.16 で, salt は2文字以上許されるようになり ました。)
mysql> SELECT ENCRYPT("hello");
        -> 'VxuFAJXVARROc'
システムで crypt() が利用できない場合は ENCRYPT() は常に NULL を返します。 少なくともいくつかのシステムでは、 ENCRYPT()str 文字中の最初の 8 文字以外は全て無視します。 これは crypt() システムコールの振る舞いによって決定づけられます。
ENCODE(str,pass_str)
パスワードとして pass_str を用いて str を暗号化します。結果 を復号化するには、DECODE()を使用します。 結果はバイナリ文字列で、長さは string と同じです。 フィールドにそれを保存したい場合は BLOB フィールド型を使用してください。
DECODE(crypt_str,pass_str)
暗号化された文字列 crypt_str をパスワードとして pass_str を 用いて復号化します。crypt_strENCODE() から返された文字列 であるべきです。
MD5(string)
文字列を MD5 128bit チェックサムした結果を返します。 値は 32 桁の 16進表示です。 例えばハッシュキーとして使用できるように:
mysql> SELECT MD5("testing");
        -> 'ae2b1fca515949e5d54fb22b8ed95575'
これは "RSA Data Security, Inc. MD5 Message-Digest Algorithm".
SHA1(string)
SHA(string)
Calculates an SHA1 160 bit checksum for the string, as described in RFC 3174 (Secure Hash Algorithm). The value is returned as a 40 digit hex number, or NULL in case the input argument was NULL. One of the possible uses for this function is as a hash key. You can also use it as cryptographically safe function for storing passwords.
mysql> SELECT SHA1("abc");
        -> 'a9993e364706816aba3e25717850c26c9cd0d89d'
SHA1() was added in version 4.0.2, and can be considered a cryptographically more secure equivalent of MD5(). SHA() is synonym for SHA1().
AES_ENCRYPT(string,key_string)
AES_DECRYPT(string,key_string)
These functions allow encryption/decryption of data using the official AES (Advanced Encryption Standard) algorithm, previously known as Rijndael. Encoding with 128 bit key length is used, but you can extend it up to 256 bit by patching the source. We chose 128 bits because it is much faster and it is usually secure enough. The input arguments may be any length. If either argument is NULL, the result of this function is also NULL. As AES is a block level algorithm, padding is used to encode uneven length strings and so the result string length may be calculated as 16*(trunc(string_length/16)+1). If AES_DECRYPT() detects invalid data or incorrect padding, it will return NULL. However, it is possible for AES_DECRYPT() to return a non-NULL value (possibly garbage) if the input data or the key was invalid. You can use the AES functions to store data in an encrypted form by modifying your queries:
INSERT INTO t VALUES (1,AES_ENCRYPT("text","password"));
You can get even more security by avoiding transferring the key over the connection for each query, which can be accomplished by storing it in a server side variable at connection time:
SELECT @password:="my password";
INSERT INTO t VALUES (1,AES_ENCRYPT("text",@password));
AES_ENCRYPT() and AES_DECRYPT() were added in version 4.0.2, and can be considered the most cryptographically secure encryption functions currently available in MySQL.
DES_ENCRYPT(string_to_encrypt [, (key_number | key_string) ] )
Encrypts the string with the given key using the Triple-DES algorithm. Note that this function only works if you have configured MySQL with SSL support. See section Using Secure Connections. The encryption key to use is chosen the following way:
Argument Description
Only one argument The first key from des-key-file is used.
key number The given key (0-9) from the des-key-file is used.
string The given key_string will be used to crypt string_to_encrypt.
The return string will be a binary string where the first character will be CHAR(128 | key_number). The 128 is added to make it easier to recognise an encrypted key. If you use a string key, key_number will be 127. On error, this function returns NULL. The string length for the result will be new_length= org_length + (8-(org_length % 8))+1. The des-key-file has the following format:
key_number des_key_string
key_number des_key_string
Each key_number must be a number in the range from 0 to 9. Lines in the file may be in any order. des_key_string is the string that will be used to encrypt the message. Between the number and the key there should be at least one space. The first key is the default key that will be used if you don't specify any key argument to DES_ENCRYPT() You can tell MySQL to read new key values from the key file with the FLUSH DES_KEY_FILE command. This requires the Reload_priv privilege. One benefit of having a set of default keys is that it gives applications a way to check for existence of encrypted column values, without giving the end user the right to decrypt those values.
mysql> SELECT customer_address FROM customer_table WHERE
       crypted_credit_card = DES_ENCRYPT("credit_card_number");
DES_DECRYPT(string_to_decrypt [, key_string])
Decrypts a string encrypted with DES_ENCRYPT(). Note that this function only works if you have configured MySQL with SSL support. See section Using Secure Connections. If no key_string argument is given, DES_DECRYPT() examines the first byte of the encrypted string to determine the DES key number that was used to encrypt the original string, then reads the key from the des-key-file to decrypt the message. For this to work the user must have the SUPER privilege. If you pass this function a key_string argument, that string is used as the key for decrypting the message. If the string_to_decrypt doesn't look like an encrypted string, MySQL will return the given string_to_decrypt. On error, this function returns NULL.
LAST_INSERT_ID([expr])
最後に AUTO_INCREMENT フィールドに挿入されて自動的に生成された値を返しま す。 See section mysql_insert_id().
mysql> SELECT LAST_INSERT_ID();
        -> 195
最後の作成された ID はそれぞれのコネクション毎にサーバーに維持されます。 これは他のクライアントからは変更できないでしょう。 もし他の非マジック値をもつ AUTO_INCREMENT フィールド (値が NULL でも 0 でもないということ) を更新しても、これは 変更されません。 一つの INSERT 文で同時に多くのレコードを挿入する場合、 LAST_INSERT_ID() は最初に挿入されたレコードの値を返します。この理由 は、他のサーバに対して同じ INSERT を簡単に再現できるようにするため です。 If expr is given as an argument to LAST_INSERT_ID(), then the value of the argument is returned by the function, is set as the next value to be returned by LAST_INSERT_ID() and used as the next auto_increment value. これは シーケンス番号のシミュレーションに使用できます: 最初にテーブルを作成:
mysql> CREATE TABLE sequence (id int not null);
mysql> INSERT INTO sequence VALUES (0);
そして以下のようにしてシーケンス番号を生成:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
LAST_INSERT_ID() の呼び出し無しでシーケンス番号を生成することが可能 ですが、この方法でこの関数を使用するユーティリティは、ID 値が最後に自動的 に生成された値としてサーバに管理されます。MySQL 内の通常の任意の AUTO_INCREMENT 値を読み込んで新しい ID を取り出すことができます。例 えば、LAST_INSERT_ID() (引数無し) は新しい ID を返します。C API 関 数 mysql_insert_id() もこの値を得るために使用できます。 Note that as mysql_insert_id() is only updated after INSERT and UPDATE statements, so you can't use the C API function to retrieve the value for LAST_INSERT_ID(expr) after executing other SQL statements like SELECT or SET.
FORMAT(X,D)
'#,###,###.##' のような形式(小数部 X 桁)で数値 D を整形 します。 もし D0 なら, 結果にはいかなる 小数点も小数部も含まれません。
mysql> SELECT FORMAT(12332.123456, 4);
        -> '12,332.1235'
mysql> SELECT FORMAT(12332.1,4);
        -> '12,332.1000'
mysql> SELECT FORMAT(12332.2,0);
        -> '12,332'
VERSION()
MySQL サーバのバージョンを返します:
mysql> SELECT VERSION();
        -> '3.23.13-log'
注意: バージョンが -log で終わる場合はロギングが有効であることを意 味します。
CONNECTION_ID()
接続の接続 ID (thread_id) を返します。すべての接続は接続自身の一意 な ID を持ちます:
mysql> SELECT CONNECTION_ID();
        -> 1
GET_LOCK(str,timeout)
timeout 秒のタイムアウトで、str と名付けられたロックの獲得を試み ます。ロックを獲得した場合は 1, タイムアウトの場合は 0, エラーの場 合(メ モリ不足やスレッドが mysqladmin kill で殺された場合など)は NULL が返ります。RELEASE_LOCK の実行、新しい GET_LOCK の実行、 スレッドの終了の場合に、ロックは解放されます。この関数はアプリケーション ロックやレコードロックのシミュレートのために使用できます。 これは、同じ名前のロックを行おうとする他のクライアントからのリクエストを ブロックします; 与えられた名前のロックに応じているクライアントは、 協調してロッキングを行うために、その文字列を使用できます:
mysql> SELECT GET_LOCK("lock1",10);
        -> 1
mysql> SELECT IS_FREE_LOCK("lock2");
        -> 1
mysql> SELECT GET_LOCK("lock2",10);
        -> 1
mysql> SELECT RELEASE_LOCK("lock2");
        -> 1
mysql> SELECT RELEASE_LOCK("lock1");
        -> NULL
2つ目の RELEASE_LOCK()NULL を返します。 なぜなら、 "lock1" は、2つ目の GET_LOCK() の呼び出し時点で、 自動的に解放されるからです。
RELEASE_LOCK(str)
GET_LOCK で獲得したロック str を解放します。ロックが解 放された場合は 1, このスレッドによってロックされていない場合は 0 (この場合、ロックは解放されません), strが存在しない場合は NULL が返ります。 もし、 GET_LOCK() をコールして得られなかった場合、 あるいは、既に解放されている場合は、ロックは存在しないでしょう。 The DO statement is convinient to use with RELEASE_LOCK(). See section DO Syntax.
IS_FREE_LOCK(str)
Checks if the lock named str is free to use (i.e., not locked). Returns 1 if the lock is free (no one is using the lock), 0 if the lock is in use, and NULL on errors (like incorrect arguments).
BENCHMARK(count,expr)
BENCHMARK() 関数は expr で与えられた文を count 回 繰り返し実行します。 これは MySQL のその文の処理がどれぐらい 速いのか知るのに使用されるでしょう。 結果は常に 0 です。 想定している使用は、 mysql クライアントです。 あるクエリの実行時間を知るための使用です:
mysql> SELECT BENCHMARK(1000000,ENCODE("hello","goodbye"));
+----------------------------------------------+
| BENCHMARK(1000000,ENCODE("hello","goodbye")) |
+----------------------------------------------+
|                                            0 |
+----------------------------------------------+
1 row in set (4.74 sec)
報告された時間は、クライアントでの経過時間です。 サーバー側の CPU 時間では ありません。BENCHMARK() を何回か実行して、サーバマシンの負荷の重さ を考慮して結果を解釈することを勧めます。
INET_NTOA(expr)
数値表現に対するネットワークアドレス(4 または 8 バイト) を返します:
mysql> SELECT INET_NTOA(3520061480);
       ->  "209.207.224.40"
INET_ATON(expr)
ネットワークアドレスに対する数値を表す整数を返します。アドレスは 4 または 8 バイトアドレスです:
mysql> SELECT INET_ATON("209.207.224.40");
       ->  3520061480
生成された数値は常にネットワークバイトオーダです; たとえば、上記の数値は 209*255^3 + 207*255^2 + 224*255 +40 として計算されます。
MASTER_POS_WAIT(log_name, log_pos)
マスターログの指定された位置にスレーブが到達するまで(すなわち、スレーブが 読み込んで全て更新しおわるまで)ブロックします。 マスター情報が初期化されていないか引数が違う場合、NULL が返ります。 スレーブが動作していない場合、ブロックし、スレーブが起動し、指定位置にくるまで待ちます。 スレーブが既に指定位置を通り過ぎていた場合、即時復帰します。 If timeout (new in 4.0.10) is specified, will give up waiting when timeout seconds have elapsed. timeout must be greater than 0; a zero or negative timeout means no timeout. The return value is the number of log events it had to wait to get to the specified position, or NULL in case of error, or -1 if the timeout has been exceeded. This command is useful for control of master-slave synchronisation, but was originally written to facilitate replication testing.
FOUND_ROWS()
Returns the number of rows that the last SELECT SQL_CALC_FOUND_ROWS ... command would have returned, if it had not been restricted with LIMIT.
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
       WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
The second SELECT will return a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause. Note that if you are using SELECT SQL_CALC_FOUND_ROWS ... MySQL has to calculate all rows in the result set. However, this is faster than if you would not use LIMIT, as the result set need not be sent to the client. SQL_CALC_FOUND_ROWS is available starting at MySQL version 4.0.0.

Functions for Use with GROUP BY Clauses

GROUP BY節を含まない文でグループ関数を使用すると 全てのレコードについてグループされたものとみなされます。

COUNT(expr)
Returns a count of the number of non-NULL values in the rows retrieved by a SELECT statement: SELECT文により選択されたレコードからNULLではないものの数を返します。
mysql> SELECT student.student_name,COUNT(*)
           FROM student,course
           WHERE student.student_id=course.student_id
           GROUP BY student_name;

COUNT(*)NULLを含むかどうかで選択されたレコードの数を返すだけです。 COUNT(*)は一つのテーブルから一つだけカラムが選択され、 尚且つWHERE節が使用されていない場合に最適化され、高速に動作します。 例えば以下のように使います。
mysql> SELECT COUNT(*) FROM student;
COUNT(DISTINCT expr,[expr...])
これはNULL値では無い値を持つデータの数を区別して返すことが出来ます。
mysql> SELECT COUNT(DISTINCT results) from student;
複数の選択されたデータ群からNULLを含まないデータの総数算出が必要な場合、 MySQLでは必要な選択リストを与えることによって得ることが出来ます。 一方でANSIのSQLではその選択一つ一つについて COUNT(DISTINCT ...) を使う必要があります。
AVG(expr)
exprで得られる値の平均値を返します。
mysql> SELECT student_name, AVG(test_score)
           FROM student
           GROUP BY student_name;
MIN(expr)
MAX(expr)
exprで得られる値の最大値、最小値を返します。 MIN()MAX()の引数は文字列を取ることもできます。 この際は文字列の値の大小を比較し、最大と最小を返します。section MySQL はどのようにインデックスを使用するか?.
mysql> SELECT student_name, MIN(test_score), MAX(test_score)
    ->        FROM student
    ->        GROUP BY student_name;
In MIN(), MAX() and other aggregate functions, MySQL currently compares ENUM and SET columns by their string value rather than by the string's relative position in the set. This will be rectified.
SUM(expr)
exprで得られる値の総計を返します。 もしも得られるレコードが見つからない場合はNULLが返ってきます。
VARIANCE(expr)
Returns the standard variance of expr. This is an extension to ANSI SQL (available only in version 4.1 or later).
STD(expr)
STDDEV(expr)
exprで得られる値の標準偏差を返します。 これはANSI SQLの格調になっています。 関数としてのSTDDEV()の形はOracleのものと互換性があります。
BIT_OR(expr)
exprで得られる値のビット和(OR)を返します。 計算は64-bit(BIGINT)の精度で行われます。
BIT_AND(expr)
exprで得られる値のビット積(AND)を返します。 計算は64-bit(BIGINT)の精度で行われます。

MySQLのGROUP BYは拡張された使い方が可能です。 SELECTで使用したフィールド名や計算式をGROUP BYには使用しない、 という使い方が可能です。 このことはグループにはどんな値も使用可能ということを表しています。 データの並べ替えやグループ分けに適さない要素を排除することによって より良好なパフォーマンスを得ることが出来ます。 例えば、次のようなクエリでcustomer.nameについてのグループ分けをする必要はありません。

mysql> SELECT order.custid,customer.name,MAX(payments)
    ->        FROM order,customer
    ->        WHERE order.custid = customer.custid
    ->        GROUP BY order.custid;

ANSI SQLではcustomer.nameGROUP BYのところに追加する必要があります。 MySQLではANSIモードで動かしていない限り余計な記述の必要はありません。

GROUP BYで省略するフィールドはグループ内でユニークでなくてはいけません。 もしそうでない場合は結果は予想もしないようなものになるでしょう。

たとえユニークでは無くても特定のフィールドの値を得るために MIN()MAX()を使用できるケースもあります。 次の例はsortフィールド中の最小値を持つレコードから 特定のcolumnの値を取り出します。

SUBSTR(MIN(CONCAT(RPAD(sort,6,' '),column)),7)

See section The Rows Holding the Group-wise Maximum of a Certain Field.

MySQLの3.22以前のバージョンをお使いであるか、ANSI SQLに沿っての使用をされる場合は GROUP BYORDER BY内に選択表現を記述してはいけません。 この制限を守った上で作業を進めるにはエイリアスを使用します。

mysql> SELECT id,FLOOR(value/100) AS val FROM tbl_name
    ->        GROUP BY id,val ORDER BY val;

MySQLのバージョン3.23では次のようにも記述できます。

mysql> SELECT id,FLOOR(value/100) FROM tbl_name ORDER BY RAND();

Data Manipulation: SELECT, INSERT, UPDATE, DELETE

SELECT 構文

SELECT [STRAIGHT_JOIN]
       [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
       [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY]
       [DISTINCT | DISTINCTROW | ALL]
    select_expression,...
    [INTO {OUTFILE | DUMPFILE} 'file_name' export_options]
    [FROM table_references
      [WHERE where_definition]
      [GROUP BY {unsigned_integer | col_name | formula} [ASC | DESC], ...]
      [HAVING where_definition]
      [ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC] ,...]
      [LIMIT [offset,] rows | rows OFFSET offset]
      [PROCEDURE procedure_name(argument_list)]
      [FOR UPDATE | LOCK IN SHARE MODE]]

SELECTは通常、1つまたは1つ以上のテーブルからレコードを検索して抽出 するのに使用されます。 select_expression は取り出したいフィールドを示します。 SELECTはまた、テーブルの参照なしに計算によって求められたレコードを 取り出すために使用されます。例:

mysql> SELECT 1 + 1;
         -> 2

全てのキーワードの使用は、上記に示すような順序で正確に与えられる必要があります。 例えば、HAVING節は必ずGROUP BY節の後、ORDER BY節の前でなければなりません。

JOIN 構文

MySQLは、以下に示すSELECTステートメントにおけるJOIN構文をサポートします:

table_reference, table_reference
table_reference [CROSS] JOIN table_reference
table_reference INNER JOIN table_reference join_condition
table_reference STRAIGHT_JOIN table_reference
table_reference LEFT [OUTER] JOIN table_reference join_condition
table_reference LEFT [OUTER] JOIN table_reference
table_reference NATURAL [LEFT [OUTER]] JOIN table_reference
{ OJ table_reference LEFT OUTER JOIN table_reference ON conditional_expr }
table_reference RIGHT [OUTER] JOIN table_reference join_condition
table_reference RIGHT [OUTER] JOIN table_reference
table_reference NATURAL [RIGHT [OUTER]] JOIN table_reference

Where table_reference is defined as:

table_name [[AS] alias] [[USE INDEX (key_list)] | [IGNORE INDEX (key_list)] | [FORCE INDEX (key_list)]]

and join_condition is defined as:

ON conditional_expr |
USING (column_list)

You should generally not have any conditions in the ON part that are used to restrict which rows you have in the result set (there are exceptions to this rule). If you want to restrict which rows should be in the result, you have to do this in the WHERE clause.

注意: 3.23.17 より前のバージョンでは、INNER JOINjoin_condition を取りません!

上に示す最後のLEFT OUTER JOIN構文は、ODBCとの互換性のためだけに存在します:

例:

mysql> SELECT * FROM table1,table2 WHERE table1.id=table2.id;
mysql> SELECT * FROM table1 LEFT JOIN table2 ON table1.id=table2.id;
mysql> SELECT * FROM table1 LEFT JOIN table2 USING (id);
mysql> SELECT * FROM table1 LEFT JOIN table2 ON table1.id=table2.id
    ->          LEFT JOIN table3 ON table2.id=table3.id;
mysql> SELECT * FROM table1 USE INDEX (key1,key2)
    ->          WHERE key1=1 AND key2=2 AND key3=3;
mysql> SELECT * FROM table1 IGNORE INDEX (key3)
    ->          WHERE key1=1 AND key2=2 AND key3=3;

See section MySQL はどのように LEFT JOINRIGHT JOIN を最適化するか?.

UNION Syntax

SELECT ...
UNION [ALL]
SELECT ...
  [UNION
   SELECT ...]

UNION is implemented in MySQL 4.0.0.

UNION is used to combine the result from many SELECT statements into one result set.

The columns listed in the select_expression portion of the SELECT should have the same type. The column names used in the first SELECT query will be used as the column names for the results returned.

The SELECT commands are normal select commands, but with the following restrictions:

If you don't use the keyword ALL for the UNION, all returned rows will be unique, as if you had done a DISTINCT for the total result set. If you specify ALL, then you will get all matching rows from all the used SELECT statements.

If you want to use an ORDER BY for the total UNION result, you should use parentheses:

(SELECT a FROM table_name WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM table_name WHERE a=11 AND B=2 ORDER BY a LIMIT 10)
ORDER BY a;

HANDLER Syntax

HANDLER tbl_name OPEN [ AS alias ]
HANDLER tbl_name READ index_name { = | >= | <= | < } (value1,value2,...)
    [ WHERE ... ] [LIMIT ... ]
HANDLER tbl_name READ index_name { FIRST | NEXT | PREV | LAST }
    [ WHERE ... ] [LIMIT ... ]
HANDLER tbl_name READ { FIRST | NEXT }
    [ WHERE ... ] [LIMIT ... ]
HANDLER tbl_name CLOSE

The HANDLER statement provides direct access to the MyISAM table storage engine interface.

The first form of HANDLER statement opens a table, making it accessible via subsequent HANDLER ... READ statements. This table object is not shared by other threads and will not be closed until the thread calls HANDLER tbl_name CLOSE or the thread dies.

The second form fetches one row (or more, specified by LIMIT clause) where the index specified complies to the condition and WHERE condition is met. If the index consists of several parts (spans over several columns) the values are specified in comma-separated list, providing values only for few first columns is possible.

The third form fetches one row (or more, specified by LIMIT clause) from the table in index order, matching WHERE condition.

The fourth form (without index specification) fetches one row (or more, specified by LIMIT clause) from the table in natural row order (as stored in datafile) matching WHERE condition. It is faster than HANDLER tbl_name READ index_name when a full table scan is desired.

HANDLER ... CLOSE closes a table that was opened with HANDLER ... OPEN.

HANDLER is a somewhat low-level statement. For example, it does not provide consistency. That is, HANDLER ... OPEN does NOT take a snapshot of the table, and does NOT lock the table. This means that after a HANDLER ... OPEN is issued, table data can be modified (by this or any other thread) and these modifications may appear only partially in HANDLER ... NEXT or HANDLER ... PREV scans.

The reasons to use this interface instead of normal SQL are:

INSERT 構文

    INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        VALUES ((expression | DEFAULT),...),(...),...
        [ ON DUPLICATE KEY UPDATE col_name=expression, ... ]
or  INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
or  INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name
        SET col_name=(expression | DEFAULT), ...
        [ ON DUPLICATE KEY UPDATE col_name=expression, ... ]

INSERTは、既存のテーブルに新しいレコードを挿入します。 INSERT ... VALUES書式は、値の明示指定を基本としてレコードを挿入します。 INSERT ... SELECT書式は、他の表(複数可)から抽出したレコードを挿入します。 複数の値リストを用いるINSERT ... VALUES書式は、 MySQL バージョン 3.22.5以降でサポートされています。 col_name=expression構文は、 MySQL バージョン 3.22.10以降でサポートされています。

tbl_nameは、レコードを挿入するテーブルです。フィールド名リストは、 後続の値定義ステートメントのフィールドを指し示します:

多重の値リストを持つ INSERT ... SELECT ... 又は INSERT ... VALUES() ステートメントを使用する場合、クエリーに関する情報を得るために C API関数 mysql_info() を使用することができます。 その情報の書式は以下に示す文字列のようになります:

Records: 100 Duplicates: 0 Warnings: 0

Duplicatesは、既に存在するユニークインデックスの値と重複することにより、 挿入できなかったレコード数を表します。 Warningsは、挿入されたフィールドが何らかの疑わしい値であったという 数を表します。警告は、次のような条件の下で発生します:

INSERT ... SELECT 構文

INSERT [LOW_PRIORITY] [IGNORE] [INTO] tbl_name [(column list)] SELECT ...

With INSERT ... SELECT statement you can quickly insert many rows into a table from one or many tables.

INSERT INTO tblTemp2 (fldID) SELECT tblTemp1.fldOrder_ID FROM tblTemp1 WHERE
tblTemp1.fldOrder_ID > 100;

The following conditions hold for an INSERT ... SELECT statement:

You can of course also use REPLACE instead of INSERT to overwrite old rows.

INSERT DELAYED 構文

INSERT DELAYED ...

INSERT 構文の DELAYED オプションは MySQL 独自の オプションで、これは INSERT が完全に終了することを待てない クライアントを持つ場合に、とても役立ちます。 これは、ロギングのために MySQL を使用する時の一般的な問題で、完了 に長い時間がかかる SELECT ステートメントも定期的に実行できます。 DELAYED は MySQL 3.22.15 で導入されました。 これは ANSI SQL92 に対する MySQL 拡張です。

INSERT DELAYED only works with ISAM and MyISAM tables. Note that as MyISAM tables supports concurrent SELECT and INSERT, if there is no free blocks in the middle of the datafile, you very seldom need to use INSERT DELAYED with MyISAM. See section MyISAM テーブル (3.23.0以上).

INSERT DELAYED を使用する時、クライアントは一度 ok となり、テーブル が他のスレッドで使用中でない時にレコードが挿入されます。

INSERT DELAYED を使用して得られるほかの利益は、 多くのクライアントからの insert が同時に束ねられ、一つのブロックで 書かれることです。 これは多くの別々の insert を実行するより とても速くなります。

現在、キューイングされたレコードは、それらがテーブルに代入されるまで メモリーに保持されているだけです。 これは、もし mysqld を 強引な方法 (kill -9) でキルしたり、 mysqld が予期せず 死んだ場合、キューイングされているレコードはディスクに書かれず失われます!

DELAYED オプションを INSERTREPLACE で使用する場合、 以下のことがおきます。 ここで ``スレッド'' とは INSERT DELAYED コマンドを受けたスレッドをさし、 ``ハンドラー'' とは特定のテーブルのための全ての INSERT DELAYED 構文を操作するスレッドを指します。

注意: INSERT DELAYED は、テーブルが使用中でない場合、通常の INSERT よりも遅くなります。INSERT DELAYED を使用する各テーブルにつ いて別のスレッドを操作するサーバの、追加のオーバーヘッドもあります。これは、 確実にそれを必要とする時にだけ INSERT DELAYED を使用すべきことを意 味します!

UPDATE 構文

UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
    SET col_name1=expr1 [, col_name2=expr2 ...]
    [WHERE where_definition]
    [ORDER BY ...]
    [LIMIT rows]

or

UPDATE [LOW_PRIORITY] [IGNORE] tbl_name [, tbl_name ...]
    SET col_name1=expr1 [, col_name2=expr2 ...]
    [WHERE where_definition]

UPDATE はテーブルに存在するレコードのフィールドを、新しい値に更新します。 SET 節はどのフィールドをどういった値にすべきかを示します。 WHERE 節が与えられた場合、更新すべきレコードを特定することになります。 それ以外は、全てのレコードを更新します。 ORDER BY 節が指定された場合、レコードは指定された順に更新されます。

LOW_PRIORITY キーワードを指定した場合、UPDATE の実行は、 テーブルを読んでいるクライアントがなくなるまで、遅らされます。

IGNORE キーワードを指定した場合は、update 文は、 update 中に二重キーのエラーを得たとしても、異常終了しません。 衝突を引き起こすレコードは更新されません。

表記中の tbl_name からのフィールドをアクセスすると、UPDATE は現在のフィールド値を使用します。例えば、次のステートメントは age フィールドにその現在値より1大きい値を設定します:

mysql> UPDATE persondata SET age=age+1;

UPDATE は左から右に評価されます。例えば、以下の文は age フィールド を 2倍にし、そのあと1増やします:

mysql> UPDATE persondata SET age=age*2, age=age+1;

もしフィールドに現在もっている値を指定した場合、MySQL はそれを通知し、 値は更新しません。

UPDATE は変更されたレコード数を返します。 MySQL バージョン 3.22 以上では、C API 関数 mysql_info() が マッチし更新されたレコード数を返します。また UPDATE 中に起きた ワーニングの数も返します。

MySQL バージョン 3.23 では、 LIMIT # で指定した数だけレコードを 変更できます。

Starting with MySQL Version 4.0.4, you can also perform UPDATE operations that cover multiple tables:

UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;

Note: you can not use ORDER BY or LIMIT with multi-table UPDATE.

DELETE 構文

DELETE [LOW_PRIORITY] [QUICK] FROM table_name
       [WHERE where_definition]
       [ORDER BY ...]
       [LIMIT rows]

or

DELETE [LOW_PRIORITY] [QUICK] table_name[.*] [, table_name[.*] ...]
       FROM table-references
       [WHERE where_definition]

or

DELETE [LOW_PRIORITY] [QUICK]
       FROM table_name[.*] [, table_name[.*] ...]
       USING table-references
       [WHERE where_definition]

DELETEは、tbl_nameより、where_definitionにて与えられた条件 を満たすレコードを削除し、削除されたレコード数を返します。

WHERE節を指定することなしにDELETEを発行した場合、全てのレコードが 削除されます。 もし AUTOCOMMIT モードでこの操作を実行するならば、これは TRUNCATE と同様に動作します。See section TRUNCATE 構文. MySQL 3.23では、DELETE は削除したレコード数を 0 で返します。

もし全てのレコードを削除している時に、いくつのレコードが消され、いくつのレコード が スピードを犠牲にしているのか、本当に知りたいならば、 DELETE 構文を以下のように使用します:

mysql> DELETE FROM tbl_name WHERE 1>0;

これは DELETE FROM tbl_nameWHERE 節なしで行うよりも、 とても遅いです。なぜなら一度で消そうとするからです。

キーワードLOW_PRIORITYを指定した場合、そのテーブルを読んでいるクライアン トがいなくなるまでDELETEの実行は遅らせられます。

削除されたレコードはリンクリストで維持され、次のINSERT操作は、古いレコー ド位置を再利用します。 ファイルをより小さくしたい場合は、OPTIMIZE TABLEステートメントかテーブル の再編成のためにmyisamchkユティリティを使用してください。 OPTIMIZE TABLEの方が簡単ですが、myisamchkの方が早く動作します。 See section OPTIMIZE TABLE 構文.

If you specify the word QUICK then the storage engine will not merge index leaves during delete, which may speed up certain kind of deletes.

The first multi-table delete format is supported starting from MySQL 4.0.0. The second multi-table delete format is supported starting from MySQL 4.0.2.

The idea is that only matching rows from the tables listed before the FROM or before the USING clause are deleted. The effect is that you can delete rows from many tables at the same time and also have additional tables that are used for searching.

The .* after the table names is there just to be compatible with Access:

DELETE t1,t2 FROM t1,t2,t3 WHERE t1.id=t2.id AND t2.id=t3.id

or

DELETE FROM t1,t2 USING t1,t2,t3 WHERE t1.id=t2.id AND t2.id=t3.id

In the above case we delete matching rows just from tables t1 and t2.

If an ORDER BY clause is used (available from MySQL 4.0), the rows will be deleted in that order. This is really only useful in conjunction with LIMIT. For example:

DELETE FROM somelog
WHERE user = 'jcole'
ORDER BY timestamp
LIMIT 1

This will delete the oldest entry (by timestamp) where the row matches the WHERE clause.

MySQL-特化 DELETELIMIT rows オプションは サーバーに消す最大のレコード数をつげます。これは DELETE コマンドが あまりに多くの時間を取らないために使用されます。 LIMIT 値よりも affected row の数が少なくなるまで、 単純に DELETE コマンドを繰り返すだけです。

From MySQL 4.0, you can specify multiple tables in the DELETE statement to delete rows from one table depending on a particular condition in multiple tables. However, you can not use ORDER BY or LIMIT in a multi-table DELETE.

TRUNCATE 構文

TRUNCATE TABLE table_name

3.23 では、COMMIT ; DELETE FROM table_name と同じことです。 See section DELETE 構文.

TRUNCATE TABLE differs from DELETE FROM ... in the following ways:

TRUNCATE は ORACLE SQL 拡張です。

REPLACE 構文

    REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        VALUES (expression,...),(...),...
or  REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
or  REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name
        SET col_name=expression, col_name=expression,...

REPLACEは、テーブル中にある古いレコードの UNIQUE インデックスか PRIMARY KEY 上にある値が、新しいレコード と同じ場合に、新しいレコードを挿入する前に 古いレコードを削除するということを除けば、INSERTと全く同じように 動作します。 See section INSERT 構文.

In other words, you can't access the values of the old row from a REPLACE statement. In some old MySQL versions it appeared that you could do this, but that was a bug that has been corrected.

To be able to use REPLACE you must have INSERT and DELETE privileges for the table.

When you use a REPLACE command, mysql_affected_rows() will return 2 if the new row replaced an old row. This is because one row was inserted after the duplicate was deleted.

This fact makes it easy to determine whether REPLACE added or replaced a row: check whether the affected-rows value is 1 (added) or 2 (replaced).

Note that unless you use a UNIQUE index or PRIMARY KEY, using a REPLACE command makes no sense, since it would just do an INSERT.

LOAD DATA INFILE 構文

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name.txt'
    [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [FIELDS
        [TERMINATED BY '\t']
        [[OPTIONALLY] ENCLOSED BY '']
        [ESCAPED BY '\\' ]
    ]
    [LINES TERMINATED BY '\n']
    [IGNORE number LINES]
    [(col_name,...)]

LOAD DATA INFILEステートメントは、テキストファイルからテーブルへと、 レコードを高速に読み込みます。 LOCAL キーワードが指定されれば、ファイルは クライアント・ホストから読み込まれます。 LOCALが指定されなければ、ファイルはサーバに位置する必要があります (LOCALは、MySQL バージョン 3.22.6以降で利用できます)。

セキュリティ上の理由から、サーバからテキストファイルを読み出す時は、 ファイルがデータベースディレクトリに存在するか、 全てに読み込み権限がある必要があります。 また、サーバファイルで LOAD DATA INFILE を使用するには、 データベースの FILE 権限も持たなければなりません。 See section MySQL が提供する権限.

In MySQL 3.23.49 and MySQL 4.0.2 LOCAL will only work if you have not started mysqld with --local-infile=0 or if you have not enabled your client to support LOCAL. See section Security issues with LOAD DATA LOCAL.

もし LOW_PRIORITY を指定した場合、LOAD DATA 構文は そのテーブルから他のクライアントが読み込みを行っている間、 遅らされます。

If you specify the keyword CONCURRENT with a MyISAM table, then other threads can retrieve data from the table while LOAD DATA is executing. Using this option will of course affect the performance of LOAD DATA a bit even if no other thread is using the table at the same time.

LOCAL 使用をすると、クライアント・ホストからサーバ・ホストへ ファイルの内容が転送される分、多少遅くなるでしょう。 いうならば、ローカルのファイルを読み込むのに、 FILE 権限は必要ないということです。

If you are using MySQL before Version 3.23.24 you can't read from a FIFO with LOAD DATA INFILE. If you need to read from a FIFO (for example the output from gunzip), use LOAD DATA LOCAL INFILE instead.

mysqlimportユティリティは、データファイルの読み込みに使用することができま す。; これは、サーバにLOAD DATA INFILEコマンドを送信することによって処理 を実現しています。 --localオプションは、mysqlimportに、クライアント・ホストからデータ ファイルを読み込ませます。 クライアントとサーバが圧縮プロトコルをサポートしていれば、低速なネットワークでよ り良いパフォーマンスを得るために、--compressオプションを指定することがで きます。

サーバ・ホストにファイルを置く場合、サーバは、以下のルールを使用します:

これらのルールは、ファイルが `myfile.txt' のように与えられれば データベースディレクトリからファイルが読み出され、 `./myfile.txt' のように与えられれば、現在選択しているデータベースのデータデ ィレクトリから ファイルが読み出されるという意味であることに注意して下さい。

例えば、以下の LOAD DATA 文は、`data.txt' ファイルを db1 データベースディレクトリから読みます。 なぜなら、db1 は 現在選択されているデータベースだからです。 たとえ、db2 データベース のテーブルに、ファイルから読み込んだデータを挿入するとしても。:

以下に示すような構文では、ファイルは db1 データベースディレクトリ から読まれます。db2 ではありません:

mysql> USE db1;
mysql> LOAD DATA INFILE "data.txt" INTO TABLE db2.my_table;

REPLACEIGNORE キーワードは、すでに存在するユニークキーに 重複しているレコードの入力に対する制御です。 REPLACE 指定の場合、同じユニークキーを持つ既存のレコードは新しいレコード で置き換えられます。 IGNORE 指定の場合、既存のレコードのユニークキーと重複するキーをもつ新しい レコードは飛ばされます。 もし、どちらも指定しなかった場合、重複したキーが 見つかった場合エラーが発生し、テキストファイルは無視されます。

LOCAL キーワードを使用してデータをローカルからロードする場合、 サーバーは操作の途中で転送をとめる方法を知りません。 それでデフォルトの動作としては IGNORE が指定されたのと 同じになります。

If you use LOAD DATA INFILE on an empty MyISAM table, all non-unique indexes are created in a separate batch (like in REPAIR). This normally makes LOAD DATA INFILE much faster when you have many indexes.

LOAD DATA INFILEは、SELECT ... INTO OUTFILEの逆です。 See section SELECT 構文. データベースからファイルへデータを書き込むには、SELECT ... INTO OUTFILEを 使用します。 ファイルからデータベースに読み戻すには、LOAD DATA INFILEを使用します。 FIELDSLINES節の構文は両方のコマンドとも同じです。 どちらの節もオプションですが、両方を指定する場合は、FIELDSは、LINES より先に指定しなければなりません。

FIELDS節を指定した場合、その段落(TERMINATED BY[OPTIONALLY] ENCLOSED BY及びESCAPED BY)は、少なくとも1つを指定しなければならないこ とを除いて、それらもまたオプションとなります。

FIELDS節を指定しなかった場合、初期値は以下のように記述したのと等価となり ます:

FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'

LINES節を指定しなかった場合、初期値は以下のように記述したのと等価となりま す:

LINES TERMINATED BY '\n'

言い換えると、LOAD DATA INFILE の初期値は、出力へ書き込む際に以下のように 振舞います:

逆に、LOAD DATA INFILEの初期値は、入力を読み込む際に以下のように振舞いま す:

FIELDS ESCAPED BY '\\'と書いた場合、単一のバックスラッシュとして読み出さ れる値とするために、2つのバックスラッシュを指定しなければならないことに注意して 下さい。

IGNORE number LINES オプションはファイルの先頭にあるレコードを無視するの に使用されます:

mysql> LOAD DATA INFILE "/tmp/file_name" INTO TABLE test IGNORE 1 LINES;

データベースからファイルへデータを書き、それから後でそのファイルからデータベース へデータを読み戻すために、SELECT ... INTO OUTFILEと対にLOAD DATA IN FILEを使う場合、双方のフィールドとレコードの取扱いに関するオプションは、一致し なければなりません。さもなければ、LOAD DATA INFILEは適切にファイルを処理 しないでしょう。 フィールドをコンマで区切ってファイルへ書き出すために、SELECT ... INTO OUT FILEを使用するとすれば:

mysql> SELECT * INTO OUTFILE 'data.txt'
    ->          FIELDS TERMINATED BY ','
    ->          FROM ...;

コンマ区切りファイルから読み戻すため、正しいステートメントはこうなるでしょう:

mysql> LOAD DATA INFILE 'data.txt' INTO TABLE table2
    ->           FIELDS TERMINATED BY ',';

その代わりとして次に示すようなステートメントでファイルを読み込もうとしても、正し く動作しないでしょう。なぜなら、これは、LOAD DATA INFILEに対してフィール ドの間にタブを探すよう指示するからです:

mysql> LOAD DATA INFILE 'data.txt' INTO TABLE table2
    ->           FIELDS TERMINATED BY '\t';

おそらく、それぞれの入力行は単一のフィールドとして処理されるでしょう。

LOAD DATA INFILEは外部ソースからもファイルを読み出すことができます。 例えば、dBASEフォーマットのファイルは、フィールドをコンマで区切られ、ダブルクォ ーテーションで囲まれています。 レコードが改行文字で区切られているとしたら、次に示すフィールド及びレコードの取扱 オプションを指定したコマンドが、このようなファイルを読み込むのに使用できます。

mysql> LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
    ->           FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ->           LINES TERMINATED BY '\n';

いくつかのフィールド及びレコードの取扱オプションに、空文字列('')を 指定することがあります。空でないなら、 FIELDS [OPTIONALLY] ENCLOSED BYFIELDS ESCAPED BYの値は 単一の文字でなければなりません。 FIELDS TERMINATED BYLINES TERMINATED BYは2つ以上の文字となるで しょう。

例えば、リターン文字と改行文字のペアで区切られたレコードを書き込んだり、 このようなレコードを含んだファイルを読み込んだりするには、 LINES TERMINATED BY '\r\n'節を指定します。

CREATE TABLE jokes (a int not null auto_increment primary key, joke text
not null);
LOAD DATA INFILE "/tmp/jokes.txt" INTO TABLE jokes FIELDS TERMINATED BY ""
LINES TERMINATED BY "\n%%\n" (joke);

FIELDS [OPTIONALLY] ENCLOSED BYは、フィールドの引用符を制御します。出力の 際(SELECT ... INTO OUTFILE)、OPTIONALLY語を省いたなら、全てのフィ ールドはENCLOSED BY文字で囲まれます。このような出力(フィールド区切りにコ ンマを使用)の例を次に示します:

"1","a string","100.20"
"2","a string containing a , comma","102.20"
"3","a string containing a \" quote","102.20"
"4","a string containing a \", quote and comma","102.20"

OPTIONALLYを指定すれば、ENCLOSED BY文字は、 CHARフィールド とVARCHARフィールドのみ囲むのに使用されます:

1,"a string",100.20
2,"a string containing a , comma",102.20
3,"a string containing a \" quote",102.20
4,"a string containing a \", quote and comma",102.20

フィールド値の中におけるENCLOSED BY文字の出現は、ESCAPED BY文字を その前に置くことによりエスケープされることに注意して下さい。ESCAPED BY値 に空を指定すると、LOAD DATA INFILEにより正しく読み込めない出力を生成する でしょう。例えば、このようにエスケープ文字を空にした場合、以下に示すような出力と なります。4行目の2つ目のフィールドに、(誤って)フィールドを区切るかのようなクォ ートに続くコンマを含んでいることに注視して下さい:

1,"a string",100.20
2,"a string containing a , comma",102.20
3,"a string containing a " quote",102.20
4,"a string containing a ", quote and comma",102.20

入力において、ENCLOSED BY文字が指定されており、それがフィールド値の両端に 現れた場合、その文字は取り去られます。(これは、OPTIONALLYが指定されたかど うかに拘らず、当てはまります;OPTIONALLYは入力解析には効果がありません。) ESCAPED BY文字を前置きされたENCLOSED BY文字の出現は、現在のフィー ルド値の一部として処理されます。具体的には、あるフィールドがそれ自身、たEN CLOSED BY文字で始まっている場合、フィールドらの内部で発生する2重のENCLOS ED BY文字は、単一のENCLOSED BY文字として処理されます。 例えば、ENCLOSED BY '"'が指定されると、引用符は以下のように操作されます:

"The ""BIG"" boss"  -> The "BIG" boss
The "BIG" boss      -> The "BIG" boss
The ""BIG"" boss    -> The ""BIG"" boss

FIELDS ESCAPED BYは、特殊文字をどのように書き込んだり読み込んだりするかを 制御します。 FIELDS ESCAPED BY文字が空でない場合、出力において次のような文字(文字列) のプリフィックスに使用されます:

FIELDS ESCAPED BY文字が空であれば、どの文字もエスケープされません。 特に、フィールド値が上に示した文字を含んでいるならば、エスケープ文字に空を指定す るのはあまり良い考えとは言えないでしょう。

入力において、FIELDS ESCAPED BY文字が空でない場合、この文字の出現は取り去 られ、後続の文字はフィールド値の一部としてそのまま受け取られます。 例外は、エスケープされた`0'`N'です (例えば、エスケープ文字が`\'である時の\0\N)。 これらのシーケンスは、ASCII 0('ゼロ値'バイト) 、NULLとして処理されます。 code{NULL}操作の規則は下を参照して下さい。

`\'-escape syntaxに関するこれ以外の情報は、section 文字列と数値をどのように書くか?参照。

フィールドとレコード操作オプションが確実に相互作用する事例:

FIELDSLINESオプションによるNULL値の多様な取扱い:

LOAD DATA INFILEでサポートされないケース:

次の例は、persondataテーブルの全てのフィールドを読み込みます:

mysql> LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata;

フィールドリストが指定されていませんから、LOAD DATA INFILEは、入力レコー ドがテーブルのそれぞれのフィールドを含むものと想定します。 FIELDSLINESの初期値が使用されます。

テーブルの一部のフィールドのみ読み込みたい場合、フィールドリストを指定します:

mysql> LOAD DATA INFILE 'persondata.txt'
    ->           INTO TABLE persondata (col1,col2,...);

テーブル内のフィールド順と入力ファイルのフィールド順が異なる場合にも、My SQLにテーブルのフィールドと入力フィールドの対応を教えるために、フィールドリスト を指定しなければなりません。

入力レコードのフィールド数の方が少ない場合、入力フィールド値が与えられないフィー ルドは、初期値が設定されます。 初期値の割当てについては、section CREATE TABLE 構文. で述べられています。

空のフィールド値は変換されます:

Note that these are the same values that result if you assign an empty string explicitly to a string, numeric, or date or time type explicitly in an INSERT or UPDATE statement.

TIMESTAMP フィールドは、フィールド値に NULL 値が指定されていた場合 もしくは、 フィールドリストが指定されている時に TIMESTAMP フィールドがそのリストから 除外されていた場合 (最初のTIMESTAMPフィールドのみ)、現在時刻が設定されるだけです。

入力レコードのフィールド数の方が多い場合、余分なフィールドは無視され、警告の数が 増やされます。

LOAD DATA INFILEは全ての入力を文字列と文字列とみなすことから、INSER TステートメントでできるようなENUMフィールドやSETフィールドへの数 値の指定はできません。全てのENUM及びSET値は文字列として与えられな ければいけません!

LOAD DATA INFILEクエリの終了時、クエリの情報を得るためにC API関数my sql_info()を使用することができます。情報の書式は以下に示すようなものです:

Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

LOAD DATA INFILE が、入力レコードのフィールド数の過不足があった時にも 警告を引き起こす事を除けば、INSERT ステートメント (See section INSERT 構文. ) により値が挿入される時に 警告が発生するのと同じ状況下で、警告が発生します。 警告はどこにも保存されません; 警告の数は全てうまくいった場合にだけ 使用できます。 もし警告を知りたい、その警告の理由を知りたいのなら、 一つ方法があります。 SELECT ... INTO OUTFILE を使用して 他のファイルに落とし、オリジナルのファイルと比べます。

パイプからの読み込みで LOAD DATA の必要があれば、次のトリッ クを使用できます:

mkfifo /mysql/db/x/x
chmod 666 /mysql/db/x/x
cat < /dev/tcp/10.1.1.12/4711 > /nt/mysql/db/x/x
mysql -e "LOAD DATA INFILE 'x' INTO TABLE x" x

If you are using a version of MySQL older than 3.23.25 you can only do the above with LOAD DATA LOCAL INFILE.

INSERTと比較したLOAD DATA INFILEの効率やLOAD DATA INFILEの 高速化についてのより詳しい情報は、See section INSERT クエリの速度を参照のこと。

DO Syntax

DO expression, [expression, ...]

Execute the expression but don't return any results. This is a shorthand of SELECT expression, expression, but has the advantage that it's slightly faster when you don't care about the result.

This is mainly useful with functions that has side effects, like RELEASE_LOCK.

Data Definition: CREATE, DROP, ALTER

CREATE DATABASE 構文

CREATE DATABASE [IF NOT EXISTS] db_name

CREATE DATABASE は与えられた名前のデータベースを作ります。データベースの 名前として許される命名規則は、section データベース名、テーブル名、インデックス名、フィールド名、エイリアス名に依ります。 もし、データベースがすでに存在しているにもかかわらず IF NOT EXISTS を 指定していなかったら、エラーが発生します。

MySQLにおけるデータベースは、データベース内のテーブルに相当するファイル を含むディレクトリとして実装されます。初期作成後はデータベース内にテーブルは存在 せず、CREATE DATABASEステートメントは、MySQLデータディレクトリ下 にディレクトリを作成するだけです。

mysqladminでもデータベースを作成することができます。 See section MySQL Client-Side Scripts and Utilities.

DROP DATABASE 構文

DROP DATABASE [IF EXISTS] db_name

DROP DATABASEは、データベース内の全てのテーブルと共にデータベースを破棄し ます。 シンボリックリンクされた DROP DATABASE を行なうと、リンクとオリジナ ルデータベースの両方が削除されます。 このコマンドの使用には万全の注意を払って下さい!

DROP DATABASEは、データベースディレクトリから削除されたファイルの数を返し ます。それぞれのテーブルは`.MYD'ファイル/`.MYI'ファイル/`.frm' ファイルに相当することから、通常この値はテーブルの3倍の数となります。

DROP DATABASE コマンドは与えられたデータベースディレクトリから、次 の拡張子のすべてのファイルを削除します:

Ext Ext Ext Ext
.BAK .DAT .HSH .ISD
.ISM .ISM .MRG .MYD
.MYI .db .frm

2桁の数値のすべてのサブディレクトリ(RAID ディレクトリ)も削除されま す。

MySQL 3.22以降では、データベースが存在しないことに起因するエラーを防ぐ ために、キーワード IF EXISTS を使用することができます。

mysqladminでもデータベースを破棄することができます。 See section MySQL Client-Side Scripts and Utilities.

CREATE TABLE 構文

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]

or

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name LIKE old_table_name;

create_definition:
  col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
            [PRIMARY KEY] [reference_definition]
  or    PRIMARY KEY (index_col_name,...)
  or    KEY [index_name] (index_col_name,...)
  or    INDEX [index_name] (index_col_name,...)
  or    UNIQUE [INDEX] [index_name] (index_col_name,...)
  or    FULLTEXT [INDEX] [index_name] (index_col_name,...)
  or    [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
            [reference_definition]
  or    CHECK (expr)

type:
        TINYINT[(length)] [UNSIGNED] [ZEROFILL]
  or    SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
  or    MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
  or    INT[(length)] [UNSIGNED] [ZEROFILL]
  or    INTEGER[(length)] [UNSIGNED] [ZEROFILL]
  or    BIGINT[(length)] [UNSIGNED] [ZEROFILL]
  or    REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
  or    NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
  or    CHAR(length) [BINARY]
  or    VARCHAR(length) [BINARY]
  or    DATE
  or    TIME
  or    TIMESTAMP
  or    DATETIME
  or    TINYBLOB
  or    BLOB
  or    MEDIUMBLOB
  or    LONGBLOB
  or    TINYTEXT
  or    TEXT
  or    MEDIUMTEXT
  or    LONGTEXT
  or    ENUM(value1,value2,value3,...)
  or    SET(value1,value2,value3,...)

index_col_name:
        col_name [(length)]

reference_definition:
        REFERENCES tbl_name [(index_col_name,...)]
                   [MATCH FULL | MATCH PARTIAL]
                   [ON DELETE reference_option]
                   [ON UPDATE reference_option]

reference_option:
        RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

table_options:
	TYPE = {BDB | HEAP | ISAM | InnoDB | MERGE | MRG_MYISAM | MYISAM }
or	AUTO_INCREMENT = #
or	AVG_ROW_LENGTH = #
or	CHECKSUM = {0 | 1}
or	COMMENT = "string"
or	MAX_ROWS = #
or	MIN_ROWS = #
or	PACK_KEYS = {0 | 1 | DEFAULT}
or	PASSWORD = "string"
or	DELAY_KEY_WRITE = {0 | 1}
or      ROW_FORMAT= { default | dynamic | fixed | compressed }
or	RAID_TYPE= {1 | STRIPED | RAID0 } RAID_CHUNKS=#  RAID_CHUNKSIZE=#
or	UNION = (table_name,[table_name...])
or	INSERT_METHOD= {NO | FIRST | LAST }
or      DATA DIRECTORY="absolute path to directory"
or      INDEX DIRECTORY="absolute path to directory"

select_statement:
	[IGNORE | REPLACE] SELECT ...  (Some legal select statement)

CREATE TABLEはカレントデータベースに、与えられた名前のテーブルを 作成します。テーブルの名前として許される命名規則は、See section データベース名、テーブル名、インデックス名、フィールド名、エイリアス名に 依ります。 カレントデータベースが無い場合や、テーブルが既に存在している場合はエラーが 発生します。

MySQL バージョン 3.22 以降ではテーブル名は db_name.tbl_name とい う形で与える事もできます。 これはカレントデータベースがあるかどうかにに関係なく動作します。

MySQL バージョン 3.23 からは、テーブル作成時に TEMPORARY キーワー ドを使用することができます。 一時テーブルの名前はそれぞれの接続内に制限されます。 一時テーブルは、もし、コネクションが落ちた場合、自動で消去されます。 これは、二つの違う接続で、同じ名前の一時テーブルを 衝突することなく、使用できるという事です。 さらには、既に存在するテーブルと同名であっても、一時テーブルは使用できます。 (一時テーブルが削除されるまで、実在するテーブルは隠されます) From MySQL 4.0.2 one must have the CREATE TEMPORARY TABLES privilege to be able to create temporary tables.

MySQL バージョン 3.23 以降では、 IF NOT EXISTS キーワードを使用 できます。 これは、もしテーブルが既に存在していた場合、エラーを発生させません。 テーブルの構造が一意かどうかまでは検査しないことに注意。

In MySQL 4.1 you can use LIKE to create a table based on a table definition in another table. In MySQL 4.1 you can also specify the type for a generated column:

CREATE TABLE foo (a tinyint not null) SELECT b+1 AS 'a' FROM bar;

それぞれのテーブルは、データベースディレクトリにおける以下の複数の ファイルで表されます。これは MyISAM 型 のテーブル場合:

File Purpose
tbl_name.frm Table definition (form) file
tbl_name.MYD Datafile
tbl_name.MYI Index file

フィールドに対する種々の型属性の詳細は、section フィールド型を参照のこと。

暗黙のフィールド定義変更

いくつかのケースにおいてMySQLは、CREATE TABLEステートメントで与 えられたフィールド定義を暗黙の内に変更します (これは ALTER TABLE で起きるかもしれません)

もし MySQL がフィールドの型をあなたが指定したものと違うものにしたかどう かを知りたい場合、テーブルの作成、alter 後に、 DESCRIBE tbl_name 構文 を発行します。

myisampackを使用してテーブルを圧縮した場合、別のフィールド定義変更がある 程度起こることがあります。 See section 圧縮テーブルの特徴.

ALTER TABLE 構文

ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...]

alter_specification:
        ADD [COLUMN] create_definition [FIRST | AFTER column_name ]
  or    ADD [COLUMN] (create_definition, create_definition,...)
  or    ADD INDEX [index_name] (index_col_name,...)
  or    ADD PRIMARY KEY (index_col_name,...)
  or    ADD UNIQUE [index_name] (index_col_name,...)
  or    ADD FULLTEXT [index_name] (index_col_name,...)
  or	ADD [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
            [reference_definition]
  or    ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
  or    CHANGE [COLUMN] old_col_name create_definition
               [FIRST | AFTER column_name]
  or    MODIFY [COLUMN] create_definition [FIRST | AFTER column_name]
  or    DROP [COLUMN] col_name
  or    DROP PRIMARY KEY
  or    DROP INDEX index_name
  or    DISABLE KEYS
  or    ENABLE KEYS
  or    RENAME [TO] new_tbl_name
  or    ORDER BY col
  or    table_options

ALTER TABLEは、既存のテーブルの構造変更を可能にします。 例えば、フィールドの追加や削除、インデックスの作成や破棄、既存のフィールド属性の 変更、及びフィールドやテーブルそのものの名前の変更です。 また、テーブルのコメントやテーブルの型式を変更することも可能です。 See section CREATE TABLE 構文.

もし ALTER TABLE でフィールド定義を変えても DESCRIBE tbl_name が フィールドを変更していないと示すなら、これは MySQL が section 暗黙のフィールド定義変更. に述べている理由の一つで変更していない可能性が あります。 例えば、 VARCHAR フィールドを CHAR にしようとすると, MySQL はそのテーブルに他の可変長のフィールドがあるかぎり、 VARCHAR のままにしようとします。

ALTER TABLEはオリジナルのテーブルの一時的なコピーを作成することにより動作 します。 コピーへの変更作業が完了すると、オリジナルのテーブルは削除され新しく 作られた方の名前が変更されます。これは全ての変更が自動的に新しいテーブルに 対して実施されることにより、誤った変更無しに完了します。 ALTER TABLEが実行されている間、オリジナルのテーブルは他の クライアントから読みだしが可能です。このテーブルへの更新や書き込みは、 新しいテーブルが準備完了となるまで遅らされます。

注意: ALTER TABLERENAME 以外のオプションを使用する場合、 MySQL は常に一時テーブルを生成します。データが厳密にコピーする必 要がないとしてもです(フィールドの名前を変更する時など)。 We plan to fix this in the future, but as one doesn't normally do ALTER TABLE that often this isn't that high on our TODO. For MyISAM tables, you can speed up the index recreation part (which is the slowest part of the recreation process) by setting the myisam_sort_buffer_size variable to a high value.

以下は、ALTER TABLEの使用例を表す例です。 次に示すように作成されたテーブルt1から始めます:

mysql> CREATE TABLE t1 (a INTEGER,b CHAR(10));

テーブルt1の名前をt2に変更するには:

mysql> ALTER TABLE t1 RENAME t2;

フィールド aINTEGER から TINYINT NOT NULL に (名前は同じままで)変更し、 bCHAR(10) から CHAR(20) に変更しつつ、 名前を b から cに変更するには:

mysql> ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20);

TIMESTAMPを追加し、名前をdとするには:

mysql> ALTER TABLE t2 ADD d TIMESTAMP;

フィールドdにインデックスを追加し、フィールドaをプライマリ・キーと するには:

mysql> ALTER TABLE t2 ADD INDEX (d), ADD PRIMARY KEY (a);

フィールドcを削除するには:

mysql> ALTER TABLE t2 DROP COLUMN c;

To add a new AUTO_INCREMENT integer column named c:

mysql> ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT,
    ->       ADD INDEX (c);

ここで我々が c をインデックス指定したのは、 AUTO_INCREMENT フィー ルドはインデックスであるべきだからで、 cNOT NULL 指定しているのは インデックスフィールドは NULL にできないからです。

AUTO_INCREMENT フィールドを追加した場合、フィールドの値は 自動的にシーケンス番号で埋められます。 最初のシーケンス番号は、ALTER TABLE 前に SET INSERT_ID=# を 実行するか、または AUTO_INCREMENT = # テーブルオプションを使用する ことで設定できます。 See section SET 構文.

MyISAM テーブルでは、AUTO_INCREMENT フィールドを変更しない場合、シー ケンス番号は影響を受けません。AUTO_INCREMENT フィールドを破棄し、そ れから別の AUTO_INCREMENT フィールドを追加した場合、番号は再度 1 か ら始まります。

See section Problems with ALTER TABLE..

RENAME TABLE 構文

RENAME TABLE tbl_name TO new_tbl_name[, tbl_name2 TO new_tbl_name2,...]

リネームは自動的に行なわれます。これは、他のスレッドはリネームが動作中はテー ブルのどこにもアクセスできないことを意味します。空のテーブルでテーブルを置 き換えることが可能です:

CREATE TABLE new_table (...);
RENAME TABLE old_table TO backup_table, new_table TO old_table;

リネームは左から右に行なわれます。2つのテーブルの名前を交換したい場合には、 次のようにする必要があることを意味します:

RENAME TABLE old_table    TO backup_table,
             new_table    TO old_table,
             backup_table TO new_table;

2つのデータベースが同じディスク上にあれば、あるデータベースから他のデータ ベースにリネームすることも可能です:

RENAME TABLE current_database.table_name TO other_database.table_name;

RENAME 実行時には、ロックされたテーブルや有効なトランザクションを持 つことはできません。元のテーブルで ALTERDROP 権限を、新 しいテーブルで CREATEINSERT 権限を持つことも必要です。

MySQL が複数のテーブルのリネームで何らかのエラーに遭遇した場合、 リネームしたすべてのテーブルを逆にリネームし、すべてを元の状態に戻します。

RENAME TABLE was added in MySQL 3.23.23.

DROP TABLE Syntax

DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name,...] [RESTRICT | CASCADE]

DROP TABLEは、1つ又は1つ以上のテーブルを破棄します。テーブルの全てのデー タとテーブル定義は破棄されますので、このコマンドの使用は慎重に行ってくだ さい!

MySQL バージョン 3.22以降では、テーブルが存在しないことに起因するエラー を防ぐために、キーワード IF EXISTS を使用することができます。 In 4.1 one gets a NOTE for all not existing tables when using IF EXISTS. See section SHOW WARNINGS | ERRORS. RESTRICTCASCADE は移植を簡単にするために許されています。 しばらくはこれらは何も行ないません。 注意: DROP TABLE はトランザクション安全ではなく、自動的に すべてのアクティブトランザクションをコミットします。 (except if you are using 4.1 and the TEMPORARY key word. )

Option TEMPORARY is ignored in 4.0. In 4.1 this option works as follows:

Using TEMPORARY is a good way to ensure that you don't accidently drop a real table.

CREATE INDEX 構文

CREATE [UNIQUE|FULLTEXT] INDEX index_name
       ON tbl_name (col_name[(length)],... )

CREATE INDEX 構文は MySQL 3.22 より以前のバージョンではなにもし ません。 バージョン 3.22 以降で、CREATE INDEX はインデックスの作成のために ALTER TABLE を呼びだしています。 @xref{ALTER TABLE, , ALTER TABLE}.

通常、テーブル内の全てのインデックスは CREATE TABLE で テーブルを作るときに一度に作成されます。 See section CREATE TABLE 構文. CREATE INDEX は既に存在するテーブルに対し、インデックスを追加します。 CREATE INDEX allows you to add indexes to existing tables.

フィールドを (col1,col2,...) として指定すると、複数フィールドインデックス を作成します。 インデックスの値は、与えられたフィールドの値を連結して、構成されます。

CHARVARCHAR フィールドでは、インデックスはフィールドの一部分だ けを使用して 作成されます。これは col_name(length) 構文を使用します。 (BLOBTEXT 節では length が必要です)。 最初の10文字をインデックスとして使用するには、この構文は以下のようにして使用しま す(name フィールドにインデックスを作ります):

mysql> CREATE INDEX part_of_name ON customer (name(10));

フィールドの一部分だけをインデックスに使用すれば、インデックスファイルをはるかに 小さくすることができます。 ほとんどの名前が最初の10文字において通常異なるので、 このインデックスは name フィールド全部を使用して創り出したインデックスに 比べて遅くなることはありません。また、多くのディスクスペースを節約でき、 INSERT を速くするのです!

MySQL version 3.23.2 以上で MyISAM 型のテーブルを使用している 場合、NULL 値をもつフィールドや、 BLOB/TEXT フィールドに対して インデックスを張ることが可能です。

MySQL がどのようにしてインデックスを使用するかは → section MySQL はどのようにインデックスを使用するか?.

FULLTEXT indexes can index only VARCHAR and TEXT columns, and only in MyISAM tables. FULLTEXT indexes are available in MySQL Version 3.23.23 and later. section MySQL Full-text Search.

DROP INDEX 構文

DROP INDEX index_name ON tbl_name

DROP INDEXindex_name という名前のインデックスをテーブル tbl_name から破棄します。 DROP INDEX は MySQL バージョン 3.22 より以前のバージョンではなに もしません。 3.22 以降で、DROP INDEX はインデックスの破棄のために ALTER TABLE を呼びだしています。 See section ALTER TABLE 構文.

Basic MySQL User Utility Commands

USE 構文

USE db_name

USE db_name 構文は、 MySQL に db_name データベースを この後のクエリのデフォルトのデータベースにするように指示します。 指定されたデータベースは、セッションの最後まで、あるいは、他の USE 構文 が発行されるまで残ります:

mysql> USE db1;
mysql> SELECT count(*) FROM mytable;      # selects from db1.mytable
mysql> USE db2;
mysql> SELECT count(*) FROM mytable;      # selects from db2.mytable

USE 構文で特定のデータベースをカレントにしても、 他のデータベースのテーブルからアクセスすることを妨げません。 以下は db1 データベースの author テーブルと、 db2 データベースの editor テーブルにアクセスする例です:

mysql> USE db1;
mysql> SELECT author_name,editor_name FROM author,db2.editor
    ->        WHERE author.editor_id = db2.editor.editor_id;

USE 構文は Sybase の互換のために提供されています。

DESCRIBE 構文 (フィールドについての情報を得る)

{DESCRIBE | DESC} tbl_name [col_name | wild]

DESCRIBE is a shortcut for SHOW COLUMNS FROM. See section Retrieving information about Database, Tables, Columns, and Indexes.

DESCRIBE はフィールドについての情報を与えます。 col_name はフィールドはフィールド名または文字列です。 文字列は SQL `%',`_' ワイルドカードを含めます。 There is no need to enclose the string in quotes.

もしフィールドの型があなたが CREATE TABLE 文で与えた物と違っているなら、 これは MySQL がフィールドの型を変更していることに注意してください。 See section 暗黙のフィールド定義変更.

このコマンドは Oracle の互換のためにあります。

SHOW 構文は似たような情報を提供します。 See section SHOW 構文.

MySQL Transactional and Locking Commands

BEGIN/COMMIT/ROLLBACK 構文

デフォルトでは MySQL は autocommit モードで動作します。こ れは、更新を実行するとすぐに MySQL が更新をディスクに格納すること を意味します。

もし トランザクションセーフのテーブル(like BDB, InnoDB) を使用するなら, 以下のコマンドで MySQL を 非 autocommit モード状態にすることができます:

SET AUTOCOMMIT=0

この後、ディスクに変更を格納するためには COMMIT を使用し、また、変 更を無視するためには ROLLBACK する必要があります。

ある一連のステートメントのために AUTOCOMMIT モードからスイッチし たい場合は、START TRANSACTIONBEGIN または BEGIN WORK ステートメントを使用できます。

START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summmary=@A WHERE type=1;
COMMIT;

START TRANSACTION was added to MySQL 4.0.11; This is the recommended way to start an ad-hoc transaction as this is ANSI SQL syntax. (訳注: 4.0.11より前では、BEGIN を使用します)

注意: トランザクション安全テーブルを使用していない場合は、autocommit モードのステータスには依存せずに、変更はすぐに格納されます。

If you do a ROLLBACK when you have updated a non-transactional table you will get an error (ER_WARNING_NOT_COMPLETE_ROLLBACK) as a warning. All transaction-safe tables will be restored but any non-transaction-safe table will not change.

If you are using START TRANSACTION or SET AUTOCOMMIT=0, you should use the MySQL binary log for backups instead of the older update log. Transactions are stored in the binary log in one chunk, upon COMMIT, to ensure that transactions which are rolled back are not stored. See section The Binary Update Log バイナリ更新ログ (3.23.15以上).

The following commands automatically end a transaction (as if you had done a COMMIT before executing the command):

Command Command Command
ALTER TABLE BEGIN CREATE INDEX
DROP DATABASE DROP TABLE RENAME TABLE
TRUNCATE

You can change the isolation level for transactions with SET TRANSACTION ISOLATION LEVEL .... See section SET TRANSACTION 構文.

LOCK TABLES/UNLOCK TABLES 構文

LOCK TABLES tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE}
            [, tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE} ...]
...
UNLOCK TABLES

LOCK TABLES はカレントのスレッドのためにテーブルをロックします。 UNLOCK TABLES はこのスレッドの全てのロックを解除します。 カレントスレッドによってロックされた全てのテーブルは、 スレッドが他の LOCK TABLES を発行した場合やサーバーが接続を閉じた場合、 自動で解除されます。

To use LOCK TABLES in MySQL 4.0.2 you need the global LOCK TABLES privilege and a SELECT privilege on the involved tables. In MySQL 3.23 you need to have SELECT, insert, DELETE and UPDATE privileges for the tables.

The main reasons to use LOCK TABLES are for emulating transactions or getting more speed when updating tables. This is explained in more detail later.

スレッドがテーブルに READ ロックを持つ場合、そのスレッド(と他の全てのスレ ッド)はテーブルからの読み込みだけができます。スレッドがテーブルに WRITE ロックを持つ場合、 このスレッドだけがテーブルの READWRITE ができます。 他のスレッドはブロックされます。

READ LOCALREAD の違いは、READ LOCAL は、ロックが 保持されている間にコンフリクトしない INSERT ステートメントを実行で きることです。ただし、これはロックを保持している間に MySQL の外で データベースファイルを操作しようとする場合は使用できません。

When you use LOCK TABLES, you must lock all tables that you are going to use and you must use the same alias that you are going to use in your queries! If you are using a table multiple times in a query (with aliases), you must get a lock for each alias!

WRITE ロックは普通、できる限り更新を行わせるため、 READ ロックよりも優先順位が高くなっています。 これはあるスレッドが READ ロックをかけ、それ以外のスレッドが WRITE を要求した場合、 READ は、WRITE スレッドがロックをし、それを解除 するまで待つということです。 LOW_PRIORITY WRITE を使用すれば、 WRITE ロックを待っているスレッドに READ ロックを得させることができ ます。 LOW_PRIORITY WRITEREAD ロックをしているスレッドが一つもないと わかっている場合に使用すべきです。

LOCK TABLES works as follows:

  1. Sort all tables to be locked in a internally defined order (from the user standpoint the order is undefined).
  2. If a table is locked with a read and a write lock, put the write lock before the read lock.
  3. Lock one table at a time until the thread gets all locks.

This policy ensures that table locking is deadlock free. There is however other things one needs to be aware of with this schema:

If you are using a LOW_PRIORITY WRITE lock for a table, this means only that MySQL will wait for this particlar lock until there is no threads that wants a READ lock. When the thread has got the WRITE lock and is waiting to get the lock for the next table in the lock table list, all other threads will wait for the WRITE lock to be released. If this becomes a serious problem with your application, you should consider converting some of your tables to transactions safe tables.

You can safely kill a thread that is waiting for a table lock with KILL. See section KILL 構文.

INSERT DELAYED で使用しているいかなるテーブルも、ロックすべきではありませ ん。この場合 INSERT は別のスレッドで行なわれるからです。

通常、全ての単一の UPDATE 構文においては、テーブルをロックする必要はあり ません; スレッドは、他のスレッドが現在実行している SQL 文に干渉することができません。 これらはテーブルをロックした方がよい、まれな場合です:

インクリメント アップデイト (UPDATE customer SET value=value+new_value) または LAST_INSERT_ID() 関数の使用により、多くの場合 LOCK TABLES を回避 できます。

いくつかの場合、ユーザレベルロック: GET_LOCK()RELEASE_LOCK() の使用 によっても解決できます。これらのロックはサーバ内のハッシュテーブル内に保 持され、高速のため pthread_mutex_lock() で実装されました。 See section その他の関数.

ロックポリシーのさらなる情報については section MySQL はどのようにテーブルをロックするか を見てくださ い。

You can lock all tables in all databases with read locks with the FLUSH TABLES WITH READ LOCK command. See section FLUSH 構文. This is very convenient way to get backups if you have a filesystem, like Veritas, that can take snapshots in time.

NOTE: LOCK TABLES is not transaction-safe and will automatically commit any active transactions before attempting to lock the tables.

SET TRANSACTION 構文

SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL
{ READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE }

Sets the transaction isolation level for the global, whole session or the next transaction.

The default behaviour is to set the isolation level for the next (not started) transaction. If you use the GLOBAL keyword, the statement sets the default transaction level globally for all new connections created from that point on. You will need the SUPER privilege to do this. Using the SESSION keyword sets the default transaction level for all future transactions performed on the current connection.

You can set the default global isolation level for mysqld with --transaction-isolation=.... See section mysqld コマンド行オプション.

MySQL Full-text Search

As of Version 3.23.23, MySQL has support for full-text indexing and searching. Full-text indexes in MySQL are an index of type FULLTEXT. FULLTEXT indexes are used with MyISAM tables and can be created from CHAR, VARCHAR, or TEXT columns at CREATE TABLE time or added later with ALTER TABLE or CREATE INDEX. For large datasets, it will be much faster to load your data into a table that has no FULLTEXT index, then create the index with ALTER TABLE (or CREATE INDEX). Loading data into a table that already has a FULLTEXT index will be slower.

Full-text searching is performed with the MATCH() function.

mysql> CREATE TABLE articles (
    ->   id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    ->   title VARCHAR(200),
    ->   body TEXT,
    ->   FULLTEXT (title,body)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO articles VALUES
    -> (NULL,'MySQL Tutorial', 'DBMS stands for DataBase ...'),
    -> (NULL,'How To Use MySQL Efficiently', 'After you went through a ...'),
    -> (NULL,'Optimising MySQL','In this tutorial we will show ...'),
    -> (NULL,'1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
    -> (NULL,'MySQL vs. YourSQL', 'In the following database comparison ...'),
    -> (NULL,'MySQL Security', 'When configured properly, MySQL ...');
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM articles
    ->          WHERE MATCH (title,body) AGAINST ('database');
+----+-------------------+------------------------------------------+
| id | title             | body                                     |
+----+-------------------+------------------------------------------+
|  5 | MySQL vs. YourSQL | In the following database comparison ... |
|  1 | MySQL Tutorial    | DBMS stands for DataBase ...             |
+----+-------------------+------------------------------------------+
2 rows in set (0.00 sec)

The MATCH() function performs a natural language search for a string against a text collection (a set of one or more columns included in a FULLTEXT index). The search string is given as the argument to AGAINST(). The search is performed in case-insensitive fashion. For every row in the table, MATCH() returns a relevance value, that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.

When MATCH() is used in a WHERE clause (see example above) the rows returned are automatically sorted with highest relevance first. Relevance values are non-negative floating-point numbers. Zero relevance means no similarity. Relevance is computed based on the number of words in the row, the number of unique words in that row, the total number of words in the collection, and the number of documents (rows) that contain a particular word.

It is also possible to perform a boolean mode search. This is explained later in the section.

The preceding example is a basic illustration showing how to use the MATCH() function. Rows are returned in order of decreasing relevance.

The next example shows how to retrieve the relevance values explicitly. As neither WHERE nor ORDER BY clauses are present, returned rows are not ordered.

mysql> SELECT id,MATCH title,body AGAINST ('Tutorial') FROM articles;
+----+-----------------------------------------+
| id | MATCH (title,body) AGAINST ('Tutorial') |
+----+-----------------------------------------+
|  1 |                        0.64840710366884 |
|  2 |                                       0 |
|  3 |                        0.66266459031789 |
|  4 |                                       0 |
|  5 |                                       0 |
|  6 |                                       0 |
+----+-----------------------------------------+
6 rows in set (0.00 sec)

The following example is more complex. The query returns the relevance and still sorts the rows in order of decreasing relevance. To achieve this result, you should specify MATCH() twice. This will cause no additional overhead, because the MySQL optimiser will notice that the two MATCH() calls are identical and invoke the full-text search code only once.

mysql> SELECT id, body, MATCH (title,body) AGAINST
    -> ('Security implications of running MySQL as root') AS score
    -> FROM articles WHERE MATCH (title,body) AGAINST
    -> ('Security implications of running MySQL as root');
+----+-------------------------------------+-----------------+
| id | body                                | score           |
+----+-------------------------------------+-----------------+
|  4 | 1. Never run mysqld as root. 2. ... | 1.5055546709332 |
|  6 | When configured properly, MySQL ... |   1.31140957288 |
+----+-------------------------------------+-----------------+
2 rows in set (0.00 sec)

MySQL uses a very simple parser to split text into words. A ``word'' is any sequence of characters consisting of letters, digits, `'', and `_'. Any ``word'' that is present in the stopword list or is just too short (3 characters or less) is ignored.

Every correct word in the collection and in the query is weighted according to its significance in the query or collection. This way, a word that is present in many documents will have lower weight (and may even have a zero weight), because it has lower semantic value in this particular collection. Otherwise, if the word is rare, it will receive a higher weight. The weights of the words are then combined to compute the relevance of the row.

Such a technique works best with large collections (in fact, it was carefully tuned this way). For very small tables, word distribution does not reflect adequately their semantic value, and this model may sometimes produce bizarre results.

mysql> SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('MySQL');
Empty set (0.00 sec)

The search for the word MySQL produces no results in the above example, because that word is present in more than half the rows. As such, it is effectively treated as a stopword (that is, a word with zero semantic value). This is the most desirable behaviour -- a natural language query should not return every second row from a 1GB table.

A word that matches half of rows in a table is less likely to locate relevant documents. In fact, it will most likely find plenty of irrelevant documents. We all know this happens far too often when we are trying to find something on the Internet with a search engine. It is with this reasoning that such rows have been assigned a low semantic value in this particular dataset.

As of Version 4.0.1, MySQL can also perform boolean full-text searches using the IN BOOLEAN MODE modifier.

mysql> SELECT * FROM articles WHERE MATCH (title,body)
    ->     AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);
+----+------------------------------+-------------------------------------+
| id | title                        | body                                |
+----+------------------------------+-------------------------------------+
|  1 | MySQL Tutorial               | DBMS stands for DataBase ...        |
|  2 | How To Use MySQL Efficiently | After you went through a ...        |
|  3 | Optimising MySQL             | In this tutorial we will show ...   |
|  4 | 1001 MySQL Tricks            | 1. Never run mysqld as root. 2. ... |
|  6 | MySQL Security               | When configured properly, MySQL ... |
+----+------------------------------+-------------------------------------+

This query retrieved all the rows that contain the word MySQL (note: the 50% threshold is not used), but that do not contain the word YourSQL. Note that a boolean mode search does not automatically sort rows in order of decreasing relevance. You can see this from result of the preceding query, where the row with the highest relevance (the one that contains MySQL twice) is listed last, not first. A boolean full-text search can also work even without a FULLTEXT index, although it would be slow.

The boolean full-text search capability supports the following operators:

+
A leading plus sign indicates that this word must be present in every row returned.
-
A leading minus sign indicates that this word must not be present in any row returned.
By default (when neither plus nor minus is specified) the word is optional, but the rows that contain it will be rated higher. This mimicks the behaviour of MATCH() ... AGAINST() without the IN BOOLEAN MODE modifier.
< >
These two operators are used to change a word's contribution to the relevance value that is assigned to a row. The < operator decreases the contribution and the > operator increases it. See the example below.
( )
Parentheses are used to group words into subexpressions.
~
A leading tilde acts as a negation operator, causing the word's contribution to the row relevance to be negative. It's useful for marking noise words. A row that contains such a word will be rated lower than others, but will not be excluded altogether, as it would be with the - operator.
*
An asterisk is the truncation operator. Unlike the other operators, it should be appended to the word, not prepended.
"
The phrase, that is enclosed in double quotes ", matches only rows that contain this phrase literally, as it was typed.

And here are some examples:

apple banana
find rows that contain at least one of these words.
+apple +juice
... both words.
+apple macintosh
... word ``apple'', but rank it higher if it also contain ``macintosh''.
+apple -macintosh
... word ``apple'' but not ``macintosh''.
+apple +(>pie <strudel)
... ``apple'' and ``pie'', or ``apple'' and ``strudel'' (in any order), but rank ``apple pie'' higher than ``apple strudel''.
apple*
... ``apple'', ``apples'', ``applesauce'', and ``applet''.
"some words"
... ``some words of wisdom'', but not ``some noise words''.

Full-text Restrictions

Fine-tuning MySQL Full-text Search

Unfortunately, full-text search has few user-tunable parameters yet, although adding some is very high on the TODO. If you have a MySQL source distribution (see section MySQL ソースディストリビューションのインストール), you can exert more control over full-text searching behaviour.

Note that full-text search was carefully tuned for the best searching effectiveness. Modifying the default behaviour will, in most cases, only make the search results worse. Do not alter the MySQL sources unless you know what you are doing!

For those changes that require you to rebuild your FULLTEXT indexes, the easiest way to do so for a MyISAM table is to use the following statement, which rebuilds the index file:

mysql> REPAIR TABLE tbl_name QUICK;

Full-text Search TODO

MySQL Query Cache (4.0.1以上)

From version 4.0.1, MySQL server features a Query Cache. When in use, the query cache stores the text of a SELECT query together with the corresponding result that was sent to the client. If an identical query is later received, the server will retrieve the results from the query cache rather than parsing and executing the same query again.

NOTE: The query cache does not return stale data. When data is modified, any relevant entries in the query cache are flushed.

The query cache is extremely useful in an environment where (some) tables don't change very often and you have a lot of identical queries. This is a typical situation for many web servers that use a lot of dynamic content.

Below is some performance data for the query cache. (These results were generated by running the MySQL benchmark suite on a Linux Alpha 2 x 500 MHz with 2GB RAM and a 64MB query cache):

How The Query Cache Operates

Queries are compared before parsing, thus

SELECT * FROM tbl_name

and

Select * from tbl_name

are regarded as different queries for query cache, so queries need to be exactly the same (byte for byte) to be seen as identical. In addition, a query may be seen as different if for instance one client is using a new communication protocol format or another character set than another client.

Queries that uses different databases, uses different protocol versions or the uses different default character sets are considered different queries and cached separately.

The cache does work for SELECT CALC_ROWS ... and SELECT FOUND_ROWS() ... type queries because the number of found rows is also stored in the cache.

If query result was returned from query cache then status variable Com_select will not be increased, but Qcache_hits will be. See section Query Cache Status and Maintenance.

If a table changes (INSERT, UPDATE, DELETE, TRUNCATE, ALTER or DROP TABLE|DATABASE), then all cached queries that used this table (possibly through a MRG_MyISAM table!) become invalid and are removed from the cache.

Transactional InnoDB tables that have been changed will be invalidated when a COMMIT is performed.

A query cannot be cached if it contains one of the functions:
Function Function Function
User-Defined Functions CONNECTION_ID FOUND_ROWS
GET_LOCK RELEASE_LOCK LOAD_FILE
MASTER_POS_WAIT NOW SYSDATE
CURRENT_TIMESTAMP CURDATE CURRENT_DATE
CURTIME CURRENT_TIME DATABASE
ENCRYPT (with one parameter) LAST_INSERT_ID RAND
UNIX_TIMESTAMP (without parameters) USER BENCHMARK

Nor can a query be cached if it contains user variables, references the mysql system database, is of the form SELECT ... IN SHARE MODE, SELECT ... INTO OUTFILE ..., SELECT ... INTO DUMPFILE ... or of the form SELECT * FROM AUTOINCREMENT_FIELD IS NULL (to retrieve last insert id - ODBC work around).

However, FOUND ROWS() will return the correct value, even if the preceding query was fetched from the cache.

In case a query does not use any tables, or uses temporary tables, or if the user has a column privilege for any of the involved tables, that query will not be cached.

Before a query is fetched from the query cache, MySQL will check that the user has SELECT privilege to all the involved databases and tables. If this is not the case, the cached result will not be used.

Query Cache Configuration

The query cache adds a few MySQL system variables for mysqld which may be set in a configuration file, on the command-line when starting mysqld.

Inside a thread (connection), the behaviour of the query cache can be changed from the default. The syntax is as follows:

QUERY_CACHE_TYPE = OFF | ON | DEMAND QUERY_CACHE_TYPE = 0 | 1 | 2

Option Description
0 or OFF Don't cache or retrieve results.
1 or ON Cache all results except SELECT SQL_NO_CACHE ... queries.
2 or DEMAND Cache only SELECT SQL_CACHE ... queries.

Query Cache Options in SELECT

There are two possible query cache related parameters that may be specified in a SELECT query:

Option Description
SQL_CACHE If QUERY_CACHE_TYPE is DEMAND, allow the query to be cached. If QUERY_CACHE_TYPE is ON, this is the default. If QUERY_CACHE_TYPE is OFF, do nothing.
SQL_NO_CACHE Make this query non-cachable, don't allow this query to be stored in the cache.

Query Cache Status and Maintenance

With the FLUSH QUERY CACHE command you can defragment the query cache to better utilise its memory. This command will not remove any queries from the cache. FLUSH TABLES also flushes the query cache.

The RESET QUERY CACHE command removes all query results from the query cache.

You can check whether the query cache is present in your MySQL version:

mysql> SHOW VARIABLES LIKE 'have_query_cache';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| have_query_cache | YES   |
+------------------+-------+
1 row in set (0.00 sec)

You can monitor query cache performance in SHOW STATUS:

Variable Description
Qcache_queries_in_cache Number of queries registered in the cache.
Qcache_inserts Number of queries added to the cache.
Qcache_hits Number of cache hits.
Qcache_lowmem_prunes Number of queries that were deleted from cache because of low memory.
Qcache_not_cached Number of non-cached queries (not cachable, or due to QUERY_CACHE_TYPE).
Qcache_free_memory Amount of free memory for query cache.
Qcache_free_blocks Number of free memory blocks in query cache.
Qcache_total_blocks Total number of blocks in query cache.

Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached.

The query cache uses variable length blocks, so Qcache_total_blocks and Qcache_free_blocks may indicate query cache memory fragmentation. After FLUSH QUERY CACHE only a single (big) free block remains.

Note: Every query needs a minimum of two blocks (one for the query text and one or more for the query results). Also, every table that is used by a query needs one block, but if two or more queries use same table only one block needs to be allocated.

You can use the Qcache_lowmem_prunes status variable to tune the query cache size. It counts the number of queries that have been removed from the cache to free up memory for caching new queries. The query cache uses a least recently used (LRU) strategy to decide which queries to remove from the cache.

MySQL テーブル型

As of MySQL Version 3.23.6, you can choose between three basic table formats (ISAM, HEAP and MyISAM. Newer versions of MySQL may support additional table types (InnoDB, or BDB), depending on how you compile it.

When you create a new table, you can tell MySQL what type of table to create. The default table type is usually MyISAM.

MySQL will always create a `.frm' file to hold the table and column definitions. The table's index and data will be stored in one or more other files, depending on the table type.

If you try to use a table type that is not compiled-in or activated, MySQL will instead create a table of type MyISAM. This behaviour is convenient when you want to copy tables between MySQL servers that support different table types. (Perhaps your master server supports transactional storage engines for increased safety, while the slave servers use only non-transactional storage engines for greater speed.)

This automatic change of table types can be confusing for new MySQL users. We plan to fix this by introducing warnings in the new client-server protocol in version 4.1 and generating a warning when a table type is automatically changed.

ALTER TABLE 文を使用すれば、テーブルを違う形式に変更できます。 See section ALTER TABLE 構文.

MySQL では、二つの違う種類のテーブルをサポートしていることに注意してください。 一つはトランザクションセーフのテーブル(BDB, InnoDB)、 もう一つはトランザクションを持たないテーブル (HEAP, ISAM, MERGE, and MyISAM).

トランザクションセーフのテーブル(Transaction Safe Tables) の利点は(TST):

Note that to use InnoDB tables you have to use at least the innodb_data_file_path startup option. See section InnoDB 起動オプション.

非トランザクションセーフ(Not Transaction Safe Tables)のテーブルの利点は(NTST):

You can combine TST and NTST tables in the same statements to get the best of both worlds.

MyISAM テーブル (3.23.0以上)

MyISAM は、MySQL Version 3.23 でのデフォルトのテーブル形式です. これは ISAM コードを基にし、多くの便利な拡張機能を持っています。

インデックスは .MYI (MYIndex) 拡張子のつくファイルに保存され、 データは、 .MYD (MYData) 拡張子のつくファイルに保存されます。 myisamchk ユーティリティを使用して、 MyISAM テーブルの 検査・修復が可能です。 See section Using myisamchk for Crash Recovery. myisampack コマンドを使用して、MyISAM を圧縮して 小さくすることが可能です See section myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ.

The following is new in MyISAM:

MyISAM also supports the following things, which MySQL will be able to use in the near future:

Note that index files are usually much smaller with MyISAM than with ISAM. This means that MyISAM will normally use less system resources than ISAM, but will need more CPU time when inserting data into a compressed index.

mysqld に与える以下のオプションは、 MyISAM テーブルの振る舞いを変更できます. See section SHOW VARIABLES.

Option Description
--myisam-recover=# 壊れたテーブルを自動でリカバリ.
-O myisam_sort_buffer_size=# リカバリに使用されるバッファ
--delay-key-write=ALL Don't flush key buffers between writes for any MyISAM table
-O myisam_max_extra_sort_file_size=# Used to help MySQL to decide when to use the slow but safe key cache index create method. Note that this parameter is given in megabytes before 4.0.3 and in bytes starting from this version.
-O myisam_max_sort_file_size=# Don't use the fast sort index method to created index if the temporary file would get bigger than this. Note that this parameter is given in megabytes before 4.0.3 and in bytes starting from this version.
-O bulk_insert_buffer_size=# Size of tree cache used in bulk insert optimisation. Note that this is a limit per thread!

automatic recovery は mysqld--myisam-recover=# オプション (3.23.26以上) で起動したときに有効になります. See section mysqld コマンド行オプション. On open, the table is checked if it's marked as crashed or if the open count variable for the table is not 0 and you are running with --skip-external-locking.(4.0.3以前では --skip-locking) 上のどれかに当てはまる場合、以下を行ないます。

If the recover wouldn't be able to recover all rows from a previous completed statement and you didn't specify FORCE as an option to myisam-recover, then the automatic repair will abort with an error message in the error file:

Error: Couldn't repair table: test.g00pages

この FORCE を使用した場合には、エラーメッセージは以下のようになります:

Warning: Found 344 of 354 rows when repairing ./test/g00pages

もしあなたが自動修復を BACKUP で実行しているなら、 あなたは、データベースのディレクトリから `tablename-datetime.BAK' のようなファイルを自動的にバックアップ メディアに移動する cron スクリプトを作るべきです。

See section mysqld コマンド行オプション.

Space Needed for Keys

MySQL can support different index types, but the normal type is ISAM or MyISAM. これらは B-tree index を使用します。インデックスファイルのサイズは、 (key_length+4)/0.67 でおおざっぱに計算できます。 (This is for the worst case when all keys are inserted in sorted order and we don't have any compressed keys.)

文字インデックスは圧縮されます。 If the first index part is a string, it will also be prefix compressed. Space compression makes the index file smaller than the above figures if the string column has a lot of trailing space or is a VARCHAR column that is not always used to the full length. Prefix compression is used on keys that start with a string. Prefix compression helps if there are many strings with an identical prefix.

In MyISAM tables, you can also prefix compress numbers by specifying PACK_KEYS=1 when you create the table. This helps when you have many integer keys that have an identical prefix when the numbers are stored high-byte first.

MyISAM Table Formats

MyISAM supports 3 different table types. Two of them are chosen automatically depending on the type of columns you are using. The third, compressed tables, can only be created with the myisampack tool.

When you CREATE or ALTER a table you can for tables that doesn't have BLOBs force the table format to DYNAMIC or FIXED with the ROW_FORMAT=# table option. In the future you will be able to compress/decompress tables by specifying ROW_FORMAT=compressed | default to ALTER TABLE. See section CREATE TABLE 構文.

Static (Fixed-length) Table Characteristics

This is the default format. It's used when the table contains no VARCHAR, BLOB, or TEXT columns.

このフォーマットは、最も単純、かつ、安全なフォーマットです。 これは, Disk 上に作られるテーブルの中で、最も速いフォーマットでもあります。 これはディスク上のデータを見つけやすいからです。 When looking up something with an index and static format it is very simple. Just multiply the row number by the row length.

Also, when scanning a table it is very easy to read a constant number of records with each disk read.

The security is evidenced if your computer crashes when writing to a fixed-size MyISAM file, in which case myisamchk can easily figure out where each row starts and ends. So it can usually reclaim all records except the partially written one. Note that in MySQL all indexes can always be reconstructed:

Dynamic Table Characteristics

This format is used if the table contains any VARCHAR, BLOB, or TEXT columns or if the table was created with ROW_FORMAT=dynamic.

この形式は少し複雑です。 なぜならそれぞれのレコードが、レコードがどのぐらいの 長さを持っているかを記録するヘッダーを持っているからです。 One record can also end up at more than one location when it is made longer at an update.

OPTIMIZE tablemyisamchk を使用して、テーブルの フラグメンテーションを修正することが可能です。 If you have static data that you access/change a lot in the same table as some VARCHAR or BLOB columns, it might be a good idea to move the dynamic columns to other tables just to avoid fragmentation:

圧縮テーブルの特徴

これは、myisampack ツール (pack_isamISAM テーブル用)に

MyISAM table problems.

The file format that MySQL uses to store data has been extensively tested, but there are always circumstances that may cause database tables to become corrupted.

壊れた MyISAM テーブル

いくら MyISAM テーブルがとても信頼できるとは言え(SQL文を返す前に テーブルへの変更を全て書き出す)、 以下のような事が起きた場合には、テーブルが壊れるかもしれません:

壊れたテーブルの、典型的な症状は:

CHECK TABLE 命令を使用して、テーブルが OK か否かを 確かめることができます。 See section CHECK TABLE 構文 (3.23.13以上).

REPAIR TABLE で不正なテーブルを修復することが可能です. See section REPAIR TABLE 構文 (3.23.14以上). mysqld が動作していないときに、 myisamchk コマンドを使用して テーブルを修復することも可能です。 myisamchk syntax.

もし多くの不整合がテーブルに起きたならば、 その理由を探すべきです! See section What To Do If MySQL Keeps Crashing.

In this case the most important thing to know is if the table got corrupted if the mysqld died (one can easily verify this by checking if there is a recent row restarted mysqld in the mysqld error file). If this isn't the case, then you should try to make a test case of this. See section Making a Test Case When You Experience Table Corruption.

Clients is using or hasn't closed the table properly

Each MyISAM `.MYI' file has in the header a counter that can be used to check if a table has been closed properly.

If you get the following warning from CHECK TABLE or myisamchk:

# clients is using or hasn't closed the table properly

this means that this counter has come out of sync. This doesn't mean that the table is corrupted, but means that you should at least do a check on the table to verify that it's okay.

The counter works as follows:

In other words, the only ways this can go out of sync are:

MERGE Tables (3.23.25以上)

MERGE tables are new in MySQL Version 3.23.25. The code is still in gamma, but should be resonable stable.

MERGE テーブルは(MRG_MyISAM テーブルとしても知られています) 同一の MyISAM をひとまとめにして使用することができるテーブルです。 そのテーブルの集合体に対しては、SELECT, DELETE, UPDATE のみが可能です。 もし MERGE テーブルを DROP すると、MERGE の 定義だけが破棄されます。

Note that DELETE FROM merge_table used without a WHERE will only clear the mapping for the table, not delete everything in the mapped tables. (We plan to fix this in 4.1).

'identical tables' とは、全てのテーブルが同一のフィールド構造とキーの 情報を有するという意味で使用しています。 You can't merge tables in which the columns are packed differently, doesn't have exactly the same columns, or have the keys in different order. However, some of the tables can be compressed with myisampack. See section myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ.

MERGE テーブルを作成すると、.frm テーブル定義ファイルと .MRG テーブルリストファイルが作成されます。 .MRG はインデックスファイル (.MYI ファイル) の リスト(これらは一つとして扱われる)だけが含まれます。 全ての使用されるテーブルは、同じデータベース内に 存在しなければなりません(MERGEテーブルも同様)。

For the moment, you need to have SELECT, UPDATE, and DELETE privileges on the tables you map to a MERGE table.

MERGE テーブルは以下の問題の解決を助けます:

MERGE の欠点は:

MERGE テーブルを作るときは、UNION(list-of-tables) に、 どのテーブルを一つのようにして扱うかを指定する必要があります。 Optionally you can specify with INSERT_METHOD if you want insert for the MERGE table to happen in the first or last table in the UNION list. もし INSERT_METHODNO を指定しなかったなら、 MERGE テーブルに対する全ての INSERT コマンドはエラーになります。

The following example shows you how to use MERGE tables:

CREATE TABLE t1 (a INT AUTO_INCREMENT PRIMARY KEY, message CHAR(20));
CREATE TABLE t2 (a INT AUTO_INCREMENT PRIMARY KEY, message CHAR(20));
INSERT INTO t1 (message) VALUES ("Testing"),("table"),("t1");
INSERT INTO t2 (message) VALUES ("Testing"),("table"),("t2");
CREATE TABLE total (a INT AUTO_INCREMENT PRIMARY KEY, message CHAR(20))
             TYPE=MERGE UNION=(t1,t2) INSERT_METHOD=LAST;

直接、手動で `.MRG' ファイルを作ることも可能です:

shell> cd /mysql-data-directory/current-database
shell> ls -1 t1.MYI t2.MYI > total.MRG
shell> mysqladmin flush-tables

Now you can do things like:

mysql> SELECT * FROM total;
+---+---------+
| a | message |
+---+---------+
| 1 | Testing |
| 2 | table   |
| 3 | t1      |
| 1 | Testing |
| 2 | table   |
| 3 | t2      |
+---+---------+

Note that the a column, though declared as PRIMARY KEY, is not really unique, as MERGE table cannot enforce uniqueness over a set of underlying MyISAM tables.

To remap a MERGE table you can do one of the following:

MERGE Table Problems

The following are the known problems with MERGE tables:

ISAM Tables

You can also use the deprecated ISAM table type. This will disappear rather soon (probably in MySQL 5.0) because MyISAM is a better implementation of the same thing. ISAM uses a B-tree index. The index is stored in a file with the `.ISM' extension, and the data is stored in a file with the `.ISD' extension. You can check/repair ISAM tables with the isamchk utility. See section Using myisamchk for Crash Recovery.

ISAM has the following features/properties:

Most of the things true for MyISAM tables are also true for ISAM tables. See section MyISAM テーブル (3.23.0以上). The major differences compared to MyISAM tables are:

If you want to convert an ISAM table to a MyISAM table so that you can use utilities such as mysqlcheck, use an ALTER TABLE statement:

mysql> ALTER TABLE tbl_name TYPE = MYISAM;

The embedded MySQL versions doesn't support ISAM tables.

HEAP Tables (3.23.0以上)

HEAP テーブルは hashed index を使用し、メモリ内に保存されます。 これはとても速くなりますが、もし MySQL がクラッシュする時にはその内容が 全て失われます。 HEAP はテンポラリのテーブルとしてはとても便利です!

MySQL 内部 HEAP テーブルは、100% ダイナッミック・ハッシングを 使用しています(オーバーフローエリア無しに)。 There is no extra space needed for free lists. HEAP tables also don't have problems with delete + inserts, which normally is common with hashed tables:

mysql> CREATE TABLE test TYPE=HEAP SELECT ip,SUM(downloads) AS down
    ->                   FROM log_table GROUP BY ip;
mysql> SELECT COUNT(ip),AVG(down) FROM test;
mysql> DROP TABLE test;

Here are some things you should consider when you use HEAP tables:

HEAP テーブル内の1レコードに必要とされるメモリは:

SUM_OVER_ALL_KEYS(max_length_of_key + sizeof(char*) * 2)
+ ALIGN(length_of_row+1, sizeof(char*))

sizeof(char*) is 4 on 32-bit machines and 8 on 64-bit machines.

InnoDB テーブル (3.23.6以上)

InnoDB テーブル 概要

InnoDB provides MySQL with a transaction-safe (ACID compliant) storage engine with commit, rollback, and crash recovery capabilities. InnoDB does locking on row level and also provides an Oracle-style consistent non-locking read in SELECTs. These features increase multiuser concurrency and performance. There is no need for lock escalation in InnoDB, because row level locks in InnoDB fit in very small space. InnoDB テーブルは MySQL のテーブルタイプの中では初めて、 FOREIGN KEY 制約 をサポートします。

InnoDB has been designed for maximum performance when processing large data volumes. Its CPU efficiency is probably not matched by any other disk-based relational database engine.

Technically, InnoDB is a complete database backend placed under MySQL. InnoDB has its own buffer pool for caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace, which may consist of several files. This is different from, for example, MyISAM tables where each table is stored as a separate file. InnoDB tables can be of any size also on those operating systems where file-size is limited to 2 GB.

最新の InnoDB についての情報は http://www.innodb.com/. The most up-to-date version of the InnoDB manual is always placed there, and you can also order commercial licenses and support for InnoDB.

InnoDB is currently (October 2001) used in production at several large database sites requiring high performance. The famous Internet news site Slashdot.org runs on InnoDB. Mytrix, Inc. stores over 1 TB of data in InnoDB, and another site handles an average load of 800 inserts/updates per second in InnoDB.

InnoDB は バージョン 3.23.34a から、 MySQL のソース配布に含まれるようになり、 そして、MySQL-max バイナリで有効になりました。 For Windows the -Max binaries are contained in the standard distribution.

If you have downloaded a binary version of MySQL that includes support for InnoDB, simply follow the instructions of the MySQL manual for installing a binary version of MySQL. If you already have MySQL-3.23 installed, then the simplest way to install MySQL -Max is to replace the server executable `mysqld' with the corresponding executable in the -Max distribution. MySQL and MySQL -Max differ only in the server executable. See section Installing a MySQL Binary Distribution.

InnoDB をサポートするように MySQL をコンパイルするには、MySQL-3.23.34a 以上をダウンロードし、 --with-innodb オプションで MySQL を configure します。 See section MySQL ソースディストリビューションのインストール.

cd /path/to/source/of/mysql-3.23.37
./configure --with-innodb

InnoDB を使用するためには、`my.cnf'`my.ini' ファイルに InnoDB 起動オプションを指定しなくてはなりません。 必要最低限の変更は、 [mysqld] セクションに以下のラインを加えることです

innodb_data_file_path=ibdata:30M

but to get good performance it is best that you specify options as recommended. See section InnoDB 起動オプション.

InnoDB is distributed under the GNU GPL License Version 2 (of June 1991). In the source distribution of MySQL, InnoDB appears as a subdirectory.

InnoDB 起動オプション

MySQL-3.23.37 から、オプションの接頭語が innobase_... から innodb_... に変わりました!

MySQL-Max-3.23 で InnoDB テーブルを使用するためには、 設定ファイル `my.cnf' (Windows では `my.ini') の [mysqld] セクションに設定をしなくてはなりません。 See section `my.cnf' オプションファイル.

+ At the minimum, in 3.23 you must specify innodb_data_file_path + where you specify the names and the sizes of datafiles. If you do + not mention innodb_data_home_dir in `my.cnf' the default + is to create these files to the datadir of MySQL. + If you specify innodb_data_home_dir as an empty string, + then you can give absolute paths to your data files in + innodb_data_file_path. In MySQL-4.0 you do not need to specify even innodb_data_file_path: the default for it is to create + an auto-extending 10 MB file `ibdata1' to the datadir of MySQL. (In MySQL-4.0.0 and 4.0.1 the datafile is 64 MB and not auto-extending.) + If you don't want to use InnoDB tables, you can add the + skip-innodb option to your MySQL option file. +

ver.3.23 では、InnoDB を使用するために唯一必要なパラメタは データファイルの大きさを指定する innodb_data_file_path です。 If you do not mention innodb_data_home_dir in `my.cnf' the default is to create these files to the datadir of MySQL. If you specify innodb_data_home_dir as an empty string, then you can give absolute paths to your data files in innodb_data_file_path. In MySQL-4.0 you do not need to specify even innodb_data_file_path: the default for it is to create an auto-extending 10 MB file `ibdata1' to the datadir of MySQL. (In MySQL-4.0.0 and 4.0.1 the datafile is 64 MB and not auto-extending.)

If you don't want to use InnoDB tables, you can add the skip-innodb option to your MySQL option file.

他のオプションはよりよいパフォーマンスを得たい場合に設定します。

Starting from versions 3.23.50 and 4.0.2 InnoDB allows the last datafile on the innodb_data_file_path line to be specified as auto-extending. The syntax for innodb_data_file_path is then the following:

pathtodatafile:sizespecification;pathtodatafile:sizespecification;...
...  ;pathtodatafile:sizespecification[:autoextend[:max:sizespecification]]

If you specify the last datafile with the autoextend option, InnoDB will extend the last datafile if it runs out of free space in the tablespace. The increment is 8 MB at a time. An example:

innodb_data_home_dir =
innodb_data_file_path = /ibdata/ibdata1:100M:autoextend

instructs InnoDB to create just a single datafile whose initial size is 100 MB and which is extended in 8 MB blocks when space runs out. If the disk becomes full you may want to add another data file to another disk, for example. Then you have to look the size of `ibdata1', round the size downward to the closest multiple of 1024 * 1024 bytes (= 1 MB), and specify the rounded size of `ibdata1' explicitly in innodb_data_file_path. After that you can add another datafile:

innodb_data_home_dir =
innodb_data_file_path = /ibdata/ibdata1:988M;/disk2/ibdata2:50M:autoextend

Be cautious on filesystems where the maximum file-size is 2 GB! InnoDB is not aware of the OS maximum file-size. On those filesystems you might want to specify the max size for the datafile:

innodb_data_home_dir =
innodb_data_file_path = /ibdata/ibdata1:100M:autoextend:max:2000M

A simple `my.cnf' example. Suppose you have a computer with 128 MB RAM and one hard disk. Below is an example of possible configuration parameters in `my.cnf' or `my.ini' for InnoDB. We assume you are running MySQL-Max-3.23.50 or later, or MySQL-4.0.2 or later. This example suits most users, both on Unix and Windows, who do not want to distribute InnoDB datafiles and log files on several disks. This creates an auto-extending data file `ibdata1' and two InnoDB log files `ib_logfile0' and `ib_logfile1' to the datadir of MySQL (typically `/mysql/data'). Also the small archived InnoDB log file `ib_arch_log_0000000000' ends up in the datadir.

[mysqld]
# You can write your other MySQL server options here
# ...
#                                  Data file(s) must be able to
#                                  hold your data and indexes.
#                                  Make sure you have enough
#                                  free disk space.
innodb_data_file_path = ibdata1:10M:autoextend
#                                  Set buffer pool size to
#                                  50 - 80 % of your computer's
#                                  memory
set-variable = innodb_buffer_pool_size=70M
set-variable = innodb_additional_mem_pool_size=10M
#                                  Set the log file size to about
#                                  25 % of the buffer pool size
set-variable = innodb_log_file_size=20M
set-variable = innodb_log_buffer_size=8M
#                                  Set ..flush_log_at_trx_commit
#                                  to 0 if you can afford losing
#                                  some last transactions 
innodb_flush_log_at_trx_commit=1

Check that the MySQL server has the rights to create files in datadir.

Note that datafiles must be < 2G in some file systems! The combined size of the log files must be < 4G. The combined size of datafiles must be >= 10 MB.

When you for the first time create an InnoDB database, it is best that you start the MySQL server from the command prompt. Then InnoDB will print the information about the database creation to the screen, and you see what is happening. See below next section what the printout should look like. For example, in Windows you can start `mysqld-max.exe' with:

your-path-to-mysqld>mysqld-max --console

Where to put `my.cnf' or `my.ini' in Windows? The rules for Windows are the following:

Where to specify options in Unix? On Unix `mysqld' reads options from the following files, if they exist, in the following order:

`COMPILATION_DATADIR' is the MySQL data directory which was specified as a ./configure option when `mysqld' was compiled (typically `/usr/local/mysql/data' for a binary installation or `/usr/local/var' for a source installation).

If you are not sure from where `mysqld' reads its `my.cnf' or `my.ini', you can give the path as the first command-line option to the server: mysqld --defaults-file=your_path_to_my_cnf.

InnoDB forms the directory path to a datafile by textually catenating innodb_data_home_dir to a datafile name or path in innodb_data_file_path, adding a possible slash or backslash in between if needed. If the keyword innodb_data_home_dir is not mentioned in `my.cnf' at all, the default for it is the 'dot' directory `./' which means the datadir of MySQL.

An advanced `my.cnf' example. あなたの機械が Linux で 512M の RAM と 20GB のハードディスクだと仮定します。 (ディレクトリパスは `/', `/dr2', `/dr3') 以下はその場合の `my.cnf' の InnoDB パラメターの例です.

Note that InnoDB does not create directories: you have to create them yourself. Use the Unix or MS-DOS mkdir command to create the data and log group home directories.

[mysqld]
# You can write your other MySQL server options here
# ...
innodb_data_home_dir =
#                                  Data files must be able to
#                                  hold your data and indexes
innodb_data_file_path = /ibdata/ibdata1:2000M;/dr2/ibdata/ibdata2:2000M:autoextend
#                                  Set buffer pool size to
#                                  50 - 80 % of your computer's
#                                  memory, but make sure on Linux
#                                  x86 total memory usage is
#                                  < 2 GB
set-variable = innodb_buffer_pool_size=1G
set-variable = innodb_additional_mem_pool_size=20M
innodb_log_group_home_dir = /dr3/iblogs
#                                  .._log_arch_dir must be the same
#                                  as .._log_group_home_dir
innodb_log_arch_dir = /dr3/iblogs
set-variable = innodb_log_files_in_group=3
#                                  Set the log file size to about
#                                  15 % of the buffer pool size
set-variable = innodb_log_file_size=150M
set-variable = innodb_log_buffer_size=8M
#                                  Set ..flush_log_at_trx_commit to
#                                  0 if you can afford losing
#                                  some last transactions 
innodb_flush_log_at_trx_commit=1
set-variable = innodb_file_io_threads=4
set-variable = innodb_lock_wait_timeout=50
#innodb_flush_method=fdatasync
#innodb_fast_shutdown=1
#set-variable = innodb_thread_concurrency=5

Note that we have placed the two datafiles on different disks. InnoDB will fill the tablespace formed by the datafiles from bottom up. In some cases it will improve the performance of the database if all data is not placed on the same physical disk. Putting log files on a different disk from data is very often beneficial for performance. You can also use raw disk partitions (raw devices) as datafiles. In some Unixes they speed up I/O. See the manual section on InnoDB file space management about how to specify them in `my.cnf'.

Warning: on Linux x86 you must be careful you do not set memory usage too high. glibc will allow the process heap to grow over thread stacks, which will crash your server. It is a risk if the value of

innodb_buffer_pool_size + key_buffer +
max_connections * (sort_buffer + read_buffer_size) + max_connections * 2 MB

is close to 2 GB or exceeds 2 GB. Each thread will use a stack (often 2 MB, but in MySQL AB binaries only 256 kB) and in the worst case also sort_buffer + read_buffer_size additional memory.

How to tune other `mysqld' server parameters? Typical values which suit most users are:

skip-locking
set-variable = max_connections=200
set-variable = read_buffer_size=1M
set-variable = sort_buffer=1M
#                                  Set key_buffer to 5 - 50%
#                                  of your RAM depending on how
#                                  much you use MyISAM tables, but
#                                  keep key_buffer + InnoDB
#                                  buffer pool size < 80% of
#                                  your RAM
set-variable = key_buffer=...

Note that some parameters are given using the numeric `my.cnf' parameter format: set-variable = innodb... = 123, others (string and boolean parameters) with another format: innodb_... = ... .

The meanings of the configuration parameters are the following:

Option Description
innodb_data_home_dir 全ての InnoDB データファイルの、共通トップディレクトリのパス。 If you do not mentioned this option in `my.cnf' the default is the datadir of MySQL. You can specify this also as an empty string, in which case you can use absolute file paths in innodb_data_file_path.
innodb_data_file_path 単一のデータファイル(individual data files)のパスとそのサイズ。 (訳注: innodb は保存すべきデータをいくつかのファイルに分割して書き込みます。 この 'individual data files' は、その、実際にデータを保存している 個々のファイルの事を指しています。) それぞれのデータファイルへのフルパスは、innodb_data_home_dir で指定された パスと連結されることで求められます。 ファイルサイズは メガバイト で与えられ、上記のように 'M' がサイズの後にきます。 ファイルサイズは 4000M より大きくしてはいけません。 ほとんどのオペレーティングシステムでは 2000M より大きなファイルを扱えません。 InnoDB は 'G' の省略形も認識します。 1G は 1024M になります。 バージョン 3.23.44 からは、オペーレーティングシステムが large ファイルを扱えるのであれば、4GB 以上の指定が可能です。 いくつかのオペレーティングシステムは一つのファイルは 2GB 未満の 制約があります。 データファイルのサイズの合計は、少なくとも、10MB 以上必要です。
innodb_mirrored_log_groups データベースのために維持しておくログのグループのコピーの数。 現在、これは 1 しかセットできません。
innodb_log_group_home_dir InnoDB ログファイルのディレクトリのパス。
innodb_log_files_in_group log group 内の、ログファイルの数。 InnoDB はログファイルを、ローテートするやり方で書きます。 3 が推奨値です。
innodb_log_file_size log group 内の、各ログファイルの大きさ(Mega bytes)。 Sensible values range from 1M to 1/nth of the size of the buffer pool specified below, where n is the number of log files in the group. The bigger the value, the less checkpoint flush activity is needed in the buffer pool, saving disk I/O. But bigger log files also mean that recovery will be slower in case of a crash. The combined size of log files must be < 4 GB on 32-bit computers.
innodb_log_buffer_size InnoDB が、disk上のログファイルにログを書き出すために使用する、 バッファのサイズ。 Sensible values range from 1M to 8M. A big log buffer allows large transactions to run without a need to write the log to disk until the transaction commit. Thus, if you have big transactions, making the log buffer big will save disk I/O.
innodb_flush_log_at_trx_commit Normally this is set to 1, meaning that at a transaction commit the log is flushed to disk, and the modifications made by the transaction become permanent, and survive a database crash. If you are willing to compromise this safety, and you are running small transactions, you may set this to 0 to reduce disk I/O to the logs.
innodb_log_arch_dir The directory where fully written log files would be archived if we used log archiving. *現在のところ、これには、 innodb_log_group_home_dir と同じ値をセットしなくてはなりません。*
innodb_log_archive This value should currently be set to 0. As recovery from a backup is done by MySQL using its own log files, there is currently no need to archive InnoDB log files.
innodb_buffer_pool_size InnoDB がデータやテーブルのインデックスををキャッシュするために使用する メモリのサイズ。 大きな値をセットすると、テーブルのデータへのアクセスに必要なディスク i/o が少なくなります。 データベースサーバ専用のマシンでは、このパラメタを物理メモリの 80% まで セットしてもかまいません。 物理メモリの競合がオペレーティングシステムのページングの原因に なるかもしれないので、あまりに大きすぎる値は与えないように。
innodb_additional_mem_pool_size Size of a memory pool InnoDB uses to store data dictionary information and other internal data structures. A sensible value for this might be 2M, but the more tables you have in your application the more you will need to allocate here. If InnoDB runs out of memory in this pool, it will start to allocate memory from the operating system, and write warning messages to the MySQL error log.
innodb_file_io_threads Number of file I/O threads in InnoDB. Normally, this should be 4, but on Windows disk I/O may benefit from a larger number.
innodb_lock_wait_timeout Timeout in seconds an InnoDB transaction may wait for a lock before being rolled back. InnoDB は自動的にトランザクションのデッド・ロックがテーブルに起きた事 を感知し、そのトランザクションをロール・バックします。 If you use LOCK TABLES command, or other transaction-safe storage engines than InnoDB in the same transaction, then a deadlock may arise which InnoDB cannot notice. In cases like this the timeout is useful to resolve the situation.
innodb_flush_method (3.23.40 以上からの機能.) The default value for this is fdatasync. Another option is O_DSYNC.

InnoDB テーブルの保存先の作成

あなたが MySQL を既にインストールしており、`my.cnf' には InnoDB configuration パラメタが記述されていると仮定します。 MySQL を起動する前に、 あなたが指定している InnoDB データファイルとログファイルを保存する ディレクトリが存在するか、 そして、それらのディレクトリのパーミッションが正しいかを 確認するべきです。 InnoDB はディレクトリを自動では作成できません。ファイルのみです。 データとログファイルを保存するために十分なディスクの空きがあるかも チェックしてください。

MySQL を起動すると、InnoDB は data file と log file を作成します。 InnoDB は以下のようなメッセージを出力します:

~/mysqlm/sql > mysqld
InnoDB: The first specified datafile /home/heikki/data/ibdata1
did not exist:
InnoDB: a new database to be created!
InnoDB: Setting file /home/heikki/data/ibdata1 size to 134217728
InnoDB: Database physically writes the file full: wait...
InnoDB: datafile /home/heikki/data/ibdata2 did not exist:
new to be created
InnoDB: Setting file /home/heikki/data/ibdata2 size to 262144000
InnoDB: Database physically writes the file full: wait...
InnoDB: Log file /home/heikki/data/logs/ib_logfile0 did not exist:
new to be created
InnoDB: Setting log file /home/heikki/data/logs/ib_logfile0 size to 5242880
InnoDB: Log file /home/heikki/data/logs/ib_logfile1 did not exist:
new to be created
InnoDB: Setting log file /home/heikki/data/logs/ib_logfile1 size to 5242880
InnoDB: Log file /home/heikki/data/logs/ib_logfile2 did not exist:
new to be created
InnoDB: Setting log file /home/heikki/data/logs/ib_logfile2 size to 5242880
InnoDB: Started
mysqld: ready for connections

新しく InnoDB データベースが、これで作成されました。 mysql のような MySQL クライアントを使用して、MySQL サーバに 接続することが可能です。 `mysqladmin shutdown' で MySQL をシャットダウンしたときには、 InnoDB は以下のようなメッセージを出力します:

010321 18:33:34  mysqld: Normal shutdown
010321 18:33:34  mysqld: Shutdown Complete
InnoDB: Starting shutdown...
InnoDB: Shutdown completed

You can now look at the datafiles and logs directories and you will see the files created. ログディレクトリには、`ib_arch_log_0000000000' という名前の、 小さなファイルが含まれているはずです。 That file resulted from the database creation, after which InnoDB switched off log archiving. MySQL が次回に起動したとき、出力は次のようになります:

~/mysqlm/sql > mysqld
InnoDB: Started
mysqld: ready for connections

InnoDB データベース作成に失敗した場合

If InnoDB prints an operating system error in a file operation, usually the problem is one of the following:

もし InnoDB database 作成時になにか問題が起きたならば、 InnoDB によって作成された全てのファイルを削除すべきです。 This means all datafiles, all log files, the small archived log file, and in the case you already did create some InnoDB tables, delete also the corresponding `.frm' files for these tables from the MySQL database directories. Then you can try the InnoDB database creation again.

InnoDB テーブルの作成

mysql test として MySQL クライアントを実行したとします。 InnoDB 形式のテーブルを作成するためには、あなたは SQL コマンドの テーブル作成文に、TYPE = InnoDB を指定しなくてはなりません。

CREATE TABLE CUSTOMER (A INT, B CHAR (20), INDEX (A)) TYPE = InnoDB;

この SQL コマンドは、`my.cnf' で定義された InnoDB のテーブル空間に存在する データファイル内に、一つのテーブルと、一つのインデックス (A フィールドに張られた)を作成します。 MySQL は `CUSTOMER.frm' ファイルを MuSQL データベースディレクトリ `test' に作成します。 内部では、InnoDB は、InnoDB 自身のデータディレクトリをもち、 そこに 'test/CUSTOMER' テーブルのエントリを追加します。 よって、MySQL 内の違うデータベース内に、同じ CUSTOMER という 名前を持つテーブルを作成することが可能で、もちろんこの名前は、 InnoDB 内でも他とは衝突しません。

MySQL の table status コマンドを使用して、TYPE = InnoDB で作成した テーブル全てに対して、InnoDB のテーブル空間の未使用量が どれくらいあるかを出すことができます。 テーブル空間の未使用領域の総量は、SHOW で出力された テーブルの comment セクションに現われます。 例:

SHOW TABLE STATUS FROM test LIKE 'CUSTOMER'

SHOW を使用して得られた InnoDB のテーブルの情報は概算です; それらは SQL オプティマイゼイションで使用されます。 ただし、テーブルとインデックスに割り当てられているサイズ(bytes)は正確です。

MyISAM テーブルを InnoDB テーブルに変換

InnoDB does not have a special optimization for separate index creation. Therefore it does not pay to export and import the table and create indexes afterwards. 素早くテーブルを InnoDB に変換する方法は、 InnoDB に直接 insert することです。 テーブルの変換には、ALTER TABLE ... TYPE=INNODB を使用するか、 空の InnoDB テーブルを作成してデータを INSERT INTO ... SELECT * FROM ... でインサートします。

insert 時においては、大きなテーブルの場合は、いくつかにテーブルを 分割して行うとよいでしょう:

INSERT INTO newtable SELECT * FROM oldtable
   WHERE yourkey > something AND yourkey <= somethingelse;

全てのデータが挿入できたら、テーブル名を変更します。

大きなテーブルを変換している間は、InnoDB のバッファプールサイズを 大きくすることで、disk I/O を軽減できます。 ただし、物理メモリの 80% 以上をバッファに割り当てないように。 InnoDB log ファイルのサイズもログのバッファも大きく取るべきです。

確実に、テーブル空間より大きくならないようにします; InnoDB テーブルは MyISAM テーブルよりも多くの disk を使用します。 もし ALTER TABLE が取っている領域よりも超えた場合には、 ロール・バックが開始されます。 これは ディスク・バウンドのために (大きなファイルならば) 数時間かかるかもしれません。 インサートする場合には、InnoDB は インサート・バッファ を使用します。 これはセカンダリ・インデックス・レコードをインデックスに一度にマージ させるために使用されます。 このため多くの disk I/O が節約されます。 ロール・バックにおいては、インサートで使用されるようなメカニズムは無く、 ロール・バックは、インサートの 約30倍、時間がかかります。

このような手に負えないロール・バックのばあい、 もし、価値のあるデータがあなたの InnoDB データベース内に一つもなければ、 データベースのプロセスをキルして全ての InnoDB データファイルとログファイルを 消去し、全ての InnoDB テーブルの `.frm' ファイルを消し、 そしてもう一度試みる方が良いでしょう。 とてつもなく多くの disk I/O が完了するのを待つよりも。

外部キー制約 (Foreign Key Constraints) (3.23.44以上)

InnoDB バージョン 3.23.43b 以上では foreign key constraints を持ちます. InnoDB is the first MySQL table type which allows you to define foreign key constraints to guard the integrity of your data.

The syntax of a foreign key constraint definition in InnoDB:

[CONSTRAINT symbol] FOREIGN KEY (index_col_name, ...)
                  REFERENCES table_name (index_col_name, ...)
                  [ON DELETE {CASCADE | SET NULL | NO ACTION
                              | RESTRICT}]
                  [ON UPDATE {CASCADE | SET NULL | NO ACTION
                              | RESTRICT}]

Both tables have to be InnoDB type and there must be an index where the foreign key and the referenced key are listed as the FIRST columns. InnoDB does not auto-create indexes on foreign keys or referenced keys: you have to create them explicitly.

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and the signedness of integer types has to be the same. The length of string types need not be the same. If you specify a SET NULL action, make sure you have not declared the columns in the child table NOT NULL.

If MySQL gives the error number 1005 from a CREATE TABLE statement, and the error message string refers to errno 150, then the table creation failed because a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails and it refers to errno 150, that means a foreign key definition would be incorrectly formed for the altered table.

Starting from version 3.23.50 you can also associate the ON DELETE CASCADE or ON DELETE SET NULL clause with the foreign key constraint. Starting from version 4.0.8 you can use also similar ON UPDATE actions.

If ON DELETE CASCADE is specified, and a row in the parent table is deleted, then InnoDB automatically deletes also all those rows in the child table whose foreign key values are equal to the referenced key value in the parent row. If ON DELETE SET NULL is specified, the child rows are automatically updated so that the columns in the foreign key are set to the SQL NULL value.

Starting from version 3.23.50, InnoDB does not check foreign key constraints on those foreign key or referenced key values which contain a NULL column.

Starting from version 3.23.50 the InnoDB parser allows you to use backquotes (`) around table and column names in the FOREIGN KEY ... REFERENCES ... clause but the InnoDB parser is not yet aware of the option lower_case_table_names you can specify in `my.cnf'.

例:

CREATE TABLE parent(id INT NOT NULL, PRIMARY KEY (id)) TYPE=INNODB;
CREATE TABLE child(id INT, parent_id INT, INDEX par_ind (parent_id),
             FOREIGN KEY (parent_id) REFERENCES parent(id)
             ON DELETE SET NULL
) TYPE=INNODB;

(訳注: 両方のテーブルとも、InnoDB でなくてはなりません。 さらに foreign key と the referenced key に指定される項目は、 インデックス中の定義の中では、最初の項目として、 指定されていなければなりません。 上記の例では、FOREIGN KEY で指定されている V, U は、 インデックスの最初の項目に指定されています。)

Starting from version 3.23.50 InnoDB allows you to add a new foreign key constraint to a table through

ALTER TABLE yourtablename
ADD [CONSTRAINT symbol] FOREIGN KEY (...) REFERENCES anothertablename(...)
[on_delete_and_on_update_actions]

Remember to create the required indexes first, though. In InnoDB versions < 3.23.50 ALTER TABLE or CREATE INDEX should not be used in connection with tables which have foreign key constraints or which are referenced in foreign key constraints: Any ALTER TABLE removes all foreign key constrainst defined for the table. You should not use ALTER TABLE to the referenced table either, but use DROP TABLE and CREATE TABLE to modify the schema. When MySQL does an ALTER TABLE it may internally use RENAME TABLE, and that will confuse the foreign key costraints which refer to the table. A CREATE INDEX statement is in MySQL processed as an ALTER TABLE, and these restrictions apply also to it.

When doing foreign key checks InnoDB sets shared row level locks on child or parent records it has to look at. InnoDB checks foreign key constraints immediately: the check is not deferred to transaction commit.

InnoDB allows you to drop any table even though that would break the foreign key constraints which reference the table. When you drop a table the constraints which were defined in its create statement are also dropped.

If you re-create a table which was dropped, it has to have a definition which conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated above. If these are not satisfied, MySQL returns error number 1005 and refers to errno 150 in the error message string.

Starting from version 3.23.50 InnoDB returns the foreign key definitions of a table when you call

SHOW CREATE TABLE yourtablename

Then also `mysqldump' produces correct definitions of tables to the dump file, and does not forget about the foreign keys.

You can also list the foreign key constraints for a table T with

SHOW TABLE STATUS FROM yourdatabasename LIKE 'T'

The foreign key constraints are listed in the table comment of the output.

InnoDB データとログの追加と削除

バージョン 3.23.50以上の3.23, 4.0.2以上では InnoDB の最後のデータファイルを autoextend に指定することが可能です。 それ未満のバージョンでは、データファイルを追加することで テーブルの空間を大きくすることが可能です。 テーブルの空間を大きくするためには、新しいデータファイルを追加します。 これを行なうには、MySQL サーバーを一度シャットダウンし、 `my.cnf' ファイルを編集して新しいデータファイルを innodb_data_file_path に追加し、MySQL サーバを起動します。

今のところ、データファイルを InnoDB から削除することはできません。 データベースのサイズを小さくするには、 一度 mysqldump でテーブルをダンプし、 新しくデータベースを作成し、ダンプしたテーブルを取り込みます。

もし InnoDB のログファイルのサイズを変更したいならば、 MySQL サーバを停止しなくてはなりません(エラー無しで確実に止まるようにしてください)。 なにかシャットダウン時に問題があった場合には、 古いログファイルを安全な場所にコピーし、 データベースの修復をしましょう。 そして、古いログファイルを log ファイルのディレクトリから消去し、 `my.cnf' ファイルを編集した後、MySQL サーバを起動します。 InnoDB は 新しいログファイルを作成したことを告げるでしょう。

InnoDB データベースのバックアップと修復

The key to safe database management is taking regular backups.

InnoDB Hot Backup is an online backup tool you can use to backup your InnoDB database while it is running. InnoDB Hot Backup does not require you to shut down your database and it does not set any locks or disturb your normal database processing. InnoDB Hot Backup is a non-free additional tool which is not included in the standard MySQL distribution. See the InnoDB Hot Backup homepage http://www.innodb.com/hotbackup.html for detailed information and screenshots.

If you are able to shut down your MySQL server, then to take a 'binary' backup of your database you have to do the following:

上のバイナリバックアップに加えて、`mysqldump' で通常のテーブルの ダンプも取るべきです。 この理由は、バイナリファイルはあなたの知らないところで おかしくなっているかもしれないからです。 テキストファイルのダンプされたテーブルは人間が読むことができ、 そしてバイナリファイルよりもずっと簡素です。 ダンプされたファイルからテーブルのおかしくなった箇所を見つけるのは容易で、 そして、致命的なデータの不正を少なくするチャンスでもあります。

データベースのバイナリバックアップと同時に、ダンプを取ることは、 よい考えです。 全テーブルを現在の状況と矛盾無くダンプするためには、全てのクライアントを データベースからシャット・アウトするべきです。 Then you can take the binary backup, and you will then have a consistent snapshot of your database in two formats.

To be able to recover your InnoDB database to the present from the binary backup described above, you have to run your MySQL database with the general logging and log archiving of MySQL switched on. Here by the general logging we mean the logging mechanism of the MySQL server which is independent of InnoDB logs.

MySQL サーバプロセスのクラッシュからのリカバリを行なうには、 MySQL をリスタートすることがただ一つの方法です。 InnoDB は自動で ログ をチェックし、データベースの roll-forward を 行ないます。 InnoDB は、クラッシュ時にコッミトされていないトランザクションを 自動的にロールバックします。 リカバリの間、InnoDB は以下のような出力をします:

~/mysqlm/sql > mysqld
InnoDB: Database was not shut down normally.
InnoDB: Starting recovery from log files...
InnoDB: Starting log scan based on checkpoint at
InnoDB: log sequence number 0 13674004
InnoDB: Doing recovery: scanned up to log sequence number 0 13739520
InnoDB: Doing recovery: scanned up to log sequence number 0 13805056
InnoDB: Doing recovery: scanned up to log sequence number 0 13870592
InnoDB: Doing recovery: scanned up to log sequence number 0 13936128
...
InnoDB: Doing recovery: scanned up to log sequence number 0 20555264
InnoDB: Doing recovery: scanned up to log sequence number 0 20620800
InnoDB: Doing recovery: scanned up to log sequence number 0 20664692
InnoDB: 1 uncommitted transaction(s) which must be rolled back
InnoDB: Starting rollback of uncommitted transactions
InnoDB: Rolling back trx no 16745
InnoDB: Rolling back of trx no 16745 completed
InnoDB: Rollback of uncommitted transactions completed
InnoDB: Starting an apply batch of log records to the database...
InnoDB: Apply batch completed
InnoDB: Started
mysqld: ready for connections

If your database gets corrupted or your disk fails, you have to do the recovery from a backup. In the case of corruption, you should first find a backup which is not corrupted. From a backup do the recovery from the general log files of MySQL according to instructions in the MySQL manual.

Checkpoints

InnoDB は fuzzy checkpoint と呼ばれる チェックポイントのメカニズムを持っています。 InnoDB will flush modified database pages from the buffer pool in small batches, there is no need to flush the buffer pool in one single batch, which would in practice stop processing of user SQL statements for a while.

クラッシュ・リカバリ時には、InnoDB はログファイルに書かれた チェックポイント・ラベルを見ます。 データベースのディスク・イメージ上にそのラベルが反映させられる前に、 それはデータベースの全ての変更を知っています。 It knows that all modifications to the database before the label are already present on the disk image of the database. Then InnoDB scans the log files forward from the place of the checkpoint applying the logged modifications to the database.

InnoDB はログファイルを循環して使用します。 全てのコミットされた変更分(変更だから当然バッファプール内のデータベースのページとディスク上のイメージが違う)は、InnoDB がリカバリを実行しなければならない時に、ログファイルに存在しなければなりません。(でなければリカバリを行なうことができません。) これは、InnoDB がログファイルを循環的に再利用しようとした時に、ディスク上のデータベースページのイメージに、既にログファイルに記録されていた変更分が含まれていなければならないということです。 言い換えれば、InnoDB はチェックポイントを作成しなければならず、そしてこれは変更されたデータベースのページをディスクにフラッシュすることをしばしば引き起こすことになります。 InnoDB writes to the log files in a circular fashion. All committed modifications which make the database pages in the buffer pool different from the images on disk must be available in the log files in case InnoDB has to do a recovery. This means that when InnoDB starts to reuse a log file in the circular fashion, it has to make sure that the database page images on disk already contain the modifications logged in the log file InnoDB is going to reuse. In other words, InnoDB has to make a checkpoint and often this involves flushing of modified database pages to disk.

上に述べた事柄は、なぜログファイルをとても大きく作成することが チェックポイント作成において disk I/O を減らすことになるのかの理由です。 The above explains why making your log files very big may save disk I/O in checkpointing. It can make sense to set the total size of the log files as big as the buffer pool or even bigger. The drawback in big log files is that crash recovery can last longer because there will be more log to apply to the database.

InnoDB データベースを他の機械に移動する

InnoDB データとログファイルは、 もし、その機械の浮動小数点数のフォーマットが同じであれば、 全プラットフォームでバイナリ互換を持ちます。 InnoDB は、単純に、関連ファイルを全てコピーすることで移動可能です。 (関連ファイルは前節で述べられています) 

InnoDB データベースは、全てのファイルを単純にコピーするだけで、 移動が可能です。 ファイルは、前述のデータベースのバックアップの節で 述べたものです。 もし浮動小数点数のフォーマットが違う機械であったとしても、 テーブルに FLOATDOUBLE の型を使用していないのであれば、 手順は同じです: すなわち単にファイルをコピーするだけです。 もし浮動小数点数のフォーマットが違う機械で、テーブルに 浮動小数点数を保存している場合は、 `mysqldump'`mysqlimport' コマンドを使用して テーブルを移動しなくてはなりません。

A performance tip is to switch off auto-commit mode when you import data into your database, assuming your tablespace has enough space for the big rollback segment the big import transaction will generate. Do the commit only after importing a whole table or a segment of a table.

InnoDB Transaction Model

In the InnoDB transaction model the goal has been to combine the best properties of a multi-versioning database to traditional two-phase locking. InnoDB does locking on row level and runs queries by default as non-locking consistent reads, in the style of Oracle. The lock table in InnoDB is stored so space-efficiently that lock escalation is not needed: typically several users are allowed to lock every row in the database, or any random subset of the rows, without InnoDB running out of memory.

In InnoDB all user activity happens inside transactions. もし、autocommit mode が MySQL で使用されているなら、 それぞれの SQL 文は単一の transaction となります。 MySQL always starts a new connection with the autocommit mode switched on.

もし autocommit mode が SET AUTOCOMMIT = 0 で off にされたなら、 ユーザーは常にトランザクションが可能な状態となります。 もし SQL の COMMIT or ROLLBACK 文を実行すると、 現在のトランザクションは完結し、新しいトランザクションが開始します。 どちらの文も全ての InnoDB のロック(カレントのトランザクションに セットされたロック)を外します。 A COMMIT means that the changes made in the current transaction are made permanent and become visible to other users. A ROLLBACK, on the other hand, cancels all modifications made by the current transaction.

If the connection has AUTOCOMMIT = 1, then the user can still perform a multi-statement transaction by starting it with BEGIN and ending it with COMMIT or ROLLBACK.

In terms of the SQL-1992 transaction isolation levels, the InnoDB default is REPEATABLE READ. Starting from version 4.0.5, InnoDB offers all 4 different transaction isolation levels described by the SQL-1992 standard. You can set the default isolation level for all connections in the [mysqld] section of `my.cnf':

transaction-isolation = {READ-UNCOMMITTED | READ-COMMITTED
                         | REPEATABLE-READ | SERIALIZABLE}

A user can change the isolation level of a single session or all new incoming connections with the

SET [SESSION | GLOBAL] TRANSACTION ISOLATION LEVEL
                       {READ UNCOMMITTED | READ COMMITTED
                        | REPEATABLE READ | SERIALIZABLE}

SQL statement. Note that there are no hyphens in level names in the SQL syntax. If you specify the keyword GLOBAL in the above statement, it will determine the initial isolation level of new incoming connections, but will not change the isolation level of old connections. Any user is free to change the isolation level of his session, even in the middle of a transaction. In versions < 3.23.50 SET TRANSACTION had no effect on InnoDB tables. In versions < 4.0.5 only REPEATABLE READ and SERIALIZABLE were available.

You can query the global and session transaction isolation levels with:

SELECT @@global.tx_isolation;
SELECT @@tx_isolation;

In row level locking InnoDB uses so-called next-key locking. That means that besides index records, InnoDB can also lock the 'gap' before an index record to block insertions by other users immediately before the index record. A next-key lock means a lock which locks an index record and the gap before it. A gap lock means a lock which only locks a gap before some index record.

A detailed description of each isolation level in InnoDB:

Consistent Read

A consistent read means that InnoDB uses its multi-versioning to present to a query a snapshot of the database at a point in time. The query will see the changes made by exactly those transactions that committed before that point of time, and no changes made by later or uncommitted transactions. The exception to this rule is that the query will see the changes made by the transaction itself which issues the query.

If you are running with the default REPEATABLE READ isolation level, then all consistent reads within the same transaction read the snapshot established by the first such read in that transaction. You can get a fresher snapshot for your queries by committing the current transaction and after that issuing new queries.

Consistent read is the default mode in which InnoDB processes SELECT statements in READ COMMITTED and REPEATABLE READ isolation levels. A consistent read does not set any locks on the tables it accesses, and therefore other users are free to modify those tables at the same time a consistent read is being performed on the table.

Locking Reads

consistent read は、いくつかの状況下では好都合ではありません。

あなたが新しいレコードを CHILD テーブルに加えたいとします。 この child はすでに PARENT テーブルにある parent を 確実に持っているものとします。

そしてあなたが PARENT テーブルを読むために、consistent read を 使用するとします。そのテーブル内に、たしかに、その child の parent を 見たとします。

この場合、その child のレコードを安全に CHILD テーブルに 追加することが可能でしょうか?

答えは No 。 なぜなら、あなたが気がつかない内に、 他のユーザーがその parent のレコードを PARENT テーブルから 消してしまうかも知れないからです。

この解決として、SELECT を locking mode で動作させる方法が あります。 LOCK IN SHARE MODE.

SELECT * FROM PARENT WHERE NAME = 'Jones' LOCK IN SHARE MODE;

Performing a read in share mode means that we read the latest available data, and set a shared mode lock on the rows we read. If the latest data belongs to a yet uncommitted transaction of another user, we will wait until that transaction commits. A shared mode lock prevents others from updating or deleting the row we have read. After we see that the above query returns the parent 'Jones', we can safely add his child to table CHILD, and commit our transaction. This example shows how to implement referential integrity in your application code.

Let us look at another example: we have an integer counter field in a table CHILD_CODES which we use to assign a unique identifier to each child we add to table CHILD. Obviously, using a consistent read or a shared mode read to read the present value of the counter is not a good idea, since then two users of the database may see the same value for the counter, and we will get a duplicate key error when we add the two children with the same identifier to the table.

In this case there are two good ways to implement the reading and incrementing of the counter: (1) update the counter first by incrementing it by 1 and only after that read it, or (2) read the counter first with a lock mode FOR UPDATE, and increment after that:

SELECT COUNTER_FIELD FROM CHILD_CODES FOR UPDATE;
UPDATE CHILD_CODES SET COUNTER_FIELD = COUNTER_FIELD + 1;

A SELECT ... FOR UPDATE will read the latest available data setting exclusive locks on each row it reads. Thus it sets the same locks a searched SQL UPDATE would set on the rows.

Next-key Locking: Avoiding the Phantom Problem

row level のロッキングにおいては、InnoDB は next-key locking と呼ばれる アルゴリズムを使用します。 InnoDB does the row level locking so that when it searches or scans an index of a table, it sets shared or exclusive locks on the index records in encounters. Thus the row level locks are more precisely called index record locks.

The locks InnoDB sets on index records also affect the 'gap' before that index record. If a user has a shared or exclusive lock on record R in an index, then another user cannot insert a new index record immediately before R in the index order. This locking of gaps is done to prevent the so-called phantom problem. Suppose I want to read and lock all children with identifier bigger than 100 from table CHILD, and update some field in the selected rows.

SELECT * FROM CHILD WHERE ID > 100 FOR UPDATE;

CHILD テーブルの ID フィールドにインデックスが 張られているとします。 Our query will scan that index starting from the first record where ID is bigger than 100. Now, if the locks set on the index records would not lock out inserts made in the gaps, a new child might meanwhile be inserted to the table. If now I in my transaction execute

SELECT * FROM CHILD WHERE ID > 100 FOR UPDATE;

again, I will see a new child in the result set the query returns. This is against the isolation principle of transactions: a transaction should be able to run so that the data it has read does not change during the transaction. If we regard a set of rows as a data item, then the new 'phantom' child would break this isolation principle.

When InnoDB scans an index it can also lock the gap after the last record in the index. Just that happens in the previous example: the locks set by InnoDB will prevent any insert to the table where ID would be bigger than 100.

You can use next-key locking to implement a uniqueness check in your application: if you read your data in share mode and do not see a duplicate for a row you are going to insert, then you can safely insert your row and know that the next-key lock set on the successor of your row during the read will prevent anyone meanwhile inserting a duplicate for your row. Thus the next-key locking allows you to 'lock' the non-existence of something in your table.

Locks Set by Different SQL Statements in InnoDB

How to cope with deadlocks?

Deadlocks are a classic problem in transactional databases, but they are not dangerous, unless they are so frequent that you cannot run certain transactions at all. Normally you have to write your applications so that they are always prepared to re-issue a transaction if it gets rolled back because of a deadlock.

InnoDB uses automatic row level locking. You can get deadlocks even in the case of transactions which just insert or delete a single row. That is because these operations are not really 'atomic': they automatically set locks on the (possibly several) index records of the row inserted/deleted.

You can cope with deadlocks and reduce the number of them with the following tricks:

Deadlock Detection and Rollback

InnoDB automatically detects a deadlock of transactions and rolls back a transaction or transactions to prevent the deadlock. Starting from version 4.0.5, InnoDB will try to pick small transactions to roll back. The size of a transaction is determined by the number of rows it has inserted, updated, or deleted. Previous to 4.0.5, InnoDB always rolled back the transaction whose lock request was the last one to build a deadlock, that is, a cycle in the waits-for graph of transactions.

InnoDB cannot detect deadlocks where a lock set by a MySQL LOCK TABLES statement is involved, or if a lock set in another storage engine than InnoDB is involved. You have to resolve these situations using innodb_lock_wait_timeout set in `my.cnf'.

When InnoDB performs a complete rollback of a transaction, all the locks of the transaction are released. However, if just a single SQL statement is rolled back as a result of an error, some of the locks set by the SQL statement may be preserved. This is because InnoDB stores row locks in a format where it cannot afterwards know which was set by which SQL statement.

An Example of How the Consistent Read Works in InnoDB

Suppose you are running on the default REPEATABLE READ isolation level. When you issue a consistent read, that is, an ordinary SELECT statement, InnoDB will give your transaction a timepoint according to which your query sees the database. Thus, if transaction B deletes a row and commits after your timepoint was assigned, then you will not see the row deleted. Similarly with inserts and updates.

You can advance your timepoint by committing your transaction and then doing another SELECT.

This is called multi-versioned concurrency control.

                  User A                 User B

              SET AUTOCOMMIT=0;      SET AUTOCOMMIT=0;
time
|             SELECT * FROM t;
|             empty set
|                                    INSERT INTO t VALUES (1, 2);
|
v             SELECT * FROM t;
              empty set
                                     COMMIT;

              SELECT * FROM t;
              empty set;

              COMMIT;

              SELECT * FROM t;
              ---------------------
              |    1    |    2    |
              ---------------------

Thus user A sees the row inserted by B only when B has committed the insert, and A has committed his own transaction so that the timepoint is advanced past the commit of B.

If you want to see the ``freshest'' state of the database, you should use a locking read:

SELECT * FROM t LOCK IN SHARE MODE;

パフォーマンス・チューニング Tips

1. もし Unix `top' や Windows `Task Manager' が CPU 使用率を 70% 未満に 表示している場合、おそらく、disk アクセスに処理が取られています。 とても多くのトランザクションのコミットを作成しているか、 バッファプールが小さいのでしょう。 バッファプールを大きくすれば良くなりますが、しかし、バッファプールは 物理メモリの 80% より大きくしないように。

2. Wrap several modifications into one transaction. InnoDB must flush the log to disk at each transaction commit, if that transaction made modifications to the database. Since the rotation speed of a disk is typically at most 167 revolutions/second, that constrains the number of commits to the same 167/second if the disk does not fool the operating system.

3. If you can afford the loss of some latest committed transactions, you can set the `my.cnf' parameter innodb_flush_log_at_trx_commit to zero. InnoDB tries to flush the log anyway once in a second, though the flush is not guaranteed.

4. Make your log files big, even as big as the buffer pool. When InnoDB has written the log files full, it has to write the modified contents of the buffer pool to disk in a checkpoint. Small log files will cause many unnecessary disk writes. The drawback in big log files is that recovery time will be longer.

5. Also the log buffer should be quite big, say 8 MB.

6. (Relevant from 3.23.39 up.) Linux や Unix のいくつかのバージョンでは、disk のファイルのフラッシュに Unix fdatasync や それに似た方法を使用しますが、 これは驚くほど遅いです。 InnoDB のデフォルトの方法は、fdatasync 関数を使用します。 もしデータベースの書き込みのパフォーマンスに満足しない場合には、 `my.cnf' ファイルで innodb_flush_methodO_DSYNC に セットしてもかまいません。しかし O_DSYNC はほとんどのシステムでは 遅いようです。

7. InnoDB にデータを流し込む場合には、 MySQL の設定が autocommit=1 になっていないようにします。 それぞれの全ての insert が log をディスクにフラッシュすることを要求するからです。 取り込む SQL の最初に

SET AUTOCOMMIT=0;

を追加し、最後に

COMMIT;

を書きます。

もし `mysqldump'--opt オプションで使用しているなら、 上記のように SET AUTOCOMMIT=0; ... COMMIT; でダンプファイルを囲まないでも、 早く InnoDB テーブルにダンプを取り込むことが可能です。

8. 大量のinsertの大きなロールバックに気をつけなさい; InnoDB は insert の時には、disk I/O を少なくするために insert buffer を 使用します。しかし、ロールバックには同じような機構は使用されません。 ロールバック時のディスク・バウンドは、対応するinsertに比べて 30倍の 時間がかかります。 データベースのプロセスを kill することは、何の解決にもなりません。 なぜなら、データベースがスタートアップした時、 再びロールバックが開始されるからです。 制御しきれないロールバックから免れる方法は、 バッファプールを増やすか(こうすればロールバックは CPU-bound でおさまり、速く終わります)、 InnoDB 全体を消し去ってしまうかしかありません。

9. Beware also of other big disk-bound operations. Use DROP TABLE or TRUNCATE (from MySQL-4.0 up) to empty a table, not DELETE FROM yourtable.

10. もしたくさんのレコードをインサートする必要があるならば、 サーバーとクライアントのコミュニケーションのオーバーヘッドを軽減するために、 マルチライン INSERT を使用します:

INSERT INTO yourtable VALUES (1, 2), (5, 5);

この方法は InnoDB だけではなく、他のテーブル型にインサートする時も使用できます。

InnoDB モニタ

バージョン 3.23.41 から、InnoDB は InnoDB Monitor を含むようになりました。 これは InnoDB 内部の状態を表示するものです。 このスイッチを on にすると、MySQL サーバは 15 秒毎に標準出力にデータを出力するようになります。 (note: the MySQL client will not print anything) このデータはパフォーマンス・チューニングに便利です。

On Windows you must start mysqld-max from a MS-DOS prompt with the --standalone --console options to direct the output to the MS-DOS prompt window.

There is a separate innodb_lock_monitor which prints the same information as innodb_monitor plus information on locks set by each transaction.

The printed information includes data on:

InnoDB モニタは、以下の SQL コマンドでスタートできます:

CREATE TABLE innodb_monitor(a int) type = innodb;

停止は:

DROP TABLE innodb_monitor;

CREATE TABLE 文は、MySQL SQL パーサーを通して InnoDB エンジンにアクセスするためだけに使用されているにすぎません: 作成されたテーブルは InnoDB モニタとは関係しません。 もし、モニタ実行中にデータベースを停止し、そのあと、 モニタを再び起動したいなら、 あなたはモニタを起動するための新しい CREATE TABLE 文を 実行する前に、前に作ったテーブルを破棄しなくてはなりません。 この構文は将来のリリースで変わるかもしれません。

InnoDB モニタ の出力サンプル:

================================
010809 18:45:06 INNODB MONITOR OUTPUT
================================
--------------------------
LOCKS HELD BY TRANSACTIONS
--------------------------
LOCK INFO:
Number of locks in the record hash table 1294
LOCKS FOR TRANSACTION ID 0 579342744
TABLE LOCK table test/mytable trx id 0 582333343 lock_mode IX

RECORD LOCKS space id 0 page no 12758 n bits 104 table test/mytable index
PRIMARY trx id 0 582333343 lock_mode X
Record lock, heap no 2 PHYSICAL RECORD: n_fields 74; 1-byte offs FALSE;
info bits 0
 0: len 4; hex 0001a801; asc ;; 1: len 6; hex 000022b5b39f; asc ";;
 2: len 7; hex 000002001e03ec; asc ;; 3: len 4; hex 00000001;
...
-----------------------------------------------
CURRENT SEMAPHORES RESERVED AND SEMAPHORE WAITS
-----------------------------------------------
SYNC INFO:
Sorry, cannot give mutex list info in non-debug version!
Sorry, cannot give rw-lock list info in non-debug version!
-----------------------------------------------------
SYNC ARRAY INFO: reservation count 6041054, signal count 2913432
4a239430 waited for by thread 49627477 op. S-LOCK file NOT KNOWN line 0
Mut ex 0 sp 5530989 r 62038708 sys 2155035;
rws 0 8257574 8025336; rwx 0 1121090 1848344
-----------------------------------------------------
CURRENT PENDING FILE I/O'S
--------------------------
Pending normal aio reads:
Reserved slot, messages 40157658 4a4a40b8
Reserved slot, messages 40157658 4a477e28
...
Reserved slot, messages 40157658 4a4424a8
Reserved slot, messages 40157658 4a39ea38
Total of 36 reserved aio slots
Pending aio writes:
Total of 0 reserved aio slots
Pending insert buffer aio reads:
Total of 0 reserved aio slots
Pending log writes or reads:
Reserved slot, messages 40158c98 40157f98
Total of 1 reserved aio slots
Pending synchronous reads or writes:
Total of 0 reserved aio slots
-----------
BUFFER POOL
-----------
LRU list length 8034
Free list length 0
Flush list length 999
Buffer pool size in pages 8192
Pending reads 39
Pending writes: LRU 0, flush list 0, single page 0
Pages read 31383918, created 51310, written 2985115
----------------------------
END OF INNODB MONITOR OUTPUT
============================
010809 18:45:22 InnoDB starts purge
010809 18:45:22 InnoDB purged 0 pages

出力に関するいくつかの注釈:

Implementation of Multi-versioning

InnoDB は multiversioned database なので、テーブル空間中のレコードの 古いバージョン情報が保持されなくてはなりません。 This information is stored in a data structure we call a rollback segment after an analogous data structure in Oracle.

InnoDB は内部では、データベースに保存されているそれぞれのレコードに対して 2 つのフィールドを付加しています。 A 6-byte field tells the transaction identifier for the last transaction which inserted or updated the row. Also a deletion is internally treated as an update where a special bit in the row is set to mark it as deleted. それぞれのレコードには、roll pointer と呼ばれる 7-byte のフィールドも含みます。 The roll pointer points to an undo log record written to the rollback segment. If the row was updated, then the undo log record contains the information necessary to rebuild the content of the row before it was updated.

InnoDB uses the information in the rollback segment to perform the undo operations needed in a transaction rollback. It also uses the information to build earlier versions of a row for a consistent read.

ロールバック セグメント の中の Undo log は、 insert と update の undo log に分けれれます。 Insert undo log は、トランザクションのロールバックの時にだけ必要とされ、 その トランザクション が コミット するやいなやすぐに破棄されます。 Update undo logs are used also in consistent reads, and they can be discarded only after there is no transaction present for which InnoDB has assigned a snapshot that in a consistent read could need the information in the update undo log to build an earlier version of a database row.

You must remember to commit your transactions regularly, also those transactions which only issue consistent reads. Otherwise InnoDB cannot discard data from the update undo logs, and the rollback segment may grow too big, filling up your tablespace.

The physical size of an undo log record in the rollback segment is typically smaller than the corresponding inserted or updated row. You can use this information to calculate the space need for your rollback segment.

In our multi-versioning scheme a row is not physically removed from the database immediately when you delete it with an SQL statement. Only when InnoDB can discard the update undo log record written for the deletion, it can also physically remove the corresponding row and its index records from the database. This removal operation is called a purge, and it is quite fast, usually taking the same order of time as the SQL statement which did the deletion.

テーブルとインデックスの構造

MySQL は、テーブルの data dictionary 情報を、 データベース ディレクトリ内の、 `.frm' ファイルに保存します。 しかし、InnoDB タイプの全てのテーブルは、 InnoDB の内部のデータ・ディクショナリを (InnoDBの)テーブル空間に持っています。 MySQL がテーブルやデータベースを破棄する時は、 `.frm' ファイル と それに対応する InnoDB のデータ・ディクショナリ 内のエントリが消去されます。 これは、`.frm' ファイルを移動するだけでは InnoDB テーブルを違うデータベースに移動することができない理由であり、 また、MySQL 3.23.43 以下のバージョンで、InnoDB 型のテーブルでは DROP DATABASE が動作しなかった理由でもあります。

Every InnoDB table has a special index called the clustered index where the data of the rows is stored. If you define a PRIMARY KEY on your table, then the index of the primary key will be the clustered index.

もしテーブルにプライマリ・キーを定義しなかった場合には、 InnoDB は内部ではクラスタド・インデックス(clustered index)を作成します。 そこでは、InnoDB がそのテーブルのレコードに割り当てた row id をもとに レコードが整理されます。 row id は 6-byte のフィールドで、新しいレコードが挿入されると単純に 数が増加していきます。 ということで、row id のよって整理されているレコードは、 物理的にインサートされた順になっています。

Accessing a row through the clustered index is fast, because the row data will be on the same page where the index search leads us. In many databases the data is traditionally stored on a different page from the index record. If a table is large, the clustered index architecture often saves a disk I/O when compared to the traditional solution.

The records in non-clustered indexes (we also call them secondary indexes), in InnoDB contain the primary key value for the row. InnoDB uses this primary key value to search for the row from the clustered index. Note that if the primary key is long, the secondary indexes will use more space.

Physical Structure of an Index

InnoDB の全てのインデックスは B-Tree で、インデックスのレコードは、 ツリーの リーフ ページ (原文 leaf page. ブロックと言い換える or not?) に保存されます。 インデックス ページの デフォルトの大きさは 16kB です。 新しいレコードがインサートされた時、InnoDB はページの 1/16 を、 将来のインデックスレコードの insert や update に備えて free に しようとします。

If index records are inserted in a sequential (ascending or descending) order, the resulting index pages will be about 15/16 full. If records are inserted in a random order, then the pages will be 1/2 - 15/16 full. If the fillfactor of an index page drops below 1/2, InnoDB will try to contract the index tree to free the page.

Insert Buffering

プライマリ・キーが一意で、新しいレコードがそのプライマリー・キーの 並びの順番で insert されるというのは、 データベースのアプリケーションではよくある事です。 この場合は、clustered index に対するインサートはディスクからの ランダム リードを要求しません。

これに対して、secondary indexes は通常 非ユニーク で、 secondary indexes に対するインサートされる順番はばらばらです。 This would cause a lot of random disk I/O's without a special mechanism used in InnoDB.

If an index record should be inserted to a non-unique secondary index, InnoDB checks if the secondary index page is already in the buffer pool. If that is the case, InnoDB will do the insertion directly to the index page. But, if the index page is not found from the buffer pool, InnoDB inserts the record to a special insert buffer structure. The insert buffer is kept so small that it entirely fits in the buffer pool, and insertions can be made to it very fast.

The insert buffer is periodically merged to the secondary index trees in the database. Often we can merge several insertions on the same page in of the index tree, and hence save disk I/Os. It has been measured that the insert buffer can speed up insertions to a table up to 15 times.

Adaptive Hash Indexes

If a database fits almost entirely in main memory, then the fastest way to perform queries on it is to use hash indexes. InnoDB has an automatic mechanism which monitors index searches made to the indexes defined for a table, and if InnoDB notices that queries could benefit from building of a hash index, such an index is automatically built.

But note that the hash index is always built based on an existing B-tree index on the table. InnoDB can build a hash index on a prefix of any length of the key defined for the B-tree, depending on what search pattern InnoDB observes on the B-tree index. A hash index can be partial: it is not required that the whole B-tree index is cached in the buffer pool. InnoDB will build hash indexes on demand to those pages of the index which are often accessed.

In a sense, through the adaptive hash index mechanism InnoDB adapts itself to ample main memory, coming closer to the architecture of main memory databases.

Physical Record Structure

How an Auto-increment Column Works in InnoDB

データベースがスタートアップした後、ユーザーが auto-increment が定義されているテーブル T に対して 初めて、insert を行なう時、 もしユーザーが auto-increment のフィールドに明示的に値を与えなければ、 InnoDB は SELECT MAX(auto-inc-column) FROM T を実行し、そして その結果得た値に1を加えた数を、 そのフィールドと テーブルの auto-increment counter に与えます。 これをもって、テーブル T の auto-increment counter が 初期化されたと言います。

InnoDB follows the same procedure in initializing the auto-increment counter for a freshly created table.

もしユーザーが auto-increment のフィールドに 0 をインサートしたなら、 InnoDB はそれを、値が与えられなかったものとして扱うことに 注意してください。

auto-increment counter が初期化された後、 もしユーザーがauto-increment のフィールドに明示的に値を与えてレコードを insert すれば、その値が現在の auto-increment counter より大きければ auto-increment counter はその値にセットされます。 もしユーザーが値を明示して与えなければ、InnODB は auto-increment counter を 1つ増やし、そしてその値をフィールドの値としてセットします。

The auto-increment mechanism, when assigning values from the counter, bypasses locking and transaction handling. Therefore you may also get gaps in the number sequence if you roll back transactions which have got numbers from the counter.

The behaviour of auto-increment is not defined if a user gives a negative value to the column or if the value becomes bigger than the maximum integer that can be stored in the specified integer type.

File Space Management and Disk I/O

Disk I/O

ディスク I/O では、InnoDB は非同期 I/O を使用します. On Windows NT it uses the native asynchronous I/O provided by the operating system. On Unix, InnoDB uses simulated asynchronous I/O built into InnoDB: InnoDB creates a number of I/O threads to take care of I/O operations, such as read-ahead. In a future version we will add support for simulated aio on Windows NT and native aio on those versions of Unix which have one.

On Windows NT InnoDB uses non-buffered I/O. That means that the disk pages InnoDB reads or writes are not buffered in the operating system file cache. This saves some memory bandwidth.

Starting from 3.23.41 InnoDB uses a novel file flush technique called doublewrite. It adds safety to crash recovery after an operating system crash or a power outage, and improves performance on most Unix flavors by reducing the need for fsync operations.

Doublewrite means that InnoDB before writing pages to a datafile first writes them to a contiguous tablespace area called the doublewrite buffer. Only after the write and the flush to the doublewrite buffer has completed, InnoDB writes the pages to their proper positions in the datafile. If the operating system crashes in the middle of a page write, InnoDB will in recovery find a good copy of the page from the doublewrite buffer.

3.23.41 からは、データファイルにロー・ディスク(raw disk)パーティションが 使用できますが、これはまだテスト段階です。 新しいデータファイルを作成するとき、 innodb_data_file_path に指定するデータファイルのサイズのすぐ後に、 newraw キーワードを付加すれば実現されます。 パーティションのサイズは、指定したサイズ以上(>=) でなければなりません。 InnoDB の 1M は、1024 x 1024 bytes を示します。 現実のディスク製品の表記では、1000 000 bytes を 1MB と表示することに 注意してください。

innodb_data_file_path=hdd1:5Gnewraw;hdd2:2Gnewraw

設定を記述してデータベースを再起動した後は、 あなたはキーワードを raw書き換えなければなりません。 書き換えを忘れると、InnoDB はそのパーティションを新規に上書きしてしまいます!

innodb_data_file_path=hdd1:5Graw;hdd2:2Graw

By using a raw disk you can on some Unixes perform unbuffered I/O.

There are two read-ahead heuristics in InnoDB: sequential read-ahead and random read-ahead. In sequential read-ahead InnoDB notices that the access pattern to a segment in the tablespace is sequential. Then InnoDB will post in advance a batch of reads of database pages to the I/O system. In random read-ahead InnoDB notices that some area in a tablespace seems to be in the process of being fully read into the buffer pool. Then InnoDB posts the remaining reads to the I/O system.

File Space Management

設定ファイルに記述したデータファイルを InnoDB のテーブル空間を作ります。 データファイルは単純に連結されてテーブル空間になります。 striping は使用されません。 Currently you cannot directly instruct where the space is allocated for your tables, except by using the following fact: from a newly created tablespace InnoDB will allocate space starting from the low end.

テーブル空間は、デフォルトサイズが 16kB の データベース ページから成ります。 それらページは 64個までの連続する部分にグループ化されます。 その、テーブル空間内の 'まとまり' は、InnoDB では セグメント と呼ばれます。 The pages are grouped into extents of 64 consecutive pages. The 'files' inside a tablespace are called segments in InnoDB. The name of the rollback segment is somewhat misleading because it actually contains many segments in the tablespace.

InnoDB 中のそれぞれのインデックスには、2つのセグメントが割り当てられます; 一つは B-tree の 非リーフ ノードに、もう一つは リーフのノードに。 The idea here is to achieve better sequentiality for the leaf nodes, which contain the data.

テーブル空間内であるセグメントが大きくなった場合、 InnoDB は 最初の 32 ページを個々に割り当てます。 そののち、InnoDB は全領域をそのセグメントに割り当はじめます。 InnoDB はデータがより良く連続することを確実にするために、 領域を 4つまで、一度に大きなセグメントに追加することが出来ます。 When a segment grows inside the tablespace, InnoDB allocates the first 32 pages to it individually. After that InnoDB starts to allocate whole extents to the segment. InnoDB can add to a large segment up to 4 extents at a time to ensure good sequentiality of data.

テーブル空間内のいくつかのページには、他のページのビットマップが含まれ、 その結果、InnoDB テーブル空間内の数個の領域は、全てをセグメントに 割り当てることができず、個々のページ毎に割り当てられます。 Some pages in the tablespace contain bitmaps of other pages, and therefore a few extents in an InnoDB tablespace cannot be allocated to segments as a whole, but only as individual pages.

テーブル空間の available free space を知るためにあなたが SHOW TABLE STATUS FROM ... LIKE ... クエリを実行した時、 InnoDB は、 テーブル空間内の、確実に使用できるフリーな領域の合計をレポートします。 InnoDB は、clean-up と他の内部的な使用目的のために、常にいくつかの領域を リザーブします。 これらのリザーブされた領域は free space には含まれません。

When you delete data from a table, InnoDB will contract the corresponding B-tree indexes. It depends on the pattern of deletes if that frees individual pages or extents to the tablespace, so that the freed space is available for other users. Dropping a table or deleting all rows from it is guaranteed to release the space to other users, but remember that deleted rows can be physically removed only in a purge operation after they are no longer needed in transaction rollback or consistent read.

テーブルのデフラグメント

If there are random insertions or deletions in the indexes of a table, the indexes may become fragmented. By fragmentation we mean that the physical ordering of the index pages on the disk is not close to the alphabetical ordering of the records on the pages, or that there are many unused pages in the 64-page blocks which were allocated to the index.

定期的に mysqldump を使用してテーブルをテキストファイルにダンプし、 テーブルを削除し、ダンプファイルからテーブルを作り直す事を行なうことで、 インデックスの走査を速くすることが可能です。 デフラグメントを行なう他の方法は、テーブルのタイプを ALTER で 一度 MyISAM にし、再び InnoDB に変更することです。 Note that a MyISAM table must fit in a single file on your operating system.

If the insertions to and index are always ascending and records are deleted only from the end, then the file space management algorithm of InnoDB guarantees that fragmentation in the index will not occur.

エラー ハンドリング

The error handling in InnoDB is not always the same as specified in the ANSI SQL standards. According to the ANSI standard, any error during an SQL statement should cause the rollback of that statement. InnoDB sometimes rolls back only part of the statement, or the whole transaction. The following list specifies the error handling of InnoDB.

InnoDB テーブルの制限

InnoDB Change History

MySQL/InnoDB-4.1.0, April x, 2003

MySQL/InnoDB-3.23.56, March xx, 2003

MySQL/InnoDB-4.0.12, March xx, 2003

MySQL/InnoDB-4.0.11, February 25, 2003

MySQL/InnoDB-4.0.10, February 4, 2003

MySQL/InnoDB-3.23.55, January 24, 2003

MySQL/InnoDB-4.0.9, January 14, 2003

MySQL/InnoDB-4.0.8, January 7, 2003

MySQL/InnoDB-4.0.7, December 26, 2002

MySQL/InnoDB-4.0.6, December 19, 2002

MySQL/InnoDB-3.23.54, December 12, 2002

MySQL/InnoDB-4.0.5, November 18, 2002

MySQL/InnoDB-3.23.53, October 9, 2002

MySQL/InnoDB-4.0.4, October 2, 2002

MySQL/InnoDB-4.0.3, August 28, 2002

MySQL/InnoDB-3.23.52, August 16, 2002

MySQL/InnoDB-4.0.2, July 10, 2002

MySQL/InnoDB-3.23.51, June 12, 2002

MySQL/InnoDB-3.23.50, April 23, 2002

MySQL/InnoDB-3.23.49, February 17, 2002

MySQL/InnoDB-3.23.48, February 9, 2002

MySQL/InnoDB-3.23.47, December 28, 2001

MySQL/InnoDB-4.0.1, December 23, 2001

MySQL/InnoDB-3.23.46, November 30, 2001

MySQL/InnoDB-3.23.45, November 23, 2001

MySQL/InnoDB-3.23.44, November 2, 2001

MySQL/InnoDB-3.23.43, October 4, 2001

MySQL/InnoDB-3.23.42, September 9, 2001

MySQL/InnoDB-3.23.41, August 13, 2001

MySQL/InnoDB-3.23.40, July 16, 2001

MySQL/InnoDB-3.23.39, June 13, 2001

MySQL/InnoDB-3.23.38, May 12, 2001

InnoDB Contact Information

Contact information of Innobase Oy, producer of the InnoDB engine. Web site: http://www.innodb.com/. E-mail: Heikki.Tuuri@innodb.com

phone: 358-9-6969 3250 (office) 358-40-5617367 (mobile)
Innobase Oy Inc.
World Trade Center Helsinki
Aleksanterinkatu 17
P.O.Box 800
00101 Helsinki
Finland

BDB or BerkeleyDB Tables

Overview of BDB Tables

BerkeleyDB, available at http://www.sleepycat.com/ has provided MySQL with a transactional storage engine. Support for this storage engine is included in the MySQL source distribution starting from version 3.23.34 and is activated in the MySQL-Max binary. This storage engine is typically called BDB for short.

BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions. The MySQL source distribution comes with a BDB distribution that has a couple of small patches to make it work more smoothly with MySQL. You can't use a non-patched BDB version with MySQL.

We at MySQL AB are working in close cooperation with Sleepycat to keep the quality of the MySQL/BDB interface high.

When it comes to supporting BDB tables, we are committed to help our users to locate the problem and help creating a reproducible test case for any problems involving BDB tables. Any such test case will be forwarded to Sleepycat who in turn will help us find and fix the problem. As this is a two-stage operation, any problems with BDB tables may take a little longer for us to fix than for other storage engines. However, as the BerkeleyDB code itself has been used by many other applications than MySQL, we don't envision any big problems with this. See section Support Offered by MySQL AB.

Installing BDB

If you have downloaded a binary version of MySQL that includes support for BerkeleyDB, simply follow the instructions for installing a binary version of MySQL. See section Installing a MySQL Binary Distribution. See section mysqld-max, An Extended mysqld Server.

To compile MySQL with Berkeley DB support, download MySQL Version 3.23.34 or newer and configure MySQL with the --with-berkeley-db option. See section MySQL ソースディストリビューションのインストール.

cd /path/to/source/of/mysql-3.23.34
./configure --with-berkeley-db

Please refer to the manual provided with the BDB distribution for more updated information.

Even though Berkeley DB is in itself very tested and reliable, the MySQL interface is still considered beta quality. We are actively improving and optimising it to get it stable very soon.

BDB startup options

If you are running with AUTOCOMMIT=0 then your changes in BDB tables will not be updated until you execute COMMIT. Instead of commit you can execute ROLLBACK to forget your changes. See section BEGIN/COMMIT/ROLLBACK 構文.

If you are running with AUTOCOMMIT=1 (the default), your changes will be committed immediately. You can start an extended transaction with the BEGIN WORK SQL command, after which your changes will not be committed until you execute COMMIT (or decide to ROLLBACK the changes).

The following options to mysqld can be used to change the behaviour of BDB tables:

Option Description
--bdb-home=directory Base directory for BDB tables. This should be the same directory you use for --datadir.
--bdb-lock-detect=# Berkeley lock detect. One of (DEFAULT, OLDEST, RANDOM, or YOUNGEST).
--bdb-logdir=directory Berkeley DB log file directory.
--bdb-no-sync Don't synchronously flush logs.
--bdb-no-recover Don't start Berkeley DB in recover mode.
--bdb-shared-data Start Berkeley DB in multi-process mode (Don't use DB_PRIVATE when initialising Berkeley DB)
--bdb-tmpdir=directory Berkeley DB temporary file directory.
--skip-bdb Disable usage of BDB tables.
-O bdb_max_lock=1000 Set the maximum number of locks possible. See section SHOW VARIABLES.

If you use --skip-bdb, MySQL will not initialise the Berkeley DB library and this will save a lot of memory. Of course, you cannot use BDB tables if you are using this option. If you try to create a BDB table, MySQL will instead create a MyISAM table.

Normally you should start mysqld without --bdb-no-recover if you intend to use BDB tables. This may, however, give you problems when you try to start mysqld if the BDB log files are corrupted. See section MySQL サーバー起動時の問題.

With bdb_max_lock you can specify the maximum number of locks (10000 by default) you can have active on a BDB table. You should increase this if you get errors of type bdb: Lock table is out of available locks or Got error 12 from ... when you have do long transactions or when mysqld has to examine a lot of rows to calculate the query.

You may also want to change binlog_cache_size and max_binlog_cache_size if you are using big multi-line transactions. See section BEGIN/COMMIT/ROLLBACK 構文.

Characteristics of BDB tables:

Things we need to fix for BDB in the near future:

Operating systems supported by BDB

Currently we know that the BDB storage engine works with the following operating systems:

It doesn't work with the following operating systems:

Note: The above list is not complete; we will update it as we receive more information.

If you build MySQL with support for BDB tables and get the following error in the log file when you start mysqld:

bdb: architecture lacks fast mutexes: applications cannot be threaded
Can't init dtabases

This means that BDB tables are not supported for your architecture. In this case you must rebuild MySQL without BDB table support.

Restrictions on BDB Tables

Here follows the restrictions you have when using BDB tables:

Errors That May Occur When Using BDB Tables

MySQL APIs

This chapter describes the APIs available for MySQL, where to get them, and how to use them. The C API is the most extensively covered, as it was developed by the MySQL team, and is the basis for most of the other APIs.

MySQL PHP API

PHP is a server-side, HTML-embedded scripting language that may be used to create dynamic web pages. It contains support for accessing several databases, including MySQL. PHP may be run as a separate program or compiled as a module for use with the Apache web server.

The distribution and documentation are available at the PHP web site (http://www.php.net/).

Common Problems with MySQL and PHP

MySQL Perl API

ここでは Perl DBI インターフェースについて述べる。 以前のインターフェースは mysqlperl であった。 DBI/DBD が Perl インターフェースとして現在推奨されているので、 mysqlperl に関してはここでは述べない。

DBI with DBD::mysql

DBI は多くのデーターベースとの一般的なインターフェースである。 これは、多くのデーターベースと動作するスクリプトを変更なしに書けることを意味する。 そのためには、それぞれのデータベース用のデータベースドライバ (DBD) が必要である。 MySQL では、そのドライバは DBD::mysql である。

Perl5 DBI に関する詳細は、DBIウェッブページを参照のこと:

http://dbi.perl.org/

Object Oriented Programming (OOP) に関する詳細は、Perl OOP ページを参照のこと:

http://language.perl.com/info/documentation.html

Note that if you want to use transactions with Perl, you need to have Msql-Mysql-modules version 1.2216 or newer.

The recommended Perl module is DBD-mysql-2.1022 or newer.

Installation instructions for MySQL Perl support are given in section Perl Installation Comments.

If you have the MySQL module installed, you can find information about specific MySQL functionallity with one of the following command

shell> perldoc DBD/mysql
shell> perldoc mysql

The DBI Interface

Portable DBI Methods

connect データベースサーバと接続する
disconnect データベースサーバとの接続を切る
prepare SQL文を設定する
execute 設定されたSQL文を実行する
do SQL文を設定し、実行する
quote 挿入するためのクォート文字、または BLOB
fetchrow_array フィールドの配列として次のレコードを取り出す
fetchrow_arrayref フィールドの配列参照として次のレコードを取り出す
fetchrow_hashref ハッシュテーブルへの参照として次のレコードを取り出す
fetchall_arrayref 配列の配列として全データを取り出す
finish 命令を終了し、リソースからシステムを切り離す
rows 影響のあったレコードの数を返す
data_sources ローカルホスト上で利用できるデータベースの配列を返す
ChopBlanks fetchrow_* メソッドが空白を取り除くかどうかを管理する
NUM_OF_PARAMS 設定された命令文中の placeholder の数
NULLABLE どのフィールドに NULL 値があるか?
trace Perform tracing for debugging

MySQL 固有メソッド

insertid 最後の AUTO_INCREMENT
is_blob どのフィールドが BLOB か?
is_key どのフィールドがキーか?
is_num どのフィールドが数値型か?
is_pri_key どのフィールドがプライマリキーか?
is_not_null どのフィールドが NULL 値か? NULLABLE 参照。
length 利用可能なフィールドサイズの最大値
max_length 実際に存在しているフィールドサイズの最大値
NAME フィールド名
NUM_OF_FIELDS 返されたフィールドの数
table 返されたセットのテーブル名
type 全てのフィールドの型
_CreateDB データベースを作成する
_DropDB データベースを削除する。 ***このメソッドは危険である***

以下の節に、より詳細な Perl メソッドの解説がある。 Variables used for method return values have these meanings:

$dbh
Database handle
$sth
Statement handle
$rc
Return code (often a status)
$rv
Return value (often a row count)

汎用 DBI メソッド

Generally the 'do' statement is MUCH faster (and is preferable) than prepare/execute for statements that doesn't contain parameters.
connect($data_source, $username, $password)
データソースとのデータベース接続をするために connect を使う。 $data_source 値は DBI:driver_name: ではじめること。 DBD::mysql ドライバーを用いた connect の使用例:
$dbh = DBI->connect("DBI:mysql:$database", $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname",
                    $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname:$port",
                    $user, $password);
ユーザー名またはパスワードが未設定の場合、 DBI は環境変数である DBI_USERDBI_PASS をそれぞれ使う。 ホスト名を指定しない場合は、'localhost' がデフォルトとなる。 ポート番号を指定しない場合は、MySQL ポート() がデフォルトとなる。 As of Msql-Mysql-modules Version 1.2009, the $data_source value allows certain modifiers:
mysql_read_default_file=file_name
Read `filename' as an option file. For information on option files, see section `my.cnf' オプションファイル.
mysql_read_default_group=group_name
The default group when reading an option file is normally the [client] group. By specifying the mysql_read_default_group option, the default group becomes the [group_name] group.
mysql_compression=1
Use compressed communication between the client and server (MySQL Version 3.22.3 or later).
mysql_socket=/path/to/socket
Specify the pathname of the Unix socket that is used to connect to the server (MySQL Version 3.21.15 or later).
Multiple modifiers may be given; each must be preceded by a semicolon. For example, if you want to avoid hardcoding the user name and password into a DBI script, you can take them from the user's `~/.my.cnf' option file instead by writing your connect call like this:
$dbh = DBI->connect("DBI:mysql:$database"
                . ";mysql_read_default_file=$ENV{HOME}/.my.cnf",
                $user, $password);
This call will read options defined for the [client] group in the option file. If you wanted to do the same thing but use options specified for the [perl] group as well, you could use this:
$dbh = DBI->connect("DBI:mysql:$database"
                . ";mysql_read_default_file=$ENV{HOME}/.my.cnf"
                . ";mysql_read_default_group=perl",
                $user, $password);
disconnect
disconnect メソッドは、データベースとのデータベースハンドルを切断する。 プログラムを終了する直前に呼び出されるのが典型的である。 例:
$rc = $dbh->disconnect;
prepare($statement)
データベースエンジンで実行するためのSQL文を設定し、execute メソッドで 使用出来るステートメントハンドル ($sth) を返す。 Typically you handle SELECT statements (and SELECT-like statements such as SHOW, DESCRIBE, and EXPLAIN) by means of prepare and execute. Example:
$sth = $dbh->prepare($statement)
    or die "Can't prepare $statement: $dbh->errstr\n";
If you want to read big results to your client you can tell Perl to use mysql_use_result() with:
my $sth = $dbh->prepare($statement { "mysql_use_result" => 1});
execute
execute メソッドは、設定されたSQL文を実行する。非 SELECT 文のときは、 影響のあったレコードの数を返す。 もしなんの変化もなかったなら、 execute"0E0" (これは Perl では ゼロ 扱いですが、 真 でもある) を返す。 If an error occurs, execute returns undef. SELECT 文のときは、SQL要求を開始するのみである。 データを操作する fetch_* メソッドの内の一つを記述する必要がある。 例:
$rv = $sth->execute
          or die "can't execute the query: $sth->errstr;
do($statement)
do メソッドはSQL文を設定・実行し、影響のあったレコードの数を返す。 このメソッドは、「非 select」文、すなわち、高度(ドライバーの限界のため)で設定できない文、 一度の実行(inserts, deletes など)で済む文のときに一般的に用いられる。 例:
$rv = $dbh->do($statement)
        or die "Can't execute $statement: $dbh- >errstr\n";
quote($string)
quote メソッドは、文字列中にエスケープ文字があるときに用いられ、 クォート文字を文の外側に付加する。 例:
$sql = $dbh->quote($string)
fetchrow_array
このメソッドはデータの次のレコードを取り出し、フィールドの値の配列として返す。 例:
while(@row = $sth->fetchrow_array) {
        print qw($row[0]\t$row[1]\t$row[2]\n);
}
fetchrow_arrayref
このメソッドはデータの次のレコードを取り出し、フィールドの値の配列への参照として返す。 例:
while($row_ref = $sth->fetchrow_arrayref) {
        print qw($row_ref->[0]\t$row_ref->[1]\t$row_ref->[2]\n);
}
fetchrow_hashref
このメソッドはデータのレコードを取り出し、名前・値のペアのフィールドを含んだ ハッシュテーブルへの参照を返す。このメソッドは、上で示した配列参照 (訳注:fetchrow_arrayref)よりもかなり効率的ではない。例:
while($hash_ref = $sth->fetchrow_hashref) {
        print qw($hash_ref->{firstname}\t$hash_ref->{lastname}\t\
                $hash_ref->{title}\n);
}
fetchall_arrayref
このメソッドは、SQL文より返されたデータ(レコード)の全てを得るために使う。 このメソッドは、各レコードへの参照の配列の配列への参照を返す。 入れ子のループを使ってデータを利用・表示する。例:
my $table = $sth->fetchall_arrayref
                or die "$sth->errstr\n";
my($i, $j);
for $i ( 0 .. $#{$table} ) {
        for $j ( 0 .. $#{$table->[$i]} ) {
                print "$table->[$i][$j]\t";
        }
        print "\n";
}
finish
そのステートメントハンドルからそれ以上データを取り出さないことを示す。ステートメントハンドルや、つかんでいたシステムリソースを解放するためにこのメソッドを呼び出す。例:
$rc = $sth->finish;
rows
最後の命令により、(データの更新、削除、などで)影響のあったレコードの数を返す。 このメソッドは do あるいは 非 SELECT execute 文を 実行した後に、たいてい使われる。例: Example:
$rv = $sth->rows;
NULLABLE
Returns a reference to an array of values that indicate whether columns may contain NULL values. The possible values for each array element are 0 or the empty string if the column cannot be NULL, 1 if it can, and 2 if the column's NULL status is unknown. Example:
$null_possible = $sth->{NULLABLE};
NUM_OF_FIELDS
この属性は、SELECT 文や SHOW FIELDS 文によって返された フィールドの数を示している。命令文が結果を返したかどうかをチェックするのに、 これを使うことが出来る:0値は、INSERT, DELETE または UPDATE のような非 SELECT 文を示している。例: Example:
$nr_of_fields = $sth->{NUM_OF_FIELDS};
data_sources($driver_name)
このメソッドは、'localhost' ホスト上の MySQL サーバで 利用可能なデータベースの名前を含んだ配列を返す。例:
@dbs = DBI->data_sources("mysql");
ChopBlanks
この属性は、 fetchrow_* メソッドが返り値から前後の空白を 除去するかどうかを決定する。例:
$sth->{'ChopBlanks'} =1;
trace($trace_level)
trace($trace_level, $trace_filename)
The trace method enables or disables tracing. When invoked as a DBI class method, it affects tracing for all handles. When invoked as a database or statement handle method, it affects tracing for the given handle (and any future children of the handle). Setting $trace_level to 2 provides detailed trace information. Setting $trace_level to 0 disables tracing. Trace output goes to the standard error output by default. If $trace_filename is specified, the file is opened in append mode and output for all traced handles is written to that file. Example:
DBI->trace(2);                # trace everything
DBI->trace(2,"/tmp/dbi.out"); # trace everything to
                              # /tmp/dbi.out
$dth->trace(2);               # trace this database handle
$sth->trace(2);               # trace this statement handle
You can also enable DBI tracing by setting the DBI_TRACE environment variable. Setting it to a numeric value is equivalent to calling DBI->(value). Setting it to a pathname is equivalent to calling DBI->(2,value).

MySQL 固有メソッド

The methods shown here are MySQL-specific and not part of the DBI standard. Several of them are now deprecated: is_blob, is_key, is_num, is_pri_key, is_not_null, length, max_length, and table. Where DBI-standard alternatives exist, they are noted here:

insertid
MySQL の特徴である AUTO_INCREMENT を使うとき、 新しい自動繰り上がり値がここに記憶される。例: Example:
$new_id = $sth->{insertid};
As an alternative, you can use $dbh->{'mysql_insertid'}.
is_blob
配列の各要素に対し、ブール値の配列への参照を返す。TRUE であれば そのフィールドが BLOB 値であることを示す。例:
$keys = $sth->{is_blob};
is_key
配列の各要素に対し、ブール値の配列への参照を返す。TRUE であれば そのフィールドがキーであることを示す。 例:
$keys = $sth->{is_key};
is_num
配列の各要素に対し、ブール値の配列への参照を返す。TRUE であれば そのフィールドが数値型であることを示す。 例:
$nums = $sth->{is_num};
is_pri_key
配列の各要素に対し、ブール値の配列への参照を返す。TRUE であれば そのフィールドがプライマリーキーであることを示す。 例:
$pri_keys = $sth->{is_pri_key};
is_not_null
配列の各要素に対し、ブール値の配列への参照を返す。FALSE であれば そのフィールドが NULL 値を含むことを示す。 例:
$not_nulls = $sth->{is_not_null};
is_not_null is deprecated; 前述の NULLABLE 属性を使用するほうが望ましい。それが DBI の標準である。
length
max_length
それぞれのメソッドは、フィールドサイズの配列への参照を返す。length 配列は、 (テーブル記述で定義された)各フィールドの利用可能最大値を示す。 max_length 配列は、テーブル中に実際に存在している最大値を示す。例:
$lengths = $sth->{length};
$max_lengths = $sth->{max_length};
NAME
フィールド名の配列への参照を返す。 例:
$names = $sth->{NAME};
table
テーブル名の配列への参照を返す。 例:
$tables = $sth->{table};
type
フィールドの型の配列への参照を返す。 例:
$types = $sth->{type};

DBI/DBD に関するそれ以上の情報

DBI に関するそれ以上の情報は perldoc コマンドで得られる。

perldoc DBI
perldoc DBI::FAQ
perldoc DBD::mysql

他のフォーマットに変換するツール、pod2man, pod2html なども 使うことが出来る。

そしてもちろん、DBI の最新情報は DBI ウェッブページで見ることが出来る:http://dbi.perl.org/.

MySQL ODBC サポート

MySQL は MyODBC プログラムで ODBC 機能を提供します。 This chapter will teach you how to install MyODBC, and how to use it. Here, you will also find a list of common programs that are known to work with MyODBC.

How To Install MyODBC

MyODBC 2.50 is a 32-bit ODBC 2.50 specification level 0 (with level 1 and level 2 features) driver for connecting an ODBC-aware application to MySQL. MyODBC works on Windows 9x/Me/NT/2000/XP and most Unix platforms. MyODBC 3.51 is an enhanced version with ODBC 3.5x specification level 1 (complete core API + level 2 features). MyODBCOpen Source で、最新の物は以下にあります: http://www.mysql.com/downloads/api-myodbc.html. Please note that the 2.50.x versions are LGPL licensed, whereas the 3.51.x versions are GPL licensed.

日本語文字コードに対応させた物は: http://www.SoftAgency.co.jp/.

If you have problem with MyODBC and your program also works with OLEDB, you should try the OLEDB driver.

Normally you only need to install MyODBC on Windows machines. You only need MyODBC for Unix if you have a program like ColdFusion that is running on the Unix machine and uses ODBC to connect to the databases.

もし、Unix に MyODBC をインストールしたいなら、 ODBC マネージャーも必要でしょう。 MyODBC は Unix の ODBC マネージャー でも動作することが知られています。

To install MyODBC on Windows, you should download the appropriate MyODBC `.zip' file, unpack it with WinZIP or some similar program, and execute the `SETUP.EXE' file.

Windows/NT の場合、MyODBC をインストール時にいかのような エラーになるかもしれません:

An error occurred while copying C:\WINDOWS\SYSTEM\MFC30.DLL. Restart
Windows and try installing again (before running any applications which
use ODBC)

The problem in this case is that some other program is using ODBC and because of how Windows is designed, you may not in this case be able to install a new ODBC drivers with Microsoft's ODBC setup program. In most cases you can continue by just pressing Ignore to copy the rest of the MyODBC files and the final installation should still work. これを解決するには、一度 ’セーフモード’でコンピュータを立ち上げ直し、 (windows リブート時に、F8キーを押すことで、セーフモードの選択が可能です) MyODBC をインストールして、リブートします:

MyODBC の設定画面には、MySQL 接続時のオプションがいくつか 設定できるようになっています。 もし問題がある場合は、これらを試します。

ODBC 管理プログラムの各種項目を埋めるには?

Windows95 上のサーバ名の記述には3つの可能性があります:

ODBC setup を埋める方法の例:

Windows DSN name:   test
Description:        This is my test database
MySql Database:     test
Server:             194.216.84.21
User:               monty
Password:           my_password
Port:

Windows DSN name 項目の値は、あなたのwindows ODBC setup における 一意の名前です。

ODBC setup 画面で、Server, User, Password, Port フィールドを設定する必要はありません。 しかし、ここで設定をすると、後でサーバーに接続する際に、 設定した値がデフォルト値として使用されます。 使用時に値を変更するオプションはあります。

ポート番号が設定されていないなら、デフォルトポート () が使用 されます。

もしオプションを Read options from C:\my.cnf にすると, clientodbc グループは `C:\my.cnf' ファイルから読まれます。 mysql_options() で使用できる全てのオプションが利用可能です。 See section mysql_options().

Connect parameters for MyODBC

One can specify the following parameters for MyODBC on the [Servername] section of an `ODBC.INI' file or through the InConnectionString argument in the SQLDriverConnect() call.

Parameter Default value Comment
user ODBC (on Windows) The username used to connect to MySQL.
server localhost The hostname of the MySQL server.
database The default database.
option 0 A integer by which you can specify how MyODBC should work. See below.
port 3306 The TCP/IP port to use if server is not localhost.
stmt A statement that will be executed when connecting to MySQL.
password The password for the server user combination.
socket The socket or Windows pipe to connect to.

The option argument is used to tell MyODBC that the client isn't 100% ODBC compliant. On Windows, one normally sets the option flag by toggling the different options on the connection screen but one can also set this in the opton argument. The following options are listed in the same order as they appear in the MyODBC connect screen:

Bit Description
1 The client can't handle that MyODBC returns the real width of a column.
2 The client can't handle that MySQL returns the true value of affected rows. If this flag is set then MySQL returns 'found rows' instead. One must have MySQL 3.21.14 or newer to get this to work.
4 Make a debug log in c:\myodbc.log. This is the same as putting MYSQL_DEBUG=d:t:O,c::\myodbc.log in `AUTOEXEC.BAT'
8 Don't set any packet limit for results and parameters.
16 Don't prompt for questions even if driver would like to prompt
32 Simulate a ODBC 1.0 driver in some context.
64 Ignore use of database name in 'database.table.column'.
128 Force use of ODBC manager cursors (experimental).
256 Disable the use of extended fetch (experimental).
512 Pad CHAR fields to full column length.
1024 SQLDescribeCol() will return fully qualifed column names
2048 Use the compressed server/client protocol
4096 Tell server to ignore space after function name and before '(' (needed by PowerBuilder). This will make all function names keywords!
8192 Connect with named pipes to a mysqld server running on NT.
16384 Change LONGLONG columns to INT columns (some applications can't handle LONGLONG).
32768 Return 'user' as Table_qualifier and Table_owner from SQLTables (experimental)
65536 Read parameters from the client and odbc groups from `my.cnf'
131072 Add some extra safety checks (should not bee needed but...)

If you want to have many options, you should add the above flags! For example setting option to 12 (4+8) gives you debugging without package limits!

The default `MYODBC.DLL' is compiled for optimal performance. If you want to debug MyODBC (for example to enable tracing), you should instead use `MYODBCD.DLL'. To install this file, copy `MYODBCD.DLL' over the installed `MYODBC.DLL' file.

MyODBC での問題をどのように報告すべきか?

MyODBC は以下でテストされました: Access, Admndemo.exe, C++-Builder, Borland Builder 4, Centura Team Developer (formerly Gupta SQL/Windows), ColdFusion (on Solaris and NT with svc pack 5), Crystal Reports, DataJunction, Delphi, ERwin, Excel, iHTML, FileMaker Pro, FoxPro, Notes 4.5/4.6, SBSS, Perl DBD-ODBC, Paradox, Powerbuilder, Powerdesigner 32 bit, VC++, and Visual Basic.

If you know of any other applications that work with MyODBC, please send mail to myodbc@lists.mysql.com about this!

With some programs you may get an error like: Another user has modifies the record that you have modified. In most cases this can be solved by doing one of the following things:

If the above doesn't help, you should do a MyODBC trace file and try to figure out why things go wrong.

MyODBC で動作することが知られているプログラム

Most programs should work with MyODBC, but for each of those listed here, we have tested it ourselves or received confirmation from some user that it works:

Program
Comment
Access
To make Access work:
ADO
When you are coding with the ADO API and MyODBC you need to put attention in some default properties that aren't supported by the MySQL server. For example, using the CursorLocation Property as adUseServer will return for the RecordCount Property a result of -1. To have the right value, you need to set this property to adUseClient, like is showing in the VB code here:
Dim myconn As New ADODB.Connection
Dim myrs As New Recordset
Dim mySQL As String
Dim myrows As Long

myconn.Open "DSN=MyODBCsample"
mySQL = "SELECT * from user"
myrs.Source = mySQL
Set myrs.ActiveConnection = myconn
myrs.CursorLocation = adUseClient
myrs.Open
myrows = myrs.RecordCount

myrs.Close
myconn.Close
Another workaround is to use a SELECT COUNT(*) statement for a similar query to get the correct row count.
Active server pages (ASP)
You should use the option flag Return matching rows.
BDE applications
To get these to work, you should set the option flags Don't optimize column widths and Return matching rows.
Borland Builder 4
When you start a query you can use the property Active or use the method Open. Note that Active will start by automatically issuing a SELECT * FROM ... query that may not be a good thing if your tables are big!
ColdFusion (On Unix)
The following information is taken from the ColdFusion documentation: Use the following information to configure ColdFusion Server for Linux to use the unixODBC driver with MyODBC for MySQL data sources. Allaire has verified that MyODBC Version 2.50.26 works with MySQL Version 3.22.27 and ColdFusion for Linux. (Any newer version should also work.) You can download MyODBC at http://www.mysql.com/downloads/api-myodbc.html ColdFusion Version 4.5.1 allows you to us the ColdFusion Administrator to add the MySQL data source. However, the driver is not included with ColdFusion Version 4.5.1. Before the MySQL driver will appear in the ODBC datasources drop-down list, you must build and copy the MyODBC driver to `/opt/coldfusion/lib/libmyodbc.so'. The Contrib directory contains the program `mydsn-xxx.zip' which allows you to build and remove the DSN registry file for the MyODBC driver on Coldfusion applications.
DataJunction
You have to change it to output VARCHAR rather than ENUM, as it exports the latter in a manner that causes MySQL grief.
Excel
Works. A few tips:
Word
To retrieve data from MySQL to Word/Excel documents, you need to use the MyODBC driver and the Add-in Microsoft Query help. For example, create a db with a table containing 2 columns of text:
odbcadmin
ODBC のテストプログラム.
Delphi
DBE 3.2 以上を必ず使用してください。 MySQL に接続する際には、'Don't optimize column width' オプションをセッ トします。 Also, here is some potentially useful Delphi code that sets up both an ODBC entry and a BDE entry for MyODBC (the BDE entry requires a BDE Alias Editor that is free at a Delphi Super Page near you. (Thanks to Bryan Brunton bryan@flesherfab.com for this):
fReg:= TRegistry.Create;
  fReg.OpenKey('\Software\ODBC\ODBC.INI\DocumentsFab', True);
  fReg.WriteString('Database', 'Documents');
  fReg.WriteString('Description', ' ');
  fReg.WriteString('Driver', 'C:\WINNT\System32\myodbc.dll');
  fReg.WriteString('Flag', '1');
  fReg.WriteString('Password', '');
  fReg.WriteString('Port', ' ');
  fReg.WriteString('Server', 'xmark');
  fReg.WriteString('User', 'winuser');
  fReg.OpenKey('\Software\ODBC\ODBC.INI\ODBC Data Sources', True);
  fReg.WriteString('DocumentsFab', 'MySQL');
  fReg.CloseKey;
  fReg.Free;

  Memo1.Lines.Add('DATABASE NAME=');
  Memo1.Lines.Add('USER NAME=');
  Memo1.Lines.Add('ODBC DSN=DocumentsFab');
  Memo1.Lines.Add('OPEN MODE=READ/WRITE');
  Memo1.Lines.Add('BATCH COUNT=200');
  Memo1.Lines.Add('LANGDRIVER=');
  Memo1.Lines.Add('MAX ROWS=-1');
  Memo1.Lines.Add('SCHEMA CACHE DIR=');
  Memo1.Lines.Add('SCHEMA CACHE SIZE=8');
  Memo1.Lines.Add('SCHEMA CACHE TIME=-1');
  Memo1.Lines.Add('SQLPASSTHRU MODE=SHARED AUTOCOMMIT');
  Memo1.Lines.Add('SQLQRYMODE=');
  Memo1.Lines.Add('ENABLE SCHEMA CACHE=FALSE');
  Memo1.Lines.Add('ENABLE BCD=FALSE');
  Memo1.Lines.Add('ROWSET SIZE=20');
  Memo1.Lines.Add('BLOBS TO CACHE=64');
  Memo1.Lines.Add('BLOB SIZE=32');

  AliasEditor.Add('DocumentsFab','MySQL',Memo1.Lines);
C++ Builder
BDE 3.0で,テストされました。唯一の知られた問題は、 テーブルスキーマが変化する時、クエリフィールドが更新されないことです。 BDE は、index PRIMARY だけを認識し、プライマリーキーは認識していないように思えま す。これはさほど問題ではないですが。
Vision
You should use the option flag Return matching rows.
Visual Basic
テーブルの更新を可能にするため、テーブルにプライマリーキーを作成しなくてはなりま せん。 Visual Basic with ADO can't handle big integers. This means that some queries like SHOW PROCESSLIST will not work properly. The fix is to set the option OPTION=16384 in the ODBC connect string or to set the Change BIGINT columns to INT option in the MyODBC connect screen. You may also want to set the Return matching rows option.
VisualInterDev
If you get the error [Microsoft][ODBC Driver Manager] Driver does not support this parameter the reason may be that you have a BIGINT in your result. Try setting the Change BIGINT columns to INT option in the MyODBC connect screen.
Visual Objects
You should use the option flag Don't optimize column widths.

AUTO_INCREMENT フィールドの値を ODBC で得る方法

共通の問題は、INSERT で自動的に生成されるIDの値を得ることです。 ODBCでは、以下のようにします( 例中の autoAUTO_INCREMENT フィー ルドです):

INSERT INTO foo (auto,text) VALUES(NULL,'text');
SELECT LAST_INSERT_ID();

もしくは、他のテーブルにIDを挿入するだけなら以下のようにします:

INSERT INTO foo (auto,text) VALUES(NULL,'text');
INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text');

See section 最後に挿入された行のユニーク ID をどのように得られるか?.

For the benefit of some ODBC applications (at least Delphi and Access), the following query can be used to find a newly inserted row:

SELECT * FROM tbl_name WHERE auto IS NULL;

Reporting Problems with MyODBC

もし MyODBC 使用時に難しい問題にあたった場合、 ODBC マネージャのログファイル (ODBCADMIN からリクエストしたときのログ) と MyODBC のログを取り始めるべきです。 これはいかなる問題にも解決の糸口になるはずです。

MyODBC のログを取るには、以下のように行ないます:

  1. Ensure that you are using `myodbcd.dll' and not `myodbc.dll'. The easiest way to do this is to get `myodbcd.dll' from the MyODBC distribution and copy it over the `myodbc.dll', which is probably in your `C:\windows\system32' or `C:\winnt\system32' directory. Note that you probably want to restore the old myodbc.dll file when you have finished testing, as this is a lot faster than `myodbcd.dll'.
  2. Tag the `Trace MyODBC' option flag in the MyODBC connect/configure screen. The log will be written to file `C:\myodbc.log'. If the trace option is not remembered when you are going back to the above screen, it means that you are not using the myodbcd.dll driver (see the item above).
  3. Start your application and try to get it to fail.

Check the MyODBC trace file, to find out what could be wrong. You should be able to find out the issued queries by searching after the string >mysql_real_query in the `myodbc.log' file.

You should also try duplicating the queries in the mysql monitor or admndemo to find out if the error is MyODBC or MySQL.

If you find out something is wrong, please only send the relevant rows (max 40 rows) to myodbc@lists.mysql.com. Please never send the whole MyODBC or ODBC log file!

If you are unable to find out what's wrong, the last option is to make an archive (tar or zip) that contains a MyODBC trace file, the ODBC log file, and a README file that explains the problem. You can send this to ftp://support.mysql.com/pub/mysql/secret/. Only we at MySQL AB will have access to the files you upload, and we will be very discrete with the data!

If you can create a program that also shows this problem, please upload this too!

If the program works with some other SQL server, you should make an ODBC log file where you do exactly the same thing in the other SQL server.

Remember that the more information you can supply to us, the more likely it is that we can fix the problem!

MySQL C API

C API コードは MySQL とともに配布されます。これは libmysqlclient ライブラリに含まれ、C プログラムからデータベースへ のアクセスを許します。

MySQL ソースディストリビューション内のクライアントの多くは C で書かれています。C API の使 用法を示す例を探すなら、これらのクライアントを調べてください。

他のクライアント API の多く(Java を除く全て)は、MySQL サーバと の通信にこのライブラリを使用します。そのため、例えば、他のクライアントプ ログラムで使用されるのと同じ環境変数の多くの利点を得ることができます。そ れらはライブラリから参照されるからです。これらの変数のリストについては section MySQL Client-Side Scripts and Utilities を参照して下さい。

クライアントは最大通信バッファサイズを持ちます。最初に割り当てられるバッ ファのサイズ(16K バイト)は自動的に最大サイズ(デフォルトは 16M)まで増加し ます。バッファサイズは必要に応じて増加するため、単純にデフォルトの最大制 限を増加しても、さらに内部で資源を使用することはありません。このサイズチェッ クは主に間違ったクエリと通信パケットのためのチェックです。

通信バッファは一つの SQL ステートメント(クライアントからサーバへの通信)と、 返されるデータ(サーバからクライアントへの通信)の1レコードを含むのに 十分大きくなくてはいけません。各スレッドの 通信バッファは、任意のレコードやクエリを処理するために、指定された制限まで動的 に増大します。例えば、最大 16M のデータを含む BLOB 値がある場合、 少なくとも 16M を通信バッファ制限として持つ必要があります(サーバとクライ アントの両方で)。 クライアントのデフォルトの最大値は 16M ですが、サーバの最大値のデフォルトは 1M です。これはサーバ起動時に、max_allowed_packet パラメータの 値を変更することにより、増やすことが出来ます。 See section サーバーパラメーターのチューニング.

MySQL サーバは、各クエリ後に各通信バッファを net_buffer_length バイトに縮小します。 クライアントでは、接続に割り当てられたバッファのサイズは、接続が閉じられるまで減少しません。 クライアントメモリは接続がクローズされた時に調整されます。

スレッドプログラミングについては、 See section スレッドクライアントを作る方法. を参考にしてください。

C API データ型

MYSQL
この構造体は一つのデータベース接続のハンドルを表わします。これはほとんど全て の MySQL 関数に使用されます。
MYSQL_RES
この構造体はレコードを返すクエリ(SELECT, SHOW, DESCRIBE, EXPLAIN)の結果を表わ します。クエリから返される情報は、この節の残りでは結果セットと呼 ばれます。
MYSQL_ROW
これはデータの1レコードの安全な型表現です。これは現在バイト文字列の配列として実 装されています。(フィールド値がバイナリデータを含むことがある場合、これを NULL 終端文字列として扱うことはできません。そのような値は内部に NULL バイトを含 むことがあるからです。) mysql_fetch_row() の呼び出しによりレコードが獲得 されます。
MYSQL_FIELD
この構造体はフィールドについての情報、つまりフィールドの名前、型、サイズ 等を含んでいます。このメンバは後でさらに詳細に説明されています。 mysql_fetch_field() を繰り返し呼び出すことにより、各フィールドの MYSQL_FIELD 構造体を得ることができます。 フィールド値はこの構造体の一部ではありません; それは MYSQL_ROW 構造 体に含まれています。
MYSQL_FIELD_OFFSET
これは、MySQL フィールドリストへのオフセットの安全な型表現です。 (mysql_field_seek() で使用されます。)オフセットはレコード内のフィールド 番号で、0 から始まります。
my_ulonglong
レコード数と mysql_affected_rows(), mysql_num_rows() そして mysql_insert_id() に使用される型です。 この型は 0 から 1.84e19 の範囲を与えます。 システムによっては、my_ulonglong 型の値を表示しようとしても、動作 しないことがあります。この値を表示するには、unsigned long に変換 し、%lu 出力書式を使用してください。例:
printf (Number of rows: %lu\n", (unsigned long) mysql_num_rows(result));

MYSQL_FIELD 構造体は次のメンバを含みます:

char * name
フィールドの名前。null終端文字列。
char * table
このフィールドを含むテーブルの名前。計算されたフィールドでない場合のみ有 効です。計算されたフィールドでは、table 値は空文字列です。
char * def
このフィールドのデフォルト値。null終端文字列。 これは mysql_list_fields() 使用時にだけ設定されます。
enum enum_field_types type
フィールドの型。 type 値は次の一つです:
型の値 型の意味
FIELD_TYPE_TINY TINYINT フィールド
FIELD_TYPE_SHORT SMALLINT フィールド
FIELD_TYPE_LONG INTEGER フィールド
FIELD_TYPE_INT24 MEDIUMINT フィールド
FIELD_TYPE_LONGLONG BIGINT フィールド
FIELD_TYPE_DECIMAL DECIMAL または NUMERIC フィールド
FIELD_TYPE_FLOAT FLOAT フィールド
FIELD_TYPE_DOUBLE DOUBLE または REAL フィールド
FIELD_TYPE_TIMESTAMP TIMESTAMP フィールド
FIELD_TYPE_DATE DATE フィールド
FIELD_TYPE_TIME TIME フィールド
FIELD_TYPE_DATETIME DATETIME フィールド
FIELD_TYPE_YEAR YEAR フィールド
FIELD_TYPE_STRING 文字列 (CHAR または VARCHAR) フィールド
FIELD_TYPE_BLOB BLOB または TEXT フィールド (最大長を確定するには max_length を使用して下さい)
FIELD_TYPE_SET SET フィールド
FIELD_TYPE_ENUM ENUM フィールド
FIELD_TYPE_NULL NULL型 フィールド
FIELD_TYPE_CHAR 非推奨; FIELD_TYPE_TINY を代わりに使用してください
IS_NUM() マクロで、フィールドが数値タイプかどうかをテストできます。 フィールドが数値の場合、type メンバを IS_NUM() に渡すと TRUE と評価します:
if (IS_NUM(field->type))
    printf("Field is numeric\n");
unsigned int length
フィールドの幅。これはテーブル定義で指定されたものです。
unsigned int max_length
結果セットのフィールドの最大幅(実際の結果セットの中のレコードの最長フィールド値 の長さ)。mysql_store_result() または mysql_list_fields() を 使用する場合は、これはフィールドの最大幅になります。 mysql_use_result() を使用する場合は、この変数の値は 0 になります。
unsigned int flags
フィールドの種々のビットフラグ。flags 値は 0 または次のビットの一つ 以上の組み合わせです:
フラグの値 フラグの意味
NOT_NULL_FLAG フィールドは NULL にできない
PRI_KEY_FLAG フィールドはプライマリキーの一部である
UNIQUE_KEY_FLAG フィールドはユニークキーの一部である
MULTIPLE_KEY_FLAG フィールドは非ユニークキーの一部である
UNSIGNED_FLAG フィールドは UNSIGNED 属性を持っている
ZEROFILL_FLAG フィールドは ZEROFILL 属性を持っている
BINARY_FLAG フィールドは BINARY 属性を持っている
AUTO_INCREMENT_FLAG フィールドは AUTO_INCREMENT 属性を持っている
ENUM_FLAG フィールドは ENUM である (非推奨)
SET_FLAG Field is a SET (deprecated)
BLOB_FLAG フィールドは BLOB または TEXT である (非推奨)
TIMESTAMP_FLAG フィールドは TIMESTAMP である (非推奨)
BLOB_FLAG, ENUM_FLAG, SET_FLAG, TIMESTAMP_FLAG の使用は推奨さ れません。これらは型の属性ではなくフィールドの型を示すからです。代わり に field->typeFIELD_TYPE_BLOB, FIELD_TYPE_ENUM, FIELD_TYPE_SET, FIELD_TYPE_TIMESTAMP に対してテストする方をお勧めします。 次の例は flags 値の典型的な使用を示しています:
if (field->flags & NOT_NULL_FLAG)
    printf("Field can't be null\n");
flags 値の真偽状態を調べるために、次の便利なマクロを使用でき ます:
IS_NOT_NULL(flags) このフィールドが NOT NULL として定義されていれば真
IS_PRI_KEY(flags) このフィールドがプライマリキーならば真
IS_BLOB(flags) このフィールドが BLOB または TEXT ならば真 (非推奨; 代わりに field->type をテストして下さい)
unsigned int decimals
数値フィールドの小数部桁数。

C API 関数概要

C API には次に一覧された関数が存在します。これらの関数は次の節でかな り詳細に説明されています。 See section C API 関数説明

Function Description
mysql_affected_rows() 最後の UPDATE, DELETE, INSERT クエリによって変更/削 除/挿入されたレコード数を返します。
mysql_change_user() 接続中ののユーザとデータベースを変更します。
mysql_character_set_name() 接続のデフォルト文字セットの名前を返します。
mysql_close() サーバ接続をクローズします。
mysql_connect() MySQL サーバに接続します。この関数は推奨されません; 代わりに mysql_real_connect() を使用してください。
mysql_create_db() データベースを生成します。この関数は推奨されません; 代わりに SQL コマン ド CREATE DATABASE を使用してください。
mysql_data_seek() クエリ結果セット中の任意のレコードにシークします。
mysql_debug() 与えられた文字列で DBUG_PUSH を行ないます。
mysql_drop_db() データベースを破棄します。この関数は推奨されません; 代わりに SQL コマン ド DROP DATABASE を使用してください。
mysql_dump_debug_info() サーバに、デバッグ情報をログに書き出させます。
mysql_eof() 結果セットの最後のレコードが読まれたかどうかを判定します。この関数は推奨されませ ん; 代わりに mysql_errno() または mysql_error() を使用して下 さい。
mysql_errno() 最後の MySQL 関数からのエラー番号を返します。
mysql_error() 最後の MySQL 関数からのエラーメッセージを返します。
mysql_escape_string() SQL ステートメント内で使用するために文字列中の特殊文字をエスケープします。
mysql_fetch_field() テーブルの次のフィールドの型を返します。
mysql_fetch_field_direct() テーブルの、番号で指定されたフィールドの型を返します。
mysql_fetch_fields() 全てのフィールド構造体の配列を返します。
mysql_fetch_lengths() 現在のレコード中の全てのフィールドの長さを返します。
mysql_fetch_row() 結果セットから次のレコードを取り出します。
mysql_field_seek() 指定されたフィールド上にフィールドカーソルを置きます。
mysql_field_count() 最後のクエリの結果のフィールドの数を返します。
mysql_field_tell() 最後の mysql_fetch_field() で使用されたフィールドカーソルの位置を返 します。
mysql_free_result() 結果セットによって使用されたメモリを解放します。
mysql_get_client_info() クライアントバージョン情報を返します。
mysql_get_host_info() 接続を説明する文字列を返します。
mysql_get_server_version() Returns version number of server as an integer (new in 4.1).
mysql_get_proto_info() 接続に使用されるプロトコルバージョンを返します。
mysql_get_server_info() サーバのバージョン番号を返します。
mysql_info() 最後に実行されたクエリについての情報を返します。
mysql_init() MYSQL 構造体を獲得または初期化します。
mysql_insert_id() AUTO_INCREMENT フィールドに最後に生成された ID を返します。
mysql_kill() 指定されたスレッドを殺します。
mysql_list_dbs() 簡易正規表現に適合するデータベース名を返します。
mysql_list_fields() 簡易正規表現に適合するフィールド名を返します。
mysql_list_processes() 現在のサーバスレッドのリストを返します。
mysql_list_tables() 簡易正規表現に適合するテーブル名を返します。
mysql_num_fields() 結果セット中のフィールド数を返します。
mysql_num_rows() 結果セット中のレコード数を返します。
mysql_options() mysql_connect() のための接続オプションを設定します。
mysql_ping() サーバへの接続が動作しているかどうかをチェックします。 必要であれば再接続します。
mysql_query() NULL 終端文字列として記述された SQL クエリを実行します。
mysql_real_connect() MySQL サーバに接続します。
mysql_real_escape_string() Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.
mysql_real_query() 数えられた文字列として記述された SQL クエリを実行します。
mysql_reload() 権限テーブルを再読み込みするようにサーバに指示します。
mysql_row_seek() 結果セット内のあるレコードへシークします。mysql_row_tell() から返される値を 使用します。
mysql_row_tell() レコードカーソルの位置を返します。
mysql_select_db() データベースを選択します。
mysql_shutdown() データベースサーバをシャットダウンします。
mysql_stat() 文字列でサーバ状態を返します。
mysql_store_result() クライアントに完全な結果セットを取り出します。
mysql_thread_id() 現在のスレッド ID を返します。
mysql_thread_save() Returns 1 if the clients are compiled as thread-safe.
mysql_use_result() 各レコードの動的結果セットを初期化します。

サーバへ接続するには、接続ハンドラを初期化するために mysql_init() を呼びだし、それから mysql_real_connect() をそのハンドラで呼びだし ます (ホスト名、ユーザ名、パスワードのような他の情報に加えて)。 Upon connection, mysql_real_connect() sets the reconnect flag (part of the MYSQL structure) to a value of 1. This flag indicates, in the event that a query cannot be performed because of a lost connection, to try reconnecting to the server before giving up. その接続で の処理が終了した時は、接続を終了させるために mysql_close() を呼びだ します。

接続が有効な間は、クライアントは mysql_query() または mysql_real_query() を使用して SQL クエリをサーバに送信できます。こ の2つの違いは、mysql_query() は NULL終端文字列としてクエリが記述さ れることを期待するのに対し、mysql_real_query() は数えられた文字列を 期待することです。文字列がバイナリデータ(NULバイトを含みことがある)を含む 場合は、mysql_real_query() を使用する必要があります。

SELECT クエリ(例えば、INSERT, UPDATE, DELETE)では、どれくらいのレコードが変更(影響)されたかを mysql_affected_rows() を呼び出すことで見つけ出すことができます。

SELECT クエリでは、選択されたレコードを結果セットとして取り出します。 (注意: いくつかのステートメントは、レコードを返すという点で SELECTに似ています。それは SHOW, DESCRIBE, EXPLAIN です。これらは SELECT ステートメントと同じ方法で扱わ れるべきです。)

クライアントが結果セットを処理するには2つの方法があります。一つ目は、 mysql_store_result() を呼び出すことで、結果セット全体を一度にすべて 取り出すことです。この関数はサーバからクエリによって返されるすべてのレコー ドを取得し、それをクライアントに格納します。二つ目は、 mysql_use_result() を呼び出すことで、レコードごとの結果セット取り出 しを初期化することです。この関数は取り出しを初期化しますが、実際にはサーバ から何のレコードも得ません。

どちらの場合でも、mysql_fetch_row() を呼び出してレコードにアクセス します。mysql_store_result() では、mysql_fetch_row() は既に サーバから取得してあるレコードにアクセスします。 mysql_use_result() では、mysql_fetch_row() は実際にサーバか らレコードを取り出します。各レコードのデータ値のサイズについての情報は mysql_fetch_lengths() を呼び出すことで得られます。

結果セットでの処理が終った後は、mysql_free_result() を呼び出し、そ れが使用していたメモリを解放して下さい。

この2つの取り出し機構は相補的なものです。クライアントプログラムは、必要に よってもっとも適切なアプローチを選択すべきです。慣例的に、クライアントは一 般に mysql_store_result() を使用する傾向にあります。

mysql_store_result() の利点は、すべてのレコードをクライアントに取っ て来るため、連続してレコードをアクセスできるだけでなく、結果セット中の現在 のレコード位置を変更するために、mysql_data_seek()mysql_row_seek() を使用して、結果セットの中を後や前に移動することが できます。また、mysql_num_rows() を呼び出すことで、レコード数を見つ けることもできます。一方、mysql_store_result() の必要メモリは、大き な結果セットではとても高く、out-of-memory 状態に遭遇する可能性が高くなりま す。

mysql_use_result() の利点は、一度に一つのレコードだけを保持するため、 クライアントが結果セットに要求するメモリが少ないことです(そして、割当のオー バーヘッドも少ないので、mysql_use_result() はより速くなります)。不 利な点は、サーバの拘束を避けるため、各レコードを素早く処理する必要があるこ と、結果セット中でレコードのランダムアクセスができないこと(レコードを順番 にアクセスすることしかできません)、そして、すべてのレコードを取り出さない 限り、結果セット中にいくつのレコードがあるかを知ることができないことです。 さらに、あなたが探している情報を、検索の途中で見つけることができて、問題が 解決したとしても、すべてのレコードを取り出さなければなりません

API はクライアントがクエリが SELECT であるかどうかを知ることなしに、 (必要時だけレコードを取り出す)クエリに適切に応答できるようにします。 それぞれの mysql_query()(または mysql_real_query())の後で、 mysql_store_result() を呼び出すことで、これが可能です。結果セットの 呼び出しが成功すると、クエリは SELECT であり、レコードを読むことが できます。結果セット呼び出しが失敗した場合は、結果が実際に期待されたもので あるかどうかを確定するために、mysql_field_count() を呼び出してくだ さい。mysql_field_count() が 0 を返す場合は、クエリはデータを返しま せん(クエリが INSERT, UPDATE, DELETE 等であることを 示します)。つまりレコードが返ることを期待できません。 mysql_field_count() が 0 でない場合は、クエリはレコードを返すべきな のに、返さなかったということです。これはクエリが SELECT で失敗した ということを示します。これをどのように行なうことができるかの例は、 mysql_field_count() の説明を参照してください。

mysql_store_result()mysql_use_result() はどちらも、結果 セットを作るフィールドについての情報(フィールドの数、その名前や型など)を 獲得することができます。mysql_fetch_field() を繰り返し呼び出すこと で順番に、または、mysql_fetch_field_direct() を呼び出すことでレコー ド内のフィールド番号で、レコード内のフィールド情報にアクセスすることができ ます。現在のフィールドカーソル位置は mysql_field_seek() を呼び出す ことで変更できます。フィールドカーソルの設定は、その後の mysql_fetch_field() 呼び出しに影響します。 mysql_fetch_fields() を呼び出すことで、一度にすべてのフィールドの情 報を得ることもできます。

エラーの検出、報告については、mysql_errno()mysql_error() 関数の方法によって、MySQL はエラー情報へのア クセスを提供します。これらは、最後に呼び出された成功または失敗し得る関数に ついてのエラーコードとエラーメッセージを返し、エラーがいつ何で発生したかを 確定することができます。

C API 関数説明

以下の説明では、NULL の引数または戻り値は C プログラミング言語で の NULL を意味します。MySQL NULL 値ではありません。 関数は通常ポインタか整数の値を返します。しかし関数説明に記述がある場合、 ポインタを返す関数は、成功を示すために非 NULL 値を返し、エラーを示すた めに NULL を返します。整数を返す関数は、成功を示すために 0 を返し、 エラーを示すために非0を返します。``非0'' は関数説明が他に述べていない限 り、その意味になることに注意してください; 関数説明が他に述べている場合、 これらに対して 0 以外の固有の値をテストしないでください:

if (result)                   /* 正しい */
    ... error ...

if (result < 0)               /* 間違い */
    ... error ...

if (result == -1)             /* 間違い */
    ... error ...

関数がエラーを返すとき、関数説明の エラー 節が起り得るエラーの 種類を一覧しています。mysql_errno() の呼び出しによってどれが発生 したかを見つけ出すことができます。エラーを表現する文字列は mysql_error() の呼び出しによって得られます。

mysql_affected_rows()

my_ulonglong mysql_affected_rows(MYSQL *mysql)

説明

最後の UPDATE によって変更されたレコード数、または、DELETE によって削除されたレコード数、INSERT によって挿入されたレコード数を 返します。UPDATE, DELETE, INSERT ステートメントでの mysql_query() 直後に呼び出します。SELECT ステートメントでは、 mysql_affected_rows()mysql_num_rows() に似た動きをします。

戻り値

0 より大きい整数は影響された行数または取り出された行数を示します。0 は UPDATE ステートメントで更新されたレコードがないこと、またはクエリの WHERE 節に適合したレコードがないこと、またはまだなんのクエリも実行 していないことを示します。-1 はクエリがエラーを返したこと、あるいは SELECT クエリで、mysql_affected_rows()mysql_store_result() 呼び出しよりも先に呼び出されたことを揣摩します。

エラー

無し。

mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10");
printf("%ld products updated",(long) mysql_affected_rows(&mysql));

If one specifies the flag CLIENT_FOUND_ROWS when connecting to mysqld, mysql_affected_rows() will return the number of rows matched by the WHERE statement for UPDATE statements.

Note that when one uses a REPLACE command, mysql_affected_rows() will return 2 if the new row replaced and old row. This is because in this case one row was inserted after the duplicate was deleted.

mysql_change_user()

my_bool mysql_change_user(MYSQL *mysql, const char *user, const char *password, const char *db)

説明

ユーザを変更し、mysql で示された接続上で、db で示されたデー タベースがデフォルト(現在の)データベースになります。その後のクエリでは、 明示的なデータベースの指定を含んでいないテーブル参照について、このデータベー スがデフォルトになります。

この関数は MySQL 3.23.3 で導入されました。

mysql_change_user() は接続されたユーザが認証されない場合、またはデー タベースを使用する権限を持っていない場合に失敗します。この場合、ユーザとデー タベースは変更されません。

デフォルトデータベースを持ちたくない場合、db パラメータを NULL に設定できます。

戻り値

成功時 0。エラーが発生した場合は非0。

エラー

mysql_real_connect() から得られるものと同じです。

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。
ER_UNKNOWN_COM_ERROR
MySQL サーバはこのコマンドを実装していない(おそらく古いサーバ)。
ER_ACCESS_DENIED_ERROR
ユーザまたはパスワードが間違っている。
ER_BAD_DB_ERROR
データベースが存在しない。
ER_DBACCESS_DENIED_ERROR
ユーザがデータベースへのアクセス権を持っていない。
ER_WRONG_DB_NAME
データベース名が長過ぎる。

if (mysql_change_user(&mysql, "user", "password", "new_database"))
{
   fprintf(stderr, "Failed to change user.  Error: %s\n",
           mysql_error(&mysql));
}

mysql_character_set_name()

const char *mysql_character_set_name(MYSQL *mysql)

Description

Returns the default character set for the current connection.

Starting from MySQL 4.0.6 this command will always ROLLBACK any active transactions, close all temporary tables, unlock all locked tables and reset the state as if one had done a new connect. This will happen even if the user didn't change.

Return Values

The default character set

Errors

None.

mysql_close()

void mysql_close(MYSQL *mysql)

説明

前にオープンされた接続をクローズします。ハンドルが mysql_init() ま たは mysql_connect() で自動的に割り当てられた場合、 mysql_close()mysql で示される接続ハンドルの解放も行ない ます。

戻り値

無し。

エラー

無し。

mysql_connect()

MYSQL *mysql_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd)

説明

この関数は推奨されません。代わりに mysql_real_connect() の使用を お勧めします。

mysql_connect()host 上で動作している MySQL デー タベースエンジンへの接続の確立を試みます。mysql_get_client_info() を除く他のすべての API 関数を実行する前にmysql_connect() が成功終了 している必要があります。

パラメータの意味は mysql_real_connect() の対応するパラメータと同じですが、 接続パラメータは NULL にできることが異なります。この場合 C API は接 続構造体に自動的にメモリを割り当て、mysql_close() 呼び出し時にそれ を解放します。このアプローチの不利な点は接続が失敗した場合にエラーメッセー ジを取り出すことができないことです。(mysql_errno() または mysql_error() からエラー情報を得るには、正しい MYSQL ポイン タを提供する必要があります。)

戻り値

mysql_real_connect() と同じ

エラー

mysql_real_connect() と同じ

mysql_create_db()

int mysql_create_db(MYSQL *mysql, const char *db)

説明

db 引数によって指定されたデータベースを作成します。

この関数は推奨されません。代わりに mysql_query() を使って、SQL CREATE DATABASE ステートメントを発行することをお勧めします。

戻り値

データベースの作成が成功した場合は0。エラーが発生した場合は非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

if(mysql_create_db(&mysql, "my_database"))
{
   fprintf(stderr, "Failed to create new database.  Error: %s\n",
           mysql_error(&mysql));
}

mysql_data_seek()

void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset)

説明

クエリ結果セット中の任意のレコードにシークします。これは、結果セット構造体 がクエリのすべての結果を持っていることを要求します。そのため、 mysql_data_seek()mysql_store_result() と共にだけ使用され、 mysql_use_result() と共には使用できません。

オフセットの値は 0 から mysql_num_rows(result)-1 でなくては なりません。

戻り値

無し。

エラー

無し。

mysql_debug()

void mysql_debug(const char *debug)

説明

与えられた文字列で DBUG_PUSH を行ないます。mysql_debug() は Fred Fish が作成した debug library を使用します。この関数を使用するためには、デバッ グをサポートするように、クライアントライブラリをコンパイルする必要があり ます。 See section MySQL server のデバッグ. See section Debugging a MySQL client.

戻り値

無し。

エラー

無し。

次に示した呼び出しは、クライアントライブラリが、クライアントマシン上の `/tmp/client.trace' にトレースファイルを生成します:

mysql_debug("d:t:O,/tmp/client.trace");

mysql_drop_db()

int mysql_drop_db(MYSQL *mysql, const char *db)

説明

db 引数によって指定されたデータベースを破棄します。

この関数は推奨されません。代わりに mysql_query() を使って、SQL DROP DATABASE ステートメントを発行することをお勧めします。

戻り値

データベースの破棄が成功した場合は0。エラーが発生した場合は非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

if(mysql_drop_db(&mysql, "my_database"))
  fprintf(stderr, "Failed to drop the database: Error: %s\n",
          mysql_error(&mysql));

mysql_dump_debug_info()

int mysql_dump_debug_info(MYSQL *mysql)

説明

いくつかのデバッグ情報をログにダンプするようにサーバに指示します。この動 作をするためには、接続されたユーザが SUPER 権限 (version4.0.2以上。未満はPROCESS 権)を持っていなけ ればなりません。

戻り値

コマンドが成功した場合は0。コマンドが失敗した場合は非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_eof()

my_bool mysql_eof(MYSQL_RES *result)

説明

この関数は推奨されません。mysql_errno()mysql_error() が 代わりに使用できます。

mysql_eof() は結果セットの最後のレコードが読まれたかどうかを調べま す。

mysql_store_result() の呼び出しが成功して、結果セットを入手した場合、 クライアントは一つのオペレーションですべてのセットを受け取ります。この場合、 mysql_fetch_row() から返される NULL は、常に結果セットの終端 に達したことを意味し、mysql_eof() を呼ぶ必要はありません。 hen used with mysql_store_result(), mysql_eof() will always return true.

一方、結果セット取り出しの初期化のために mysql_use_result() を使用 する場合、セットのレコードは mysql_fetch_row() を繰り返し呼ぶことに より、ひとつずつサーバから獲得されます。この処理中に接続上でエラーが発生し 得るため、mysql_fetch_row() からの戻り値 NULL は、通常必ずし も結果セットの終端に達したことを意味しません。この場合 mysql_eof() を使用して、何が起こったかを検出できます。結果セットの 終端に達した場合は mysql_eof() は非0値を返し、エラーが発生した場合 は 0 を返します。

歴史的に mysql_eof() は標準 MySQL エラー関数 mysql_errno()mysql_error() 以前に遡ります。これらのエラー 関数は同じ情報を提供するので、これらの使用が mysql_eof() よりも好ま れます。mysql_eof() は現在推奨されません。(実際、これらは多くの情 報を提供します。エラー関数はエラーが発生した時のエラーの理由を示しますが、 mysql_eof() は真偽値だけを返します。)

戻り値

エラーが発生しなかった場合は0。結果セットの終端に達した場合は非0。

エラー

無し。

次の例は mysql_eof の使用方法を示します:

mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
{
    // do something with data
}
if(!mysql_eof(result))  // mysql_fetch_row() failed due to an error
{
    fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}

しかし、標準 MySQL エラー関数で同じ効果を得ることができます:

mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
{
    // do something with data
}
if(mysql_errno(&mysql))  // mysql_fetch_row() failed due to an error
{
    fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
}

mysql_errno()

unsigned int mysql_errno(MYSQL *mysql)

説明

mysql によって指定された接続上で、最後に呼び出された API 関数の成否のエラーコー ドを返します。戻り値0はエラーが発生しなかったことを意味します。クライア ントエラーメッセージ番号は `errmsg.h' にリストされています。サーバ エラーメッセージ番号は `mysqld_error.h' にリストされています。 In the MySQL source distribution you can find a complete list of error messages and error numbers in the file `Docs/mysqld_error.txt'.

戻り値:

エラーコード値。エラーが発生していない場合は0。

エラー

無し。

mysql_error()

char *mysql_error(MYSQL *mysql)

説明

mysql によって指定された接続上で、 mysql_error() は 最後に呼び出された API 関数の成否を、エラーメッセージとして返します。 エラー発生しなかった場合は空文字列 ("") が返されます。 これは次の2つのテストが同じであることを意味します:

if(mysql_errno(&mysql))
{
    // an error occurred
}

if(mysql_error(&mysql)[0] != '\0')
{
    // an error occurred
}

クライアントエラーメッセージの言語は MySQL クラ イアントライブラリの再コンパイルで変更できます。現在はいくつかの言語で書かれた クライアントエラーメッセージを選択できます。 See section Non-English Error Messages.

戻り値

エラーを表わす文字列。 エラーが発生していない場合は空文字列。

エラー

無し。

mysql_escape_string()

You should use mysql_real_escape_string() instead!

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler as its first argument and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

mysql_fetch_field()

MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)

説明

結果セットの一つのフィールドの定義を MYSQL_FIELD 構造体として返しま す。結果セット内の全てのフィールドについて情報を取り出すには、この関数を繰 り返し呼んでください。mysql_fetch_field() はフィールドが残っていな いと NULL を返します。

mysql_fetch_field() は、新しい SELECT クエリを実行するたびに、 最初のフィールドについての情報を返すようにリセットされます。 mysql_fetch_field() で返されるフィールドは mysql_field_seek() の呼び出しにも影響をうけます。

テーブルを SELECT するために mysql_query() を呼び、しかしま だ mysql_store_result() を呼んでいない場合、 mysql_fetch_field()BLOB フィールドの長さの問い合わせに使 用すると、MySQL はデフォルトの blob 長 (8K bytes) を返します。 (8K サイズになるのは、MySQL は BLOB の最大長を知らないから です。これはいつかコンフィグ可能になるべきです。) 一度結果セットを取り出せ ば、field->max_length は指定したクエリ内でのこのフィールドの最大値 の長さを含みます。

戻り値

現在のフィールドの MYSQL_FIELD 構造体。フィールドが残っていない場合は NULL

エラー

無し。

MYSQL_FIELD *field;

while((field = mysql_fetch_field(result)))
{
    printf("field name %s\n", field->name);
}

mysql_fetch_fields()

MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result)

説明

結果セットのすべての MYSQL_FIELD 構造体の配列を返します。各構造体は 結果セットの一つのフィールドのフィールド定義を提供します。

戻り値

結果セットの全ての項目の MYSQL_FIELD 構造体の配列。

エラー

無し。

unsigned int num_fields;
unsigned int i;
MYSQL_FIELD *fields;

num_fields = mysql_num_fields(result);
fields = mysql_fetch_fields(result);
for(i = 0; i < num_fields; i++)
{
   printf("Field %u is %s\n", i, fields[i].name);
}

mysql_fetch_field_direct()

MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *result, unsigned int fieldnr)

説明

結果セット中のフィールドを示すフィールド番号 fieldnr が与えられ、そ のフィールドのフィールド定義を MYSQL_FIELD 構造体として返します。こ の関数は任意のフィールドについての定義を取り出すことに使用できます。 fieldnr の値は 0 から mysql_num_fields(result)-1 の範囲にす べきです。

戻り値

指定されたフィールドの MYSQL_FIELD 構造体。

エラー

無し。

unsigned int num_fields;
unsigned int i;
MYSQL_FIELD *field;

num_fields = mysql_num_fields(result);
for(i = 0; i < num_fields; i++)
{
    field = mysql_fetch_field_direct(result, i);
    printf("Field %u is %s\n", i, field->name);
}

mysql_fetch_lengths()

unsigned long *mysql_fetch_lengths(MYSQL_RES *result)

説明

結果セット中の現在のレコードのフィールドの長さを返します。フィールドの値をコピーする場合、 この長さ情報は最適化にも有用です。strlen() の呼び出しを回避できる ためです。 さらに、結果セットがバイナリデータを持つ場合は、データのサイズを特定するためにこの関数を使わなければなりません。 なぜなら strlen() は NULL 文字を含むフィールドについての結果を正しく返さないからです。

空フィールドの長さと NULL 値を含むフィールドの長さは 0 です。この2 つのケースを区別する方法については、mysql_fetch_row() の説明を参照 して下さい。

戻り値

各フィールドのサイズ (終端 NUL 文字は含みません)を提供する unsigned long 整数の配列。 エラーが発生した場合は NULL

エラー

mysql_fetch_lengths() は結果セットの現在のレコードについてだけ有効 です。mysql_fetch_row() を呼び出す前、または結果の全てのレコードを 取り出した後にこれを呼んだ場合、NULL が返されます。

MYSQL_ROW row;
unsigned long *lengths;
unsigned int num_fields;
unsigned int i;

row = mysql_fetch_row(result);
if (row)
{
    num_fields = mysql_num_fields(result);
    lengths = mysql_fetch_lengths(result);
    for(i = 0; i < num_fields; i++)
    {
         printf("Column %u is %lu bytes in length.\n", i, lengths[i]);
    }
}

mysql_fetch_row()

MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)

説明

結果セットの次のレコードを取り出します。mysql_store_result() の後に使用すると、 これ以上取り出すレコードがない時は、NULL を返します。 mysql_use_result() の後に使用するなら、 これ以上取り出すレコードがない場合やエラーが発生した場合に NULL を返します。

レコード内の値の数は mysql_num_fields(result) によって与えられます。 rowmysql_fetch_row() の呼び出しからの戻り値を保持する場 合、値へのポインタは row[0] から row[mysql_num_fields(result)-1 としてアクセスされます。レコード内の NULL 値はNULL ポインタによって示されます。

レコードのフィールド値の長さは、mysql_fetch_lengths() の呼び出しで 獲得できます。空フィールドと NULL を含むフィールドはどちらも長さ 0 を持ちます; フィールド値のポインタをチェックすることで、これらを区別でき ます。ポインタが NULL の場合、フィールドは NULL です; そうで なければフィールドは空です。

戻り値

次のレコードの MYSQL_ROW 構造体、エラーが発生したか、もう取り出すレ コードがない場合は NULL

エラー

CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;

num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
   unsigned long *lengths;
   lengths = mysql_fetch_lengths(result);
   for(i = 0; i < num_fields; i++)
   {
       printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
   }
   printf("\n");
}

mysql_field_count()

unsigned int mysql_field_count(MYSQL *mysql)

3.22.24 より前の MySQL バージョンを使用している場合、 unsigned int mysql_num_fields(MYSQL *mysql) を代わりに使用すべきで す。

説明

接続上の最後のクエリのフィールド数を返します。

この関数は通常 mysql_store_result()NULL を返した時(そし てこのように結果セットポインタを持っていない時)に使用されます。この場合、 mysql_store_result() が空でない結果を提供すべきかどうかを調べるため に、mysql_field_count() を呼び出すことができます。これは、クエリが SELECT(または SELECTに似た)ステートメントであるかを知るこ と無しに、クライアントプログラムに、適切な行動をとらせることができます。下 に示される例は、これをどのように行なうことができるかを説明しています。

See section mysql_query() が成功を返した後、mysql_store_result()NULL を返す時があるのは何故?.

戻り値

結果セット中のフィールド番号を表す unsigned integer。

エラー

無し。

MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;

if (mysql_query(&mysql,query_string))
{
    // error
}
else // query succeeded, process any data returned by it
{
    result = mysql_store_result(&mysql);
    if (result)  // there are rows
    {
        num_fields = mysql_num_fields(result);
        // retrieve rows, then call mysql_free_result(result)
    }
    else  // mysql_store_result() returned nothing; should it have?
    {
        if(mysql_field_count(&mysql) == 0)
        {
            // query does not return data
            // (it was not a SELECT)
            num_rows = mysql_affected_rows(&mysql);
        }
        else // mysql_store_result() should have returned data
        {
            fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
        }
    }
}

別の方法は、mysql_field_count(&mysql) 呼び出しを mysql_errno(&mysql) に置き換えることです。この場合、ステートメント が SELECT かどうかを mysql_field_count() の値から推測するの ではなく、直接 mysql_store_result() からのエラーをチェックします。

mysql_field_seek()

MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset)

説明

与えられたオフセットにフィールドカーソルを設定します。次の mysql_fetch_field() の呼び出しはそのオフセットに対応したフィールドを取 り出します。

レコードの最初にシークするには、0 の offset 値を渡してください。

戻り値

フィールドカーソルの前の値。

エラー

無し。

mysql_field_tell()

MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result)

説明

最後の mysql_fetch_field() に使用したフィールドカーソルの位置を返 します。この値は mysql_field_seek() への引数として使用できます。

戻り値

フィールドカーソルの現在のオフセット。

エラー

無し。

mysql_free_result()

void mysql_free_result(MYSQL_RES *result)

説明

mysql_store_result(), mysql_use_result(), mysql_list_dbs() 等によって結果セットに割り当てられたメモリを解放 します。結果セットで何かを行なった時、mysql_free_result() を呼び 出してそれが使用したメモリを解放する必要があります。

戻り値

無し。

エラー

無し。

mysql_get_client_info()

char *mysql_get_client_info(void)

説明

クライアントライブラリバージョンを表わす文字列を返します。

戻り値

MySQL クライアントライブラリバージョンを表わす文字列。

エラー

無し。

mysql_get_server_version()

unsigned long mysql_get_server_version(MYSQL *mysql)

Description

Returns version number of server as an integer (new in 4.1).

Return Values

A number that represents the MySQL server version in format:

main_version*10000 + minor_version *100 + sub_version

For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the server in a client program to know if some capability exits.

Errors

None.

mysql_get_host_info()

char *mysql_get_host_info(MYSQL *mysql)

説明

使用中の接続タイプを表わす文字列を返します。サーバのホスト名を含みます。

戻り値

サーバホスト名と接続タイプを表わす文字列。

エラー

無し。

mysql_get_proto_info()

unsigned int mysql_get_proto_info(MYSQL *mysql)

説明

現在の接続に使用されているプロトコルバージョンを返します。

Return Values

現在の接続に使用されているプロトコルバージョンを表わす符号無し整数値。

エラー

無し。

mysql_get_server_info()

char *mysql_get_server_info(MYSQL *mysql)

説明

サーバのバージョン番号を表わす文字列を返します。

戻り値

サーバのバージョン番号を表わす文字列。

エラー

無し。

mysql_info()

char * mysql_info(MYSQL *mysql)

説明

最も最近に実行されたクエリについての情報を文字列で返します。が、 以下に挙げる構文に限ります。 他の構文ではmysql_info()NULL を返します。 文字列の形式 はクエリの型によって様々です。次に説明します (数値は例です; 文字列はクエ リに適した値を含みます):

INSERT INTO ... SELECT ...
String format: Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 3 Duplicates: 0 Warnings: 0
UPDATE
String format: Rows matched: 40 Changed: 40 Warnings: 0

注意: 複数の値リストがステートメント中に記述された場合にだけ、 mysql_info() は、INSERT ... VALUES ステートメントに非 NULL値を返します。

戻り値

最も最近に実行されたクエリについての追加情報を表わす文字列。クエリに有効 な情報がない場合は NULL ポインタ。

エラー

無し。

mysql_init()

MYSQL * mysql_init(MYSQL *mysql)

説明

mysql_real_connect() に適した MYSQL オブジェクトの割り当て または初期化を行ないます。引数が NULL ポインタの場合、関数は新し いオブジェクトを割り当てて初期化し返します。そうでなければオブジェクトは 初期化され、オブジェクトのアドレスが返されます。新しいオブジェクトが割り 当てられた場合、mysql_close() はこのオブジェクトを解放します。

戻り値

初期化された MYSQL* ハンドル、または新しいオブジェクトを割り当て るのに十分なメモリがなかった場合は NULL ポインタ。

エラー

メモリ不足の場合は NULL が返されます。

mysql_insert_id()

my_ulonglong mysql_insert_id(MYSQL *mysql)

説明

前のクエリによって AUTO_INCREMENT フィールドに生成された ID を返します。 AUTO_INCREMENT フィールドを含むテーブルに INSERT クエリを 実行した後で、この関数を使用してください。

注意: 前のクエリが AUTO_INCREMENT 値を生成しなかった場合、 mysql_insert_id()0 を返します。後のために値を保存する必 要がある場合、値を生成するクエリの直後に mysql_insert_id() を呼び出 すことに気をつけてください。

mysql_insert_id() is updated after INSERT and UPDATE statements that generate an AUTO_INCREMENT value or that set a column value to LAST_INSERT_ID(expr). See section その他の関数.

また、SQL LAST_INSERT_ID() 常に最後に生成された AUTO_INCREMENT 値を含み、クエリ間でリセットされないことに注意して下 さい。その関数の値はサーバ内で保守されるからです。

戻り値

前のクエリによって更新された AUTO_INCREMENT フィールドの値。接続上 の前のクエリがない場合、クエリが AUTO_INCREMENT 値を更新しなかった 場合には 0 が返ります。

エラー

無し。

mysql_kill()

int mysql_kill(MYSQL *mysql, unsigned long pid)

説明

pid で指定されたスレッドを殺すようにサーバに頼みます。

戻り値

成功時0。失敗時非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_list_dbs()

MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild)

説明

サーバ上の、wild 引数で指定された簡易正規表現に適合する、データベー ス名からなる結果セットを返します。wild はワイルドカード文字 `%' または `_' を含むことができます。また、全てのデータベース に適合するように NULL ポインタにできます。mysql_list_dbs() の呼び出しはクエリ SHOW databases [LIKE wild] を実行するのと同様 です。

mysql_free_result() で結果セットを解放する必要があります。

戻り値

成功時 MYSQL_RES 結果セット。失敗した場合は NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_OUT_OF_MEMORY
メモリ不足。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_list_fields()

MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)

説明

与えられたテーブル内の、wild 引数で指定された簡易正規表現に適合する フィールド名からなる結果セットを返します。wild はワイルドカー ド文字 `%' または `_' を含むことができます。また、全てのフィー ルドに適合するように NULL ポインタにできます。 mysql_list_fields() はクエリ SHOW COLUMNS FROM table [LIKE wild] を実行するのと同様です。

注意: mysql_list_fields() の代わりに SHOW COLUMNS FROM tbl_name の使用を勧めます。

mysql_free_result() で結果セットを解放する必要があります。

戻り値

成功時 MYSQL_RES 結果セット。エラーが発生した場合は NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_list_processes()

MYSQL_RES *mysql_list_processes(MYSQL *mysql)

説明

現在のサーバスレッドを示す結果セットを返します。これは mysqladmin processlistSHOW PROCESSLIST クエリで 報告されるものと同じ種類の情報です。

mysql_free_result() で結果セットを解放する必要があります。

戻り値

成功時 MYSQL_RES 結果セット。失敗した場合は NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_list_tables()

MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild)

説明

wild 引数で指定された簡易正規表現に適合する、現在のデータベース 内のテーブル名からなる結果セットを返します。wild はワイルドカード 文字 `%' または `_' を含むことができます。また、全てのテーブル に適合するように NULL ポインタにできます。 mysql_list_tables() はクエリ SHOW tables [LIKE wild] を実 行するのと同様です。

mysql_free_result() で結果セットを解放する必要があります。

戻り値

成功時 MYSQL_RES 結果セット。失敗した場合は NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_num_fields()

unsigned int mysql_num_fields(MYSQL_RES *result)

または

unsigned int mysql_num_fields(MYSQL *mysql)

二番目の形式は MySQL 3.23 以上では動作しません。MYSQL* 引 数を通す場合は、代わりに unsigned int mysql_field_count(MYSQL*mysql) を使用しなくてはいけません。

説明

結果セット中のフィールド数を返します。

注意: 結果セットへのポインタまたは接続ハンドルのいずれかからフィールドの数 を得ることができます。mysql_store_result() または mysql_use_result()NULL を返した(つまり結果セットポイン タが無い)場合、接続ハンドルを使用します。この場合、 mysql_field_count() を呼び出して、mysql_store_result() が空 でない結果を提供すべきかどうかを決定できます。これにより、クライアントプロ グラムはクエリが SELECT(または SELECT に似た)ステートメン トだったかどうかを知ることなしに、適切な行動を取ることができます。以下に示 す例はこれをどのように行なうかを説明しています。

See section mysql_query() が成功を返した後、mysql_store_result()NULL を返す時があるのは何故?.

戻り値

結果セット中のフィールド数を表わす符号無し整数。

エラー

無し。

MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;

if (mysql_query(&mysql,query_string))
{
    // error
}
else // query succeeded, process any data returned by it
{
    result = mysql_store_result(&mysql);
    if (result)  // there are rows
    {
        num_fields = mysql_num_fields(result);
        // retrieve rows, then call mysql_free_result(result)
    }
    else  // mysql_store_result() returned nothing; should it have?
    {
        if (mysql_errno(&mysql))
	{
           fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
	}
        else if (mysql_field_count(&mysql) == 0)
        {
            // query does not return data
            // (it was not a SELECT)
            num_rows = mysql_affected_rows(&mysql);
        }
    }
}

(結果セットが返るべきクエリであることを知っている場合の)方法は、 mysql_errno(&mysql) コールを mysql_field_count(&mysql) が 0 かどうかのチェックに置き換えることです。これは何かが悪い場合にだけ起こり ます。

mysql_num_rows()

my_ulonglong mysql_num_rows(MYSQL_RES *result)

説明

結果セット中のレコード数を返します。

mysql_num_rows() の使用は、結果セットを返すのに mysql_store_result()mysql_use_result() のどちらを使用す るかに依存します。mysql_store_result() を使用する場合、 mysql_num_rows() はすぐに呼ぶことができます。 mysql_use_result() を使用する場合、結果セットの全てのレコードが取り 出されるまで、mysql_num_rows() は正しい値を返しません。

戻り値

結果セットのレコード数。

エラー

無し。

mysql_options()

int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg)

説明

特別な接続オプションを設定し、接続の振舞いに影響を与えるために使用できます。 この関数は複数のオプションを設定するために複数回呼ぶことができます。

mysql_options()mysql_init() の後で、 mysql_connect()mysql_real_connect() の前に呼ばれなければ なりません。

option 引数は設定したいオプションです; arg 引数はオプション に対する値です。オプションが整数の場合、arg は整数値へのポインタで す。

有効なオプション値:

オプション 引数型 機能
MYSQL_OPT_CONNECT_TIMEOUT unsigned int * 接続タイムアウト(秒)。
MYSQL_OPT_COMPRESS 使用しない 圧縮クライアント/サーバプロトコルを使用する。
MYSQL_OPT_LOCAL_INFILE optional pointer to uint If no pointer is given or if pointer points to an unsigned int != 0 the command LOAD LOCAL INFILE is enabled.
MYSQL_OPT_NAMED_PIPE 使用しない NT 上の MySQL サーバへの接続に名前付パイプを使用する。
MYSQL_INIT_COMMAND char * MySQL サーバへの接続時に実行するコマンド。再接続時に自動的に再実行される。
MYSQL_READ_DEFAULT_FILE char * `my.cnf' の代わりに指定されたオプションファイルからオプションを読み込む。
MYSQL_READ_DEFAULT_GROUP char * `my.cnf' または MYSQL_READ_DEFAULT_FILE で指定されたファイルから指定されたグループのオプションを読み込む。

注意: MYSQL_READ_DEFAULT_FILEMYSQL_READ_DEFAULT_GROUP を 使用する場合、client グループが常に読まれます。

オプションファイル中に指定されるグループは次のオプションを含むことができま す:

connect-timeout 接続タイムアウト(秒)。On Linux this timeout is also used for waiting for the first answer from the server.
compress 圧縮クライアント/サーバプロトコルを使用する。
database 接続命令中でデータベースが指定されない場合、このデータベースに接続する。
debug デバッグオプション
disable-local-infile Disable use of LOAD DATA LOCAL.
max_allowed_packet Max size of packet client can read from server.
host デフォルトホスト名
init-command MySQL サーバへの接続時に実行するコマンド。再接続時に自動的に再実行される。
local-infile[=(0|1)] If no argument or argument != 0 then enable use of LOAD DATA LOCAL.
password デフォルトパスワード
pipe NT 上の MySQL サーバへの接続に名前付パイプを使用する。
protocol=(TCP | SOCKET | PIPE | MEMORY) Which protocol to use when connecting to server (New in 4.1)
port デフォルトポート番号
return-found-rows UPDATE 使用時、mysql_info() が更新された行の代わりに見つかった行を返すようにする。
shared-memory-base-name=name Shared memory name to use to connect to server (default is "MySQL"). New in MySQL 4.1.
socket デフォルトソケット番号
user デフォルトユーザ

Note that timeout has been replaced by connect-timeout, but timeout will still work for a while.

オプションファイルについてのさらなる情報は、section `my.cnf' オプションファイル を参照して 下さい。

戻り値

成功の場合は0。未知のオプションを使用した場合は非0。

MYSQL mysql;

mysql_init(&mysql);
mysql_options(&mysql,MYSQL_OPT_COMPRESS,0);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"odbc");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
{
    fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(&mysql));
}

上記は、圧縮クライアント/サーバプロトコルを使用し、my.cnf ファイル 中の odbc セクションから追加オプションを読むように、クライアントに 要求します。

mysql_ping()

int mysql_ping(MYSQL *mysql)

説明

サーバへの接続が動作しているかどうかをチェックします。ダウンしている場合 は、自動的に再接続を試みます。

この関数は、長い間静かにしているクライアントが、サーバが接続をクローズし たかどうかをチェック(と再接続)するために使用できます。

戻り値

サーバが生きている場合0。他の値はエラーを示します。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_query()

int mysql_query(MYSQL *mysql, const char *query)

説明

NULL 終端文字列 query で示される SQL クエリを実行します。クエリはひ とつの SQL ステートメントでなければなりません。終端のセミコロン (`;')や \g をステートメントに追加すべきではありません。

mysql_query() はバイナリデータを含むクエリには使用できません(バ イナリデータは `\0' 文字を含むことがあります。これはクエリ文字列の 最後として解釈されます)。この場合、mysql_real_query() を代わりに 使用してください。

If you want to know if the query should return a result set or not, you can use mysql_field_count() to check for this. See section mysql_field_count().

戻り値

クエリが成功した場合は0。クエリが失敗した場合は非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_real_connect()

MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned int client_flag)

説明

host 上で動作している MySQL データベースエンジンへの接続 の確立を試みます。 mysql_get_client_info() 以外の他の API 関数を実行する前に、 mysql_real_connect() が成功している必要があります。

mysql_real_connect() を呼び出す前に、MYSQL 構造体を獲得ま たは初期化するために mysql_init() を呼ぶ必要があることに注意して ください。

mysql_real_connect() の最初の引数に NULL ポインタを記述す ることもできます。これは C API が接続構造体のメモリを割り当て、 mysql_close() 呼び出し時に自動的に解放されます。この方法の不利な 点は、接続が失敗した場合に mysql_real_connect() からのエラーメッ セージを取り出すことができないことです。

最初の引数が NULL ポインタでない場合は、存在する MYSQL 構 造体のアドレスであるべきです。

戻り値

接続が成功した場合は MYSQL* 接続ハンドルです。接続が失敗した場合 は C NULL ポインタです。 接続に成功すると、戻り値はその最初のパラメータの値と同じです。

エラー

CR_CONN_HOST_ERROR
MySQL サーバへの接続に失敗した。
CR_CONNECTION_ERROR
ローカル MySQL サーバへの接続に失敗した。
CR_IPSOCK_ERROR
IP ソケットの生成に失敗した。
CR_OUT_OF_MEMORY
メモリ不足。
CR_SOCKET_CREATE_ERROR
UNIX ソケットの生成に失敗した。
CR_UNKNOWN_HOST
ホスト名の IP アドレスを見つけるのに失敗した。
CR_VERSION_ERROR
異なるプロトコルバージョンを使用するクライアントライブラリでサーバへの接 続を試みた結果のプロトコルミスマッチ。これは、とても古いクライアントライ ブラリを使用して、--old-protocol オプション付きで開始していない新 しいサーバに接続する場合に発生します。
CR_NAMEDPIPEOPEN_ERROR
Windows 上の名前つきパイプの生成に失敗した。
CR_NAMEDPIPEWAIT_ERROR
Windows 上の名前つきパイプの wait に失敗した。
CR_NAMEDPIPESETSTATE_ERROR
Windows 上のパイプハンドラの獲得に失敗した。
CR_SERVER_LOST
If connect_timeout > 0 and it took longer then connect_timeout seconds to connect to the server or if the server died while executing the init-command.

MYSQL mysql;

mysql_init(&mysql);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
{
    fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(&mysql));
}

By using mysql_options() the MySQL library will read the [client] and [your_prog_name] sections in the `my.cnf' file which will ensure that your program will work, even if someone has set up MySQL in some non-standard way.

Note that upon connection, mysql_real_connect() sets the reconnect flag (part of the MYSQL structure) to a value of 1. This flag indicates, in the event that a query cannot be performed because of a lost connection, to try reconnecting to the server before giving up.

mysql_real_escape_string()

unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length)

説明

This function is used to create a legal SQL string that you can use in a SQL statement. See section 文字列.

from の文字列を、SQL ステートメントとしてサーバに送ることができる ように、現在のキャラクタ・セットを考慮しながら変換します。 結果は to に入り、終端 null 文字を追加します。 変換される文字列は `NUL' (ASCII 0), `\n', `\r', `\', `'', `"', Control-Z です。(see section 文字列と数値をどのように書くか?). (Strictly speaking, MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. This function quotes the other characters to make them easier to read in log files.)

from で示される文字列 はlength バイト長でなければなりません。 to バッファには少なくとも length*2+1 バイト長を割り当てる 必要があります。(最悪の場合、それぞれの文字が2バイトに変換されることがあ り、さらに終端 null バイトのための場所が必要です。) mysql_real_escape_string() が復帰するとき、to の内容は NUL 終端文字列になります。 戻り値は変換された文字列の長さです。終端 null 文字は含みません。

char query[1000],*end;

end = strmov(query,"INSERT INTO test_table values(");
*end++ = '\'';
end += mysql_real_escape_string(&mysql, end,"What's this",11);
*end++ = '\'';
*end++ = ',';
*end++ = '\'';
end += mysql_real_escape_string(&mysql, end,"binary data: \0\r\n",16);
*end++ = '\'';
*end++ = ')';

if (mysql_real_query(&mysql,query,(unsigned int) (end - query)))
{
   fprintf(stderr, "Failed to insert row, Error: %s\n",
           mysql_error(&mysql));
}

上記の strmov() 関数は mysqlclient ライブラリに含まれてい て、strcpy() のように働きますが、最初の引数の終りの null へのポイ ンタを返します。

戻り値

to へ置かれた値の長さ。終端 null 文字は含みません。

エラー

無し。

mysql_real_query()

int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length)

説明

query で示される SQL クエリを実行します。これは length バ イト長です。クエリはひとつの SQL ステートメントでなければなりません。終端 のセミコロン(`;')や \g をステートメントに追加すべきではありま せん。

バイナリデータを含むクエリは mysql_real_query() を使 用しなければなりません。バイナリデータは `\0' 文字を含むこと があるからです。 また、mysql_real_query()mysql_query() よりも速いです。 クエリの strlen() を呼ばないからです。

If you want to know if the query should return a result set or not, you can use mysql_field_count() to check for this. See section mysql_field_count().

戻り値

クエリが成功した場合は0。クエリが失敗した場合は非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_reload()

int mysql_reload(MYSQL *mysql)

説明

MySQL サーバに、アクセス権テーブルを再読み込みするように依頼し ます。接続されたユーザは RELOAD 権限を持つ必要があります。

この関数は推奨されません。代わりに、SQL FLUSH PRIVILEGES ステートメ ントを発行する mysql_query() の使用が推奨されます。

戻り値

成功時0。失敗時非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_row_seek()

MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset)

説明

レコードカーソルをクエリ結果セット中の絶対レコードに設定します。これは、結 果セット構造体がクエリのすべての結果を持っていることを要求します。そのため、 mysql_row_seek()mysql_store_result() と共にだけ使用でき、 mysql_use_result() と共には使用できません。

オフセットは mysql_row_tell() または mysql_row_seek() 呼びだ しからの戻り値であるべきです。この値は単純なレコード番号ではありません;レ コード番号を使用して結果セット内のレコードにシークしたい場合は、 mysql_data_seek() を代わりに使用してください。

戻り値

レコードカーソルの前の値。この値はその後の mysql_row_seek() 呼びだ しに渡すことができます。

エラー

無し。

mysql_row_tell()

MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result)

説明

最後の mysql_fetch_row() についてレコードカーソルの現在の位置を返します。 この値は mysql_row_seek() への引数として使用できます。

mysql_row_tell()mysql_store_result() の後にだけ使用すべ きで、mysql_use_result() の後には使用すべきではありません。

戻り値

行カーソルの現在のオフセット。

エラー

無し。

mysql_select_db()

int mysql_select_db(MYSQL *mysql, const char *db)

説明

mysql で示される現在の接続に、デフォルト(現在の)データベースとし て db で示されるデータベースを使用するように指示します。以降のク エリでは、明示的にデータベースを指定しないテーブル参照について、このデー タベースがデフォルトになります。

接続されたユーザがデータベースを使用する権限を持っていると証明されなけれ ば、mysql_select_db() は失敗します。

戻り値

成功時0。失敗時非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_shutdown()

int mysql_shutdown(MYSQL *mysql)

説明

データベースサーバにシャットダウンするように要求します。接続されたユーザ は SHUTDOWN 権限を持っている必要があります。

戻り値

成功時0。失敗時非0。

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_stat()

char *mysql_stat(MYSQL *mysql)

説明

mysqladmin status で提供されるのと同様の情報を文字列として返しま す。これは秒での uptime と、実行中のスレッド数、問い合わせ数、再読み込み 数、オープンテーブル数を含みます。

戻り値

サーバ状態を表わす文字列。エラーが発生した場合 NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_store_result()

MYSQL_RES *mysql_store_result(MYSQL *mysql)

説明

データを取り出すクエリ(SELECT, SHOW, DESCRIBE, EXPLAIN)が成功する毎に、mysql_store_result() または mysql_use_result() を呼び出す必要があります。

You don't have to call mysql_store_result() or mysql_use_result() for other queries, but it will not do any harm or cause any notable performance if you call mysql_store_result() in all cases. You can detect if the query didn't have a result set by checking if mysql_store_result() returns 0 (more about this later one).

If you want to know if the query should return a result set or not, you can use mysql_field_count() to check for this. See section mysql_field_count().

mysql_store_result() はクエリのすべての結果をクライアントへ読み込み、 MYSQL_RES 構造体を割り当て、この構造体に結果を配置します。

mysql_store_results() returns a null pointer if the query didn't return a result sets (If the query was, for example, an INSERT statement).

mysql_store_results() returns also null pointer if reading of the result set failed. You can check if you got an error by checking if mysql_error() doesn't return a null pointer, if mysql_errno() returns <> 0 or if mysql_field_count() returns <> 0.

返されるレコードが無い場合、空の結果セットが返されます。 (空の結果セットは NULL 戻り値とは異なります。)

一度 mysql_store_result() を呼び出して null ポインターでない 結果を得る事ができたら、結果セット中にいくつのレ コードがあるかを見つけるために、mysql_num_rows() を呼び出すことがで きます。

結果セットからレコードを取り出すために mysql_fetch_row() を呼び出す ことができます。また、結果セット内の現在のレコード位置を設定/取得するため に mysql_row_seek()mysql_row_tell() を呼び出すことができ ます。

一度結果セットで行なうと、mysql_free_result() を呼び出す必要があ ります。

See section mysql_query() が成功を返した後、mysql_store_result()NULL を返す時があるのは何故?.

戻り値

結果の MYSQL_RES 結果構造体。エラーがある場合 NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_OUT_OF_MEMORY
メモリ不足。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

mysql_thread_id()

unsigned long mysql_thread_id(MYSQL *mysql)

説明

現在の接続のスレッド ID を返します。この値は、スレッドを殺すための mysql_kill() への引数として使用できます。

接続が失われて、mysql_ping() で再接続した場合、スレッド ID は変更さ れます。これはスレッド ID を後で使うために取得して格納すべきではないことを 意味します。必要な時にそれを取得すべきです。

戻り値

現在の接続のスレッド ID。

エラー

無し。

mysql_use_result()

MYSQL_RES *mysql_use_result(MYSQL *mysql)

説明

データを取り出すクエリ(SELECT, SHOW, DESCRIBE, EXPLAIN)が成功する毎に、 mysql_store_result() または mysql_use_result() を呼び出す必要があります。

mysql_use_result() は結果セット検索を開始しますが, mysql_store_result() のように、実際にクライアントに結果セットを読み 取りません. 代わりに、各レコードは mysql_fetch_row() 呼びだしが行な われることにより、個々に取り出されます。 mysql_use_result() はクエリの結果を、一時テーブルやローカルバッファ に格納すること無く、サーバから直接読み込みます。これは mysql_store_result() よりもいくらか速く、少ないメモリを使用します。 この場合、クライアントは現在の行と接続バッファ ( max_allowed_packet bytes まで増加する ) のメモリだけを割り当てます。

一方、クライアント側で各行に ついて多くの処理を行なう場合や、ユーザが ^S (スクロール停止) を入 力できるような画面に出力を送る場合は、mysql_use_result() を使用す べきではありません。これはサーバと連携しており、他のスレッドが データが取り出されるテーブルを更新する事を邪魔します。

mysql_use_result() 使用時、NULL 値を取り出すまで mysql_fetch_row() を実行する必要があります。そうしないと、次のク エリは前のクエリから結果を取り出します。これを忘れると、C API はエラー Commands out of sync; You can't run this command now を与えます!

mysql_use_result() から返される結果では、 mysql_data_seek(), mysql_row_seek(), mysql_row_tell(), mysql_num_rows(), mysql_affected_rows() を使用できません。 また、mysql_use_result() が終了するまで他のクエリの発行もできませ ん。(全ての行をフェッチした後に、フェッチされた行数を知るために mysql_num_rows を呼び出すことができます。)

一度結果セットで行なうと、mysql_free_result() を呼び出す必要があ ります。

戻り値

結果の MYSQL_RES 結果構造体。エラーがある場合 NULL

エラー

CR_COMMANDS_OUT_OF_SYNC
不当な順にコマンドが実行された。
CR_OUT_OF_MEMORY
メモリ不足。
CR_SERVER_GONE_ERROR
MySQL サーバがいなくなった。
CR_SERVER_LOST
サーバへの接続がクエリ中に失われた。
CR_UNKNOWN_ERROR
未知のエラーが発生した。

C Threaded Function Descriptions

You need to use the following functions when you want to create a threaded client. See section スレッドクライアントを作る方法.

my_init()

void my_init(void)

Description

This function needs to be called once in the program before calling any MySQL function. This initialises some global variables that MySQL needs. If you are using a thread-safe client library, this will also call mysql_thread_init() for this thread.

This is automatically called by mysql_init(), mysql_server_init() and mysql_connect().

Return Values

None.

mysql_thread_init()

my_bool mysql_thread_init(void)

Description

This function needs to be called for each created thread to initialise thread-specific variables.

This is automatically called by my_init() and mysql_connect().

Return Values

None.

mysql_thread_end()

void mysql_thread_end(void)

Description

This function needs to be called before calling pthread_exit() to free memory allocated by mysql_thread_init().

Note that this function is not invoked automatically by the client library. It must be called explicitly to avoid a memory leak.

Return Values

None.

mysql_thread_safe()

unsigned int mysql_thread_safe(void)

Description

This function indicates whether the client is compiled as thread-safe.

Return Values

1 is the client is thread-safe, 0 otherwise.

C Embedded Server Function Descriptions

You must use the following functions if you want to allow your application to be linked against the embedded MySQL server library. See section libmysqld, the Embedded MySQL Server Library.

If the program is linked with -lmysqlclient instead of -lmysqld, these functions do nothing. This makes it possible to choose between using the embedded MySQL server and a stand-alone server without modifying any code.

mysql_server_init()

int mysql_server_init(int argc, char **argv, char **groups)

Description

This function must be called once in the program using the embedded server before calling any other MySQL function. It starts up the server and initialises any subsystems (mysys, InnoDB, etc.) that the server uses. If this function is not called, the program will crash. If you are using the DBUG package that comes with MySQL, you should call this after you have called MY_INIT().

The argc and argv arguments are analogous to the arguments to main(). The first element of argv is ignored (it typically contains the program name). For convenience, argc may be 0 (zero) if there are no command-line arguments for the server. mysql_server_init() makes a copy of the arguments so it's safe to destroy argv or groups after the call.

The NULL-terminated list of strings in groups selects which groups in the option files will be active. See section `my.cnf' オプションファイル. For convenience, groups may be NULL, in which case the [server] and [emedded] groups will be active.

Example

#include <mysql.h>
#include <stdlib.h>

static char *server_args[] = {
  "this_program",       /* this string is not used */
  "--datadir=.",
  "--key_buffer_size=32M"
};
static char *server_groups[] = {
  "embedded",
  "server",
  "this_program_SERVER",
  (char *)NULL
};

int main(void) {
  mysql_server_init(sizeof(server_args) / sizeof(char *),
                    server_args, server_groups);

  /* Use any MySQL API functions here */

  mysql_server_end();

  return EXIT_SUCCESS;
}

Return Values

0 if okay, 1 if an error occurred.

mysql_server_end()

void mysql_server_end(void)

Description

This function must be called once in the program after all other MySQL functions. It shuts down the embedded server.

Return Values

None.

Common questions and problems when using the C API

mysql_query() が成功を返した後、mysql_store_result()NULL を返す時があるのは何故?

mysql_query() の呼び出しが成功した後に mysql_store_result()NULL を返すことがあります。これが 起こったとき、次の条件のどれかの発生を意味します:

ステートメントが空でない結果を提供するかどうかは mysql_field_count() の呼び出しによっていつでもチェックできます。 mysql_field_count() が 0 を返す場合、結果は空で最後のクエリは値を 返さないステートメントです (例えば、INSERTDELETE)。 mysql_field_count() が非 0 値を返す場合、ステートメントは空でない 結果を提供します。 例はmysql_field_count() 関数の説明を参照してください。

mysql_error() または mysql_errno() を呼び出すことによって エラーのテストもできます。

クエリから得られる結果は何か?

クエリによって返される結果セットに加えて、次の情報も得ることができます:

最後に挿入された行のユニーク ID をどのように得られるか?

AUTO_INCREMENT 属性を持つ項目を含むテーブルにレコードを挿入する場 合、mysql_insert_id() 関数で与えられた ID を得ることができます。

mysql_query() に渡すクエリ文字列内のLAST_INSERT_ID() 関数 を使用することでも、ID を取り出すことができます。

次のコードを実行することで、AUTO_INCREMENT インデックスが使用され たかどうかチェックできます。これは、クエリが AUTO_INCREMENT イン デックスを伴う INSERT だったかどうかもチェックできます:

if (mysql_error(&mysql)[0] == 0 &&
    mysql_num_fields(result) == 0 &&
    mysql_insert_id(&mysql) != 0)
{
    used_id = mysql_insert_id(&mysql);
}

生成された最後の ID は接続毎にサーバ内で維持されています。他のクライアント によって変更はされません。他の AUTO_INCREMENT 項目を非マジック値 (すなわち、NULL でなく 0 でない値) で更新する場合でも、それは変更 されません。

また、他のテーブルにその ID を挿入しようとする場合、次で行なうことができます:

INSERT INTO foo (auto,text)
    VALUES(NULL,'text');              # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table

C API でのリンクの問題

C API でリンクする時、いくつかのシステム上では次のエラーになります:

gcc -g -o client test.o -L/usr/local/lib/mysql -lmysqlclient -lsocket -lnsl

Undefined        first referenced
 symbol          in file
floor            /usr/local/lib/mysql/libmysqlclient.a(password.o)
ld: fatal: Symbol referencing errors. No output written to client

これは、あなたのシステム上では、コンパイル/リンク行の最後に、math ライブ ラリ (-lm) を含める必要があることを意味します。

Building Client Programs

If you compile MySQL clients that you've written yourself or that you obtain from a third-party, they must be linked using the -lmysqlclient -lz option on the link command. You may also need to specify a -L option to tell the linker where to find the library. For example, if the library is installed in `/usr/local/mysql/lib', use -L/usr/local/mysql/lib -lmysqlclient -lz on the link command.

For clients that use MySQL header files, you may need to specify a -I option when you compile them (for example, -I/usr/local/mysql/include), so the compiler can find the header files.

To make the above simpler on Unix we have provied the mysql_config script for you. See section mysql_config, Get compile options for compiling clients.

You can use this to compile a MySQL client by as follows:

CFG=/usr/local/mysql/bin/mysql_config
sh -c "gcc -o progname `$CFG --cflags` progname.c `$CFG --libs`"

The sh -c is need to get the shell to not threat the output from mysql_config as one word.

スレッドクライアントを作る方法

クライアントは `ほとんど' スレッド安全です。一番大きな問題は `net.c' (ソケットから読み込みをするサブルーチンを含むファイル) が割 り込み安全でないことです。これは、サーバからの長い読み込みを中断できるよ うに、自身のアラームを持ちたいだろうという考慮で行なわれました。 If you install interrupt handlers for the SIGPIPE interrupt, the socket handling should be thread-safe.

われわれの Web site で公開している古いバイナリ配布では、 標準クライアントライブラリはスレッドオプションでコンパイルされていません。 (the Windows binaries are by default compiled to be thread safe). Newer binary distributions should have both a normal and a thread-safe client library.

スレッド安全クライアント(MySQLサーバーとの通信時に、 他のスレッドがクライアントのスレッドに interrupt をかけたり、 タイムアウトをセットしたりする) を得るためには、-lmysys, -lstring, -ldbug ライブラリとサーバが使用する net_serv.o を使用しま す。

If you don't need interrupts or timeouts, you can just compile a thread-safe client library (mysqlclient_r) and use this. See section MySQL C API. In this case you don't have to worry about the net_serv.o object file or the other MySQL libraries.

スレッドクライアントを使用する時、`thr_alarm.c' ルーチンを大いに使 用できます。mysys ライブラリからのルーチンを使用する場合、覚えて おかなければならないことは my_init() を最初に呼ぶことだけです!

mysql_real_connect() を除く全ての関数は現在スレッド安全です。スレッ ド安全クライアントライブラリをコンパイルし、それをスレッド安全なマナーで使 用するための方法を、次の注意で説明します。(この mysql_real_connect() についての注意は、実際には mysql_connect() にも有効です。しかし mysql_connect() は推奨 されませんので、とにかく mysql_real_connect() を使用すべきです。)

mysql_real_connect() をスレッド安全にするためには、クライアントを次の コマンドで再コンパイルする必要があります:

shell> ./configure --enable-thread-safe-client

This will create a thread-safe client library libmysqlclient_r. --enable-thread-safe-client. This library is thread safe per connection. You can let two threads share the same connection as long as you do the following:

You need to know the following if you have a thread that is calling MySQL functions which did not create the connection to the MySQL database:

When you call mysql_init() or mysql_connect(), MySQL will create a thread-specific variable for the thread that is used by the debug library (among other things).

If you call a MySQL function, before the thread has called mysql_init() or mysql_connect(), the thread will not have the necessary thread-specific variables in place and you are likely to end up with a core dump sooner or later.

The get things to work smoothly you have to do the following:

  1. Call my_init() at the start of your program if it calls any other MySQL function before calling mysql_real_connect().
  2. Call mysql_thread_init() in the thread handler before calling any MySQL function.
  3. In the thread, call mysql_thread_end() before calling pthread_exit(). This will free the memory used by MySQL thread-specific variables.

You may get some errors because of undefined symbols when linking your client with libmysqlclient_r. In most cases this is because you haven't included the thread libraries on the link/compile line.

libmysqld, the Embedded MySQL Server Library

Overview of the Embedded MySQL Server Library

The embedded MySQL server library makes it possible to run a full-featured MySQL server inside the client application. The main benefits are increased speed and more simple management for embedded applications.

The API is identical for the embedded MySQL version and the client/server version. To change an old threaded application to use the embedded library, you normally only have to add calls to the following functions:

Function When to call
mysql_server_init() Should be called before any other MySQL function is called, preferably early in the main() function.
mysql_server_end() Should be called before your program exits.
mysql_thread_init() Should be called in each thread you create that will access MySQL.
mysql_thread_end() Should be called before calling pthread_exit()

Then you must link your code with `libmysqld.a' instead of `libmysqlclient.a'.

The above mysql_server_xxx functions are also included in `libmysqlclient.a' to allow you to change between the embedded and the client/server version by just linking your application with the right library. See section mysql_server_init().

Compiling Programs with libmysqld

To get a libmysqld library you should configure MySQL with the --with-embedded-server option.

When you link your program with libmysqld, you must also include the system-specific pthread libraries and some libraries that the MySQL server uses. You can get the full list of libraries by executing mysql_config --libmysqld-libs.

The correct flags for compiling and linking a threaded program must be used, even if you do not directly call any thread functions in your code.

Restrictions when using the Embedded MySQL Server

The embedded server has the following limitations:

Some of these limitations can be changed by editing the `mysql_embed.h' include file and recompiling MySQL.

Using Option Files with the Embedded Server

The following is the recommended way to use option files to make it easy to switch between a client/server application and one where MySQL is embedded. See section `my.cnf' オプションファイル.

Things left to do in Embedded Server (TODO)

A Simple Embedded Server Example

This example program and makefile should work without any changes on a Linux or FreeBSD system. For other operating systems, minor changes will be needed. This example is designed to give enough details to understand the problem, without the clutter that is a necessary part of a real application.

To try out the example, create an `test_libmysqld' directory at the same level as the mysql-4.0 source directory. Save the `test_libmysqld.c' source and the `GNUmakefile' in the directory, and run GNU `make' from inside the `test_libmysqld' directory.

`test_libmysqld.c'

/*
 * A simple example client, using the embedded MySQL server library
 */

#include <mysql.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

MYSQL *db_connect(const char *dbname);
void db_disconnect(MYSQL *db);
void db_do_query(MYSQL *db, const char *query);

const char *server_groups[] = {
  "test_libmysqld_SERVER", "embedded", "server", NULL
};

int
main(int argc, char **argv)
{
  MYSQL *one, *two;

  /* mysql_server_init() must be called before any other mysql
   * functions.
   *
   * You can use mysql_server_init(0, NULL, NULL), and it will
   * initialise the server using groups = {
   *   "server", "embedded", NULL
   *  }.
   *
   * In your $HOME/.my.cnf file, you probably want to put:

[test_libmysqld_SERVER]
language = /path/to/source/of/mysql/sql/share/english

   * You could, of course, modify argc and argv before passing
   * them to this function.  Or you could create new ones in any
   * way you like.  But all of the arguments in argv (except for
   * argv[0], which is the program name) should be valid options
   * for the MySQL server.
   *
   * If you link this client against the normal mysqlclient
   * library, this function is just a stub that does nothing.
   */
  mysql_server_init(argc, argv, (char **)server_groups);

  one = db_connect("test");
  two = db_connect(NULL);

  db_do_query(one, "SHOW TABLE STATUS");
  db_do_query(two, "SHOW DATABASES");

  mysql_close(two);
  mysql_close(one);

  /* This must be called after all other mysql functions */
  mysql_server_end();

  exit(EXIT_SUCCESS);
}

static void
die(MYSQL *db, char *fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
  (void)putc('\n', stderr);
  if (db)
    db_disconnect(db);
  exit(EXIT_FAILURE);
}

MYSQL *
db_connect(const char *dbname)
{
  MYSQL *db = mysql_init(NULL);
  if (!db)
    die(db, "mysql_init failed: no memory");
  /*
   * Notice that the client and server use separate group names.
   * This is critical, because the server will not accept the
   * client's options, and vice versa.
   */
  mysql_options(db, MYSQL_READ_DEFAULT_GROUP, "test_libmysqld_CLIENT");
  if (!mysql_real_connect(db, NULL, NULL, NULL, dbname, 0, NULL, 0))
    die(db, "mysql_real_connect failed: %s", mysql_error(db));

  return db;
}

void
db_disconnect(MYSQL *db)
{
  mysql_close(db);
}

void
db_do_query(MYSQL *db, const char *query)
{
  if (mysql_query(db, query) != 0)
    goto err;

  if (mysql_field_count(db) > 0)
  {
    MYSQL_RES   *res;
    MYSQL_ROW    row, end_row;
    int num_fields;

    if (!(res = mysql_store_result(db)))
      goto err;
    num_fields = mysql_num_fields(res);
    while ((row = mysql_fetch_row(res)))
    {
      (void)fputs(">> ", stdout);
      for (end_row = row + num_fields; row < end_row; ++row)
        (void)printf("%s\t", row ? (char*)*row : "NULL");
      (void)fputc('\n', stdout);
    }
    (void)fputc('\n', stdout);
  }
  else
    (void)printf("Affected rows: %lld\n", mysql_affected_rows(db));

  return;

err:
  die(db, "db_do_query failed: %s [%s]", mysql_error(db), query);
}

`GNUmakefile'

# This assumes the MySQL software is installed in /usr/local/mysql
inc      := /usr/local/mysql/include/mysql
lib      := /usr/local/mysql/lib

# If you have not installed the MySQL software yet, try this instead
#inc      := $(HOME)/mysql-4.0/include
#lib      := $(HOME)/mysql-4.0/libmysqld

CC       := gcc
CPPFLAGS := -I$(inc) -D_THREAD_SAFE -D_REENTRANT
CFLAGS   := -g -W -Wall
LDFLAGS  := -static
# You can change -lmysqld to -lmysqlclient to use the
# client/server library
LDLIBS    = -L$(lib) -lmysqld -lz -lm -lcrypt

ifneq (,$(shell grep FreeBSD /COPYRIGHT 2>/dev/null))
# FreeBSD
LDFLAGS += -pthread
else
# Assume Linux
LDLIBS += -lpthread
endif

# This works for simple one-file test programs
sources := $(wildcard *.c)
objects := $(patsubst %c,%o,$(sources))
targets := $(basename $(sources))

all: $(targets)

clean:
	rm -f $(targets) $(objects) *.core

Licensing the Embedded Server

The MySQL source code is covered by the GNU GPL license (see section GNU General Public License). One result of this is that any program which includes, by linking with libmysqld, the MySQL source code must be released as free software (under a license compatible with the GPL).

We encourage everyone to promote free software by releasing code under the GPL or a compatible license. For those who are not able to do this, another option is to purchase a commercial licence for the MySQL code from MySQL AB. For details, please see section MySQL Licenses.

MySQL C++ APIs

MySQL Connector/C++ (or MySQL++) is the official MySQL API for C++. More information can be found at http://www.mysql.com/products/mysql++/.

Borland C++

You can compile the MySQL Windows source with Borland C++ 5.02. (The Windows source includes only projects for Microsoft VC++, for Borland C++ you have to do the project files yourself.)

One known problem with Borland C++ is that it uses a different structure alignment than VC++. This means that you will run into problems if you try to use the default libmysql.dll libraries (that was compiled with VC++) with Borland C++. You can do one of the following to avoid this problem.

MySQL Java Connectivity (JDBC)

There are 2 supported JDBC drivers for MySQL (the Connector/J driver and the Resin JDBC driver). You can find a copy of the Connector/J driver at http://www.mysql.com/products/connector-j/ and the Resin driver at http://www.caucho.com/projects/jdbc-mysql/index.xtp For documentation consult any JDBC documentation and the driver's own documentation for MySQL-specific features.

MySQL Python APIs

MySQLdb provides MySQL support for Python, compliant with the Python DB API version 2.0. It can be found at http://sourceforge.net/projects/mysql-python/.

MySQL Tcl APIs

MySQLtcl is a simple API for accessing a MySQL database server from the Tcl programming language. It can be found at http://www.xdobry.de/mysqltcl/.

MySQL Eiffel wrapper

Eiffel MySQL is an interface to the MySQL database server using the Eiffel programming language, written by Michael Ravits. It can be found at http://efsa.sourceforge.net/archive/ravits/mysql.htm.

You can also find this at: http://www.netpedia.net/hosting/newplayer/

MySQL Ruby API

以下のサイトに、Ruby の MySQL インターフェースがあります。

www.tmtm.org とみたまさひろ氏の Web ページ

Extending MySQL

MySQL Internals

This chapter describes a lot of things that you need to know when working on the MySQL code. If you plan to contribute to MySQL development, want to have access to the bleeding-edge in-between versions code, or just want to keep track of development, follow the instructions in section 開発ソースツリーからのインストール. If you are interested in MySQL internals, you should also subscribe to our internals mailing list. This list is relatively low traffic. For details on how to subscribe, please see section MySQL メーリングリスト. All developers at MySQL AB are on the internals list and we help other people who are working on the MySQL code. Feel free to use this list both to ask questions about the code and to send patches that you would like to contribute to the MySQL project!

MySQL Threads

The MySQL server creates the following threads:

mysqladmin processlist only shows the connection, INSERT DELAYED, and replication threads.

MySQL Test Suite

Until recently, our main full-coverage test suite was based on proprietary customer data and for that reason has not been publicly available. The only publicly available part of our testing process consisted of the crash-me test, a Perl DBI/DBD benchmark found in the sql-bench directory, and miscellaneous tests located in tests directory. The lack of a standardised publicly available test suite has made it difficult for our users, as well developers, to do regression tests on the MySQL code. To address this problem, we have created a new test system that is included in the source and binary distributions starting in Version 3.23.29.

The current set of test cases doesn't test everything in MySQL, but it should catch most obvious bugs in the SQL processing code, OS/library issues, and is quite thorough in testing replication. Our eventual goal is to have the tests cover 100% of the code. We welcome contributions to our test suite. You may especially want to contribute tests that examine the functionality critical to your system, as this will ensure that all future MySQL releases will work well with your applications.

Running the MySQL Test Suite

The test system consist of a test language interpreter (mysqltest), a shell script to run all tests(mysql-test-run), the actual test cases written in a special test language, and their expected results. To run the test suite on your system after a build, type make test or mysql-test/mysql-test-run from the source root. If you have installed a binary distribution, cd to the install root (eg. /usr/local/mysql), and do scripts/mysql-test-run. All tests should succeed. If not, you should try to find out why and report the problem if this is a bug in MySQL. See section Reporting Bugs in the MySQL Test Suite.

If you have a copy of mysqld running on the machine where you want to run the test suite you do not have to stop it, as long as it is not using ports 9306 and 9307. If one of those ports is taken, you should edit mysql-test-run and change the values of the master and/or slave port to one that is available.

You can run one individual test case with mysql-test/mysql-test-run test_name.

If one test fails, you should test running mysql-test-run with the --force option to check if any other tests fails.

Extending the MySQL Test Suite

You can use the mysqltest language to write your own test cases. Unfortunately, we have not yet written full documentation for it - we plan to do this shortly. You can, however, look at our current test cases and use them as an example. The following points should help you get started:

Reporting Bugs in the MySQL Test Suite

If your MySQL version doesn't pass the test suite you should do the following:

MySQL への新しい関数の追加

There are two ways to add new functions to MySQL:

それぞれの方法には、有利な点と不利な点があります:

新しい関数を追加するためにどちらの方法を使用しても、ABS()SOUNDEX() のようなネイティブ関数と同じように使用することができま す。

CREATE FUNCTION/DROP FUNCTION Syntax

CREATE [AGGREGATE] FUNCTION function_name RETURNS {STRING|REAL|INTEGER}
       SONAME shared_library_name

DROP FUNCTION function_name

A user-definable function (UDF) is a way to extend MySQL with a new function that works like native (built in) MySQL functions such as ABS() and CONCAT().

AGGREGATE is a new option for MySQL Version 3.23. An AGGREGATE function works exactly like a native MySQL GROUP function like SUM or COUNT().

CREATE FUNCTION saves the function's name, type, and shared library name in the mysql.func system table. You must have the INSERT and DELETE privileges for the mysql database to create and drop functions.

All active functions are reloaded each time the server starts, unless you start mysqld with the --skip-grant-tables option. In this case, UDF initialisation is skipped and UDFs are unavailable. (An active function is one that has been loaded with CREATE FUNCTION and not removed with DROP FUNCTION.)

For instructions on writing user-definable functions, see section MySQL への新しい関数の追加. For the UDF mechanism to work, functions must be written in C or C++, your operating system must support dynamic loading and you must have compiled mysqld dynamically (not statically).

Note that to make AGGREGATE work, you must have a mysql.func table that contains the column type. If this is not the case, you should run the script mysql_fix_privilege_tables to get this fixed.

新しいユーザ定義関数の追加

UDF 機構が動作するためには、関数は C か C++ で書かれる必要があり、OS が 動的ローディングをサポートする必要があります。MySQL ソース配布 は `sql/udf_example.cc' を含んでいて、これは5つの新しい関数を定義 しています。UDF の呼び出し方法がどのように働くかはこのファイルを参考にし てください。

For mysqld to be able to use UDF functions, you should configure MySQL with --with-mysqld-ldflags=-rdynamic The reason is that to on many platforms (including Linux) you can load a dynamic library (with dlopen()) from a static linked program, which you would get if you are using --with-mysqld-ldflags=-all-static If you want to use an UDF that needs to access symbols from mysqld (like the methaphone example in `sql/udf_example.cc' that uses default_charset_info), you must link the program with -rdynamic (see man dlopen).

SQL ステートメントで使用したいそれぞれの関数について、対応する C (または C++) 関数を定義すべきです。下の説明では、名前 ``xxx'' がサンプル関数名と して使用されています。SQL と C/C++ 使用法を distinquish するために、 XXX() (大文字) は SQL 関数呼び出しを表わし、xxx() (小文字) は C/C++ 関数呼び出しを表わします。

XXX() のインタフェースを実装するために書く C/C++ 関数は:

xxx() (必要)
メイン関数。これは関数結果が計算されるところです。SQL 型と C/C++ 関数の 戻り値型の対応は次に示します:
SQL type C/C++ type
STRING char *
INTEGER long long
REAL double
xxx_init() (オプション)
xxx() の初期化関数。これは次のように使用されます:
xxx_deinit() (オプション)
xxx() の終了関数(deinitialization function)。これは初期化関数によっ て割り当てられたメモリを解放すべきです。

SQL ステートメントが XXX() を呼び出すとき、MySQL は引数 チェックやメモリ割り当てのように、必要なセットアップを行なわせるために、 初期化関数 xxx_init() を呼び出します。xxx_init() がエラー を返す場合、SQL ステートメントはエラーメッセージと共に異常終了し、メイン 関数と終了関数は呼び出されません。そうでなければ、メイン関数 xxx() が各行毎に呼び出されます。全ての行が処理された後、終了関数 xxx_deinit() が、必要な掃除を行なうために、呼び出されます。

For aggregate functions (like SUM()), you must also provide the llowing functions:

xxx_reset() (required)
Reset sum and insert the argument as the initial value for a new group.
xxx_add() (required)
Add the argument to the old sum.

When using aggregate UDF functions MySQL works the following way:

  1. Call xxx_init() to let the aggregate function allocate the memory it will need to store results.
  2. Sort the table according to the GROUP BY expression.
  3. For the first row in a new group, call the xxx_reset() function.
  4. For each new row that belongs in the same group, call the xxx_add() function.
  5. When the group changes or after the last row has been processed, call xxx() to get the result for the aggregate.
  6. Repeat 3-5 until all rows has been processed
  7. Call xxx_deinit() to let the UDF free any memory it has allocated.

全ての関数はスレッド安全でなくてはいけません(メイン関数だけでなく、初期 化関数と終了関数も同様です)。これは変更されうるグローバル変数や静的変数 を割り当てることは許されないことを意味します! メモリが必要な場合は、 xxx_init() で割り当て、xxx_deinit() でそれを解放すべきです。

UDF Calling Sequences

メイン関数は下に示すように宣言されるべきです。戻り値型と引数は、 CREATE FUNCTION ステートメントで、SQL 関数 XXX() の戻り値 をSTRING, INTEGER, REAL のどれに宣言するかに依存し て異なることに注意してください:

STRING 関数では:

char *xxx(UDF_INIT *initid, UDF_ARGS *args,
          char *result, unsigned long *length,
          char *is_null, char *error);

INTEGER 関数では:

long long xxx(UDF_INIT *initid, UDF_ARGS *args,
              char *is_null, char *error);

REAL 関数では:

double xxx(UDF_INIT *initid, UDF_ARGS *args,
              char *is_null, char *error);

初期化と終了関数は次のように宣言します

my_bool xxx_init(UDF_INIT *initid, UDF_ARGS *args, char *message);

void xxx_deinit(UDF_INIT *initid);

initid 引数は3つの関数全てに渡されます。これは UDF_INIT 構造体を示し、関数間で情報を伝達するために使用されます。UDF_INIT 構造体のメンバは下に一覧します。初期化関数は変更したい全てのメンバを埋め るべきです。(メンバにデフォルトを使用するには、未変更のままにしてくださ い。)

my_bool maybe_null
xxx()NULL を返す場合、xxx_init()maybe_null1 に設定すべきです。デフォルト値は、引数のい ずれかが maybe_null として宣言された場合、1 です。
unsigned int decimals
小数部の桁数。デフォルト値はメイン関数に渡される引数の小数部の最大桁数で す。(例えば、関数に 1.34, 1.345, 1.3 が渡された場合、 デフォルトは 3 です。1.345 が 3 桁の小数部を持つためです。)
unsigned int max_length
文字列結果の最大長。デフォルト値は関数の戻り値型に依存して異なります。文 字列関数では、デフォルトは最も長い引数の長さです。整数関数では、デフォル トは 21 桁です。実数関数では、デフォルトは 13 に initid->decimals で示される小数部の桁数を加えたものです。(数値関数では、長さは符号と小数 点文字を含みます。) If you want to return a blob, you can set this to 65K or 16M; this memory is not allocated but used to decide which column type to use if there is a need to temporary store the data.
char *ptr
それ自身の目的のために関数が使用できるポインタです。例えば、関数は割り当 てたメモリを関数間で伝達するために、initid->ptr を使用できます。 xxx_init() では、メモリを獲得し、このポインタに割り当てます:
initid->ptr = allocated_memory;
xxx()xxx_deinit() では、initid->ptr を参照して、 メモリを使用または解放します。

UDF Calling Sequences for aggregate functions

Here follows a description of the different functions you need to define when you want to create an aggregate UDF function.

char *xxx_reset(UDF_INIT *initid, UDF_ARGS *args,
                char *is_null, char *error);

This function is called when MySQL finds the first row in a new group. In the function you should reset any internal summary variables and then set the given argument as the first argument in the group.

In many cases this is implemented internally by reseting all variables and then calling xxx_add().

char *xxx_add(UDF_INIT *initid, UDF_ARGS *args,
              char *is_null, char *error);

This function is called for all rows that belongs to the same group, except for the first row. In this you should add the value in UDF_ARGS to your internal summary variable.

The xxx() function should be declared identical as when you define a simple UDF function. See section UDF Calling Sequences.

This function is called when all rows in the group has been processed. You should normally never access the args variable here but return your value based on your internal summary variables.

All argument processing in xxx_reset() and xxx_add() should be done identically as for normal UDF functions. See section 引数処理.

The return value handling in xxx() should be done identically as for a normal UDF. See section 戻り値とエラー処理.

The pointer argument to is_null and error is the same for all calls to xxx_reset(), xxx_add() and xxx(). You can use this to remember that you got an error or if the xxx() function should return NULL. Note that you should not store a string into *error! This is just a 1 byte flag!

is_null is reset for each group (before calling xxx_reset(). error is never reset.

If isnull or error are set after xxx() then MySQL will return NULL as the result for the group function.

引数処理

args 引数は次に示すメンバを持つ UDF_ARGS 構造体へのポイン タです:

unsigned int arg_count
引数の数。関数が特定の引数の数で呼び出されることを期待する場合は、初期化 関数でこの値をチェックしてください。例えば:
if (args->arg_count != 2)
{
    strcpy(message,"XXX() requires two arguments");
    return 1;
}
enum Item_result *arg_type
引数の型。可能な型の値は STRING_RESULT, INT_RESULT, REAL_RESULT です。 引数が与えられた型であることと、そうでない場合エラーを返すことを確実にす るために、初期化関数で arg_type 配列をチェックしてください。例えば:
if (args->arg_type[0] != STRING_RESULT ||
    args->arg_type[1] != INT_RESULT)
{
    strcpy(message,"XXX() requires a string and an integer");
    return 1;
}
関数の引数が特定の型を要求するための代案として、初期化関数を使用して、 arg_type 要素を求める型に設定できます。これは MySQLxxx() の各呼び出しにこれらの型を引数に強制するようにさせます。例 えば、最初の2つの引数に文字列と整数を強制するように指定するには、 xxx_init() で次を行なってください:
args->arg_type[0] = STRING_RESULT;
args->arg_type[1] = INT_RESULT;
char **args
args->args は、関数が呼ばれる時の引数の一般的な特性について、情報 を初期化関数に伝達します。定数引数 i について、 args->args[i] は引数値のをポイントします。(値への正しいアクセス方 法については後述。)非定数引数について、args->args[i]0 です。定数引数は定数だけを使用する表現で、3, 4*7-2, SIN(3.14) などです。非定数引数は行から行に変更される値を参照する 表現で、項目名や非定数引数で呼び出される関数などです。 メイン関数のそれぞれの呼び出しについて、args->args は現在処理され ている行に渡される実際の引数を含んでいます。 関数は次のように引数 i を参照できます:
unsigned long *lengths
初期化関数では、lengths 配列は各引数についての最大文字列長を示し ます。メイン関数の各呼び出しについては、lengths は、現在処理され ている行に渡される任意の文字列引数の実際の長さを含んでいます。 INT_RESULT, REAL_RESULT 型の引数については、lengths はまだ引数の最大長を含んでいます(初期化関数については)。

戻り値とエラー処理

初期化関数は、エラーが無い場合は 0 を、そうでなければ 1 を 返すべきです。エラーが発生する場合は、xxx_init() は NULL 終端エラー メッセージを message パラメータに格納すべきです。このメッセージは クライアントに返されます。メッセージバッファは MYSQL_ERRMSG_SIZE 文字長ですが、80 文字より小さく保つように試みるべきです。標準的な端末画 面の幅にフィットするようにです。

メイン関数 xxx() の返す値は long longdouble 関 数については関数値です。文字列関数については、resultlength 引数で文字列が返されます。result は少なくとも 255 バイト長のバッファです。これらに内容と戻り値の長さを設定してください。例 えば:

memcpy(result, "result string", 13);
*length = 13;

The result buffer that is passed to the calc function is 255 byte big. If your result fits in this, you don't have to worry about memory allocation for results.

あなたの文字列関数が 255 バイトよりも長い文字列を返す必要がある場合、 xxx_init() 関数または xxx() 関数内で malloc() で領域 を割り当て、xxx_deinit() 関数でそれを解放する必要があります。将来の xxx() 呼び出しによって再利用されるように、割り当てたメモリを UDF_INIT 構造体の ptr スロットに格納できます。 See section UDF Calling Sequences.

メイン関数で NULL 値の戻り値を示すには、is_null1 に設定してください:

*is_null = 1;

To indicate an error return in the main function, set the error parameter to 1:

*error = 1;

xxx() が任意の行について *error1 を設定する場合、 関数値は現在の行についてと、その後の XXX() が呼び出されるステート メントによって処理される任意の行について NULL です。(xxx() は続く行については呼び出しさえされません。) 注意: 3.22.10 より 前の MySQL バージョンでは、*error*is_null の 両方に設定すべきです:

*error = 1;
*is_null = 1;

ユーザ定義関数のコンパイルとインストール

UDF を実装するファイルはサーバが動作するホスト上でコンパイルされインストー ルされないければなりません。この処理はサンプル UDF ファイル `udf_example.cc' について次に説明します。これは MySQL ソー ス配布に含まれています。このファイルは次の関数を含みます:

動的ロード可能ファイルは、次のような何らかのコマンドを使用して、共有オブ ジェクトファイルとしてコンパイルされるべきです:

shell> gcc -shared -o udf_example.so myfunc.cc

MySQL ソースツリーの `sql' ディレクトリ内で次のコマンドを 実行することにより、システムのコンパイラオプションを簡単に正しく見つけ出 すことができます:

shell> make udf_example.o

make が表示するものに似たコンパイルコマンドを実行すべきですが、行 末近くの -c オプションを取り除いて、-o udf_example.so を行 末につけてください。(いくつかのシステムでは、コマンドに -c を残す 必要があります。)

UDF を含む共有オブジェクトをコンパイルすると、それをインストールしてその ことを MySQL に知らせる必要があります。`udf_example.cc' か らの共有オブジェクトのコンパイルは、`udf_example.so' のような何かの ファイル名を提供します(実際の名前はプラットフォームによって変わります)。 このファイルを `/usr/lib' のような ld が探すどこかのディレク トリにコピーしてください。多くのシステムでは、LD_LIBRARY または LD_LIBRARY_PATH 環境変数を設定して、UDF 関数ファイルがあるディレ クトリを示すことができます。dlopen マニュアルページはシステム上で 使用すべき変数を教えてくれます。これを mysql.server または safe_mysqld スタートアップスクリプトに設定し、 mysqld を再起動すべきです。

ライブラリがインストールされた後、mysqld に新しい関数について次の コマンドで通知すべきです:

mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "udf_example.so";
mysql> CREATE FUNCTION myfunc_double RETURNS REAL SONAME "udf_example.so";
mysql> CREATE FUNCTION myfunc_int RETURNS INTEGER SONAME "udf_example.so";
mysql> CREATE FUNCTION lookup RETURNS STRING SONAME "udf_example.so";
mysql> CREATE FUNCTION reverse_lookup
    ->        RETURNS STRING SONAME "udf_example.so";
mysql> CREATE AGGREGATE FUNCTION avgcost
    ->        RETURNS REAL SONAME "udf_example.so";

関数は DROP FUNCTION を使用して削除できます:

mysql> DROP FUNCTION metaphon;
mysql> DROP FUNCTION myfunc_double;
mysql> DROP FUNCTION myfunc_int;
mysql> DROP FUNCTION lookup;
mysql> DROP FUNCTION reverse_lookup;
mysql> DROP FUNCTION avgcost;

CREATE FUNCTIONDROP FUNCTION ステートメントは mysql データベース内のシステムテーブル func を更新します。 関数の名前、型、共有ライブラリ名はテーブルに保存されます。作成と破棄機能 のためには、mysql データベースに INSERTDELETE 権限を持つ必要があります。

既に生成してある関数を追加するために CREATE FUNCTION を使用すべき ではありません。関数の再インストールが必要な場合は、DROP FUNCTION でそれを削除し、それから CREATE FUNCTION で再インストールすべきで す。例えば、関数の新しいバージョンの再コンパイルをした場合、 mysqld が新しいバージョンを得るために、これを行なう必要があるでしょ う。そうでなければ、サーバは古いバージョンの使用を継続します。

mysqld--skip-grant-tables オプションで起動しなくても、 有効な関数はサーバの開始毎に再読み込みされます。この場合、UDF 初期化は飛 ばされ、UDF が無効になります。(有効な関数は CREATE FUNCTION でロー ドされているもので、DROP FUNCTION で削除されていないものです。)

新しいネイティブ関数の追加

ネイティブ関数を追加するためのプロシジャを以下に示します。バイナリ配布に はネイティブ関数を追加できないことに注意してください。プロシジャは MySQL ソースコードの変更を必要とするためです。MySQL を ソース配布から自分でコンパイルする必要があります。また、MySQL の他のバージョンに移行する場合(例えば、新しいバージョンがリリースされた 時)、新しいバージョンでこのプロシジャを繰り返す必要があります。

新しいネイティブ MySQL 関数を追加するためには、次のステップに従っ てください:

  1. sql_functions[] 配列内で関数名を定義している `lex.h' に1行 追加してください。
  2. If the function prototype is simple (just takes zero, one, two or three arguments), you should in lex.h specify SYM(FUNC_ARG#) (where # is the number of arguments) as the second argument in the sql_functions[] array and add a function that creates a function object in `item_create.cc'. Take a look at "ABS" and create_funcs_abs() for an example of this. If the function prototype is complicated (for example takes a variable number of arguments), you should add two lines to `sql_yacc.yy'. 一つは、yacc が定義す べきプリプロセッサシンボルを指示します(これはファイルの先頭に追加すべき です)。それから関数パラメータを定義し、これらのパラメータとともに ``item'' を simple_expr パース規則に追加します。例えば、これがど のように動作するかを見るには、`sql_yacc.yy' 内の ATAN の 全ての出来事をチェックしてください。
  3. `item_func.h' 内で、関数が数値または文字列のどちらを返すかに依存し て、Item_num_func または Item_str_func から継承するクラス を宣言してください。
  4. `item_func.cc' 内で、数値または文字列のどちらの関数を定義するかに依 存して、次の宣言の一つを追加してください:
    double   Item_func_newname::val()
    longlong Item_func_newname::val_int()
    String  *Item_func_newname::Str(String *str)
    
    If you inherit your object from any of the standard items (like Item_num_func you probably only have to define one of the above functions and let the parent object take care of the other functions. For example, the Item_str_func class defines a val() function that executes atof() on the value returned by ::str().
  5. おそらく次のオブジェクト関数も定義すべきです
    void Item_func_newname::fix_length_and_dec()
    
    この関数は与えられた引数に基づいて少なくとも max_length を計算す べきです。max_length は関数が返し得る文字の最大数です。この関数は、 メイン関数が NULL 値を返すことがない場合は、maybe_null = 0 も設定すべきです。関数は、引数の maybe_null 変数をチェックするこ とで、関数の任意の引数が NULL を返しうるかどうかをチェックできま す。 You can take a look at Item_func_mod::fix_length_and_dec for a typical example of how to do this.

全ての関数はスレッド安全である必要があります (In other words, don't use any global or static variables in the functions without protecting them with mutexes).

If you want to return NULL, from ::val(), ::val_int() or ::str() you should set null_value to 1 and return 0.

::str() オブジェクト関数については、次のいくつかの追加検討事項があ ります:

MySQLにプロシージャを追加する

MySQL ではC++で書かれたプロシージャを定義することが できます。 これらのプロシージャを使うとデータが クライアントに送信される前にクエリー内でデータにアクセス、 修正することが可能です。 データの修正は列単位、あるいは グループ単位(GROUP BY)で行えます。

プロシージャを使って何ができるかをご覧いただくために、 MySQL バージョン3.23を使ったサンプルを用意しました。

さらに Contrib ディレクトリにある 'mylua' を参考にされることをお薦めします。 See section Contributed Programs。 myluaではLUA言語を使って、 ランタイム時にプロシージャを mysqld にロードすることができます。

Additionally we recommend you to take a look at mylua. With this you can use the LUA language to load a procedure at runtime into mysqld.

プロシージャ分析

analyse([max elements,[max memory]])

このプロシージャは `sql/sql_analyse.cc' によって定義されています。 クエリーの結果を調べ、 分析結果を返します:

SELECT ... FROM ... WHERE ... PROCEDURE ANALYSE([max elements,[max memory]])

プロシージャの記述

今のところ、 この項目にはソースコードしかありません。

プロシージャに関する全ての情報は以下のファイルにありますのでご覧下さい:

Problems and Common Errors

This chapter lists some common problems and error messages that users have run into. You will learn how to figure out what the problem is, and what to do to solve it. You will also find proper solutions to some common problems.

How to Determine What Is Causing Problems

When you run into problems, the first thing you should do is to find out which program / piece of equipment is causing problems:

If after you have examined all other possibilities and you have concluded that it's the MySQL server or a MySQL client that is causing the problem, it's time to do a bug report for our mailing list or our support team. In the bug report, try to give a very detailed description of how the system is behaving and what you think is happening. You should also state why you think it's MySQL that is causing the problems. Take into consideration all the situations in this chapter. State any problems exactly how they appear when you examine your system. Use the 'cut and paste' method for any output and/or error messages from programs and/or log files!

Try to describe in detail which program is not working and all symptoms you see! We have in the past received many bug reports that just state "the system doesn't work". This doesn't provide us with any information about what could be the problem.

If a program fails, it's always useful to know:

When sending a bug report, you should of follow the outlines described in this manual. See section 質問またはバグ報告.

MySQL 使用時のよくあるいくつかのエラー

This section lists some errors that users frequently get. You will find descriptions of the errors, and how to solve the problem here.

Access denied エラー

See section 何故 Access denied エラーになるのか. See section 特権システムはどのように動くか?.

MySQL server has gone away エラー

このセクションは Lost connection to server during query エラーに関することもカバーします。

MySQL server has gone away エラーのもっとも一般的な理由は、サーバ がタイムアウトで接続をクローズしたことです。デフォルトでは、何も起きない 場合、サーバは 8 時間後に接続をクローズします。 この時間は mysqld 起動時の wait_timeout 変数に与えることにより、変 更できます。

Another common reason to receive the MySQL server has gone away error is because you have issued a ``close'' on your MySQL connection and then tried to run a query on the closed connection.

mysqladmin version を実行することで MySQL が死んでいるかどうか、 また uptime はどれぐらいか、チェックできます。

スクリプトの場合は、自動的に再接続するためにクライアントからクエリを再発 行する必要があります。

この場合、通常これらのエラーコードを得ます: (OS 依存です):

CR_SERVER_GONE_ERROR クライアントがサーバーに問い合わせを送る ことができなかった server.
CR_SERVER_LOST クライアントがサーバーに書き込みを行ったときに はエラーは無かったけれども、問い合わせに対して完全に回答が返ってこない

You will also get this error if someone has kills the running thread with kill #threadid#.

You can check that the MySQL hasn't died by executing mysqladmin version and examining the uptime. If the problem is that mysqld crashed you should concentrate one finding the reason for the crash. You should in this case start by checking if issuing the query again will kill MySQL again. See section What To Do If MySQL Keeps Crashing.

間違っているか大きすぎるクエリをサーバに送った場合にもこのエラーが発生し ます。mysqld が間違ったブロックを得た場合、クライアントの何かが間違った と見なし、接続をクローズします。大きなクエリが必要な場合、例えば大きな BLOB で働かせる場合は、mysqld をオプション -O max_query_size=# (デフォルト 1M) で起動することでクエリ制限を増加できます。拡張メモリ はオンデマンドで割り当てられます。そのため、mysqld は大きなクエリを発行し た時や大きな結果行を返す必要のある時だけ、多くのメモリを割り当てます!

You will also get a lost connection if you are sending a packet >= 16M if your client is older than 4.0.8 and your server is 4.0.8 and above, or the other way around.

If you want to make a bug report regarding this problem, be sure that you include the following information:

See section 質問またはバグ報告.

Can't connect to [local] MySQL server エラー

UNIX 上の MySQL クライアントは mysqld サーバに2つの異なる方法で 接続できます: UNIX ソケット, これはファイルシステム上のファイル(デフォルト `/tmp/mysql.sock')を通して接続します。または TCP/IP, これはポート番 号を通して接続します。Unix ソケットは TCP/IP よりも速いですが、サーバと 同じコンピュータから接続する時しか使えません。UNIX ソケットは、ホスト名 を指定しない場合か、特別なホスト名 localhost を指定した場合に使用され ます。

On Windows, if the mysqld server is running on 9x/Me, you can connect only via TCP/IP. If the server is running on NT/2000/XP and mysqld is started with --enable-named-pipe, you can also connect with named pipes. The name of the named pipe is MySQL. If you don't give a hostname when connecting to mysqld, a MySQL client will first try to connect to the named pipe, and if this doesn't work it will connect to the TCP/IP port. You can force the use of named pipes on Windows by using . as the hostname.

(2002) Can't connect to ... エラーは、通常、MySQL サーバーが システム上に走っていないか、あなたが、間違ったソケットファイルや TCP/IP ポートを使用して mysqld に接続しようとする場合におきます。

サーバー上に mysqld というプロセスが走っているか ( ps を使用して。 Windows の場合はタスクマネージャでみて) 確認することから開始してください! See section MySQL サーバー起動時の問題.

mysqld プロセスが走っているなら、違う接続を試すことでサーバーを 確認することができます(もちろん、ポート番号とソケットのパスはあなたが セットアップしたものとは違うでしょう):

shell> mysqladmin version
shell> mysqladmin variables
shell> mysqladmin -h `hostname` version variables
shell> mysqladmin -h `hostname` --port=3306 version
shell> mysqladmin -h 'ip for your host' version
shell> mysqladmin --protocol=socket --socket=/tmp/mysql.sock version

hostname コマンドはフォワードクオートでなくバッククオテーションで 囲んでいることに注意してください; これは ホスト名 (カレントのホスト名) を mysqladmin コマンドに与えます。

Can't connect to local MySQL server エラーが起こりうる理由として:

もし Can't connect to MySQL server on some_hostname エラーの場合, 何が問題なのかを見つけるために、以下の手順を踏みます:

Host '...' is blocked エラー

以下のエラーの場合:

Host 'hostname' is blocked because of many connection errors.
Unblock with 'mysqladmin flush-hosts'

これは mysqld が多くの 'hostname' ホストからの接続エラー(max _connect_errors) を受けた場合に発生します。 この max_connect_errors 大量発生後、mysqld は何か(クラッカーによる サーバーへのアタックなど)が起こったと判断し、このホストからの接続をいっさい拒否 するようにします。 これを解除するには、mysqladmin flush-hosts コマンドを実行します。

デフォルトでは、10回の接続エラーが発生した場合に、mysqld はそのホストを拒 否します。 この値は以下のようにして簡単に変更できます:

shell> safe_mysqld -O max_connect_errors=10000 &

もしこのエラーがあるホストに対して発生するならば、まず最初にそのホストからの TCP /IP 接続に不具合がないかチェックしてください。 もし TCP/IP 接続が動作していないようなら、 max_connect_errors 値を増やす ことはよくないことです!

Too many connections エラー

もし MySQL に接続しようとして Too many connections となった場合、 これは既に max_connections 分、クライアントから mysqld サーバーへの 接続が行われています。

もしデフォルトの100よりも多い接続を必要とするならば、 max_connections 変数に多くの値を与えて、mysqld を リスタートしなくてはなりません。

実際は、mysqld は (max_connections+1) 個のクライアントからの接続を 許しています。 最後の1個は、 SUPER 権限 (version4.0.2以上。未満は PROCESS 権限)を もつユーザーのために取ってあります。 By not giving this privilege to normal users (they shouldn't need this), an administrator with this privilege can log in and use SHOW PROCESSLIST to find out what could be wrong. See section SHOW PROCESSLIST.

The maximum number of connects MySQL is depending on how good the thread library is on a given platform. Linux or Solaris should be able to support 500-1000 simultaneous connections, depending on how much RAM you have and what your clients are doing.

Some non-transactional changed tables couldn't be rolled back エラー

もし ROLLBACK を試みたときに Warning: Some non-transactional changed tables couldn't be rolled back エラー/警告が出た場合、これは、あなたが使用しているテーブルがトランザクションを サポートしていないということです。 これらの非トランザクションのテーブルは ROLLBACK によって、何の影響も受けません。

The most typical case when this happens is when you have tried to create a table of a type that is not supported by your mysqld binary. If mysqld doesn't support a table type (or if the table type is disabled by a startup option) , it will instead create the table type with the table type that is most resembles to the one you requested, probably MyISAM.

以下の SQL 文でテーブルの型をチェックできます:

SHOW TABLE STATUS LIKE 'table_name'. See section SHOW TABLE STATUS.

You can check the extensions your mysqld binary supports by doing:

show variables like 'have_%'. See section SHOW VARIABLES.

Out of memory エラー

クエリを行って、次のエラーのようなものを得た場合:

mysql: Out of memory at line 42, 'malloc.c'
mysql: needed 8136 byte (8k), memory in use: 12481367 bytes (12189k)
ERROR 2008: MySQL client ran out of memory

エラーは MySQL クライアント mysql に関係することに注意してください。 エラーの理由は単純で、クライアントが結果全体を格納するのに十分なメモリを持っ ていないことです。

この問題を解決するにあたり、まず最初にクエリーが正しいか確認してください。 そのクエリーは大量の結果を返すものでしょうか? もしそうなら、mysql --quick を使用してください。 これは結果を取り出すために mysql_use_result() を使用します。 これはクライアントのロード不足を補います(サーバーより多い領域は取れません)。

Packet too large エラー

MySQL クライアントが max_allowed_packet よりも大きなブロックを mysqld サーバーから得た時、Packet too large エラーを発します。

In MySQL 3.23 the biggest possible packet is 16M (due to limits in the client/server protocol). In MySQL 4.0.1 and up, this is only limited by the amount on memory you have on your server (up to a theoretical maximum of 2G).

A communication packet is a single SQL statement sent to the MySQL server or a single row that is sent to the client.

MySQL クライアントや mysqld サーバーが max_allowed_packet バイトより 大きなパケットを受け取ったた場合、 Packet too large エラーを発して 接続を閉じます。 いくつかのクライアントでは、 Lost connection to MySQL server during query エラーも出すでしょう。

クライアントとサーバーは、自身の max_allowed_packet 変数を持っています。 もし大きなパケットを扱いたい場合には、クライアントとサーバーの両方の max_allowed_packet 値を増やしてください。

It's safe to increase this variable as memory is only allocated when needed; this variable is more a precaution to catch wrong packets between the client/server and also to ensure that you don't accidentally use big packets so that you run out of memory.

If you are using the mysql client, you may specify a bigger buffer by starting the client with mysql --set-variable=max_allowed_packet=8M. Other clients have different methods to set this variable. Please note that --set-variable is deprecated since MySQL 4.0, just use --max-allowed-packet=8M instead.

You can use the option file to set max_allowed_packet to a larger size in mysqld. For example, if you are expecting to store the full length of a MEDIUMBLOB into a table, you'll need to start the server with the set-variable=max_allowed_packet=16M option.

Communication Errors / Aborted Connection

MySQL 3.23.40 からは、mysqld--warnings オプションで たち上げた時にだけ、Aborted connection エラーを出力することが可能です。

もし以下のようなエラーがエラーログファイルに記録されていたら、

010301 14:38:23  Aborted connection 854 to db: 'users' user: 'josh'

See section The Error Log.

これは以下が起きたことを示します:

上記が起きたときには、サーバーは Aborted_clients 変数を増やします。

サーバー変数 Aborted_connects は以下の時に増えます:

Note that the above could indicate that someone is trying to break into your database!

See section SHOW VARIABLES.

Other reasons for problems with Aborted clients / Aborted connections.

The table is full エラー

Can't create/write to file エラー

If you get an error for some queries of type:

Can't create/write to file '\\sqla3fe_0.ism'.

this means that MySQL can't create a temporary file for the result set in the given temporary directory. (The above error is a typical error message on Windows, and the Unix error message is similar.) The fix is to start mysqld with --tmpdir=path or to add to your option file:

[mysqld]
tmpdir=C:/temp

assuming that the `c:\\temp' directory exists. See section `my.cnf' オプションファイル.

Check also the error code that you get with perror. One reason may also be a disk full error;

shell> perror 28
Error code  28:  No space left on device

Commands out of sync Error in Client

Commands out of sync; you can't run this command now をクライアン トコード中で得た場合、クライアント関数を間違った順番で呼び出しました!

これは例えば、mysql_use_result() を使用していて、mysql_free_result( ) を行う前に新しいクエリの実行を試みた場合に発生します。これはまた、データ を返す2つのクエリの実行を、間に mysql_use_result()mysql_store_result() 無しで試みた場合にも発生します。

Ignoring user エラー

以下のエラーの場合:

Found wrong password for user: 'some_user@some_host'; ignoring user

これは mysqld の開始または 'reload' 時に user テーブル内に正しいパ スワードを持たないエントリを見つけたことを意味します。 これは単にエントリが許可システムに拒否されているだけです。

起こり得ることとその解決:

Table 'xxx' doesn't exist エラー

もし Table 'xxx' doesn't existCan't find file: 'xxx' (errno: 2) エラーが出た場合、使用しているデータベースに xxx という名前のテーブルが 見付からなかったことを示します

データベースとテーブルの保存に、MySQL はディレクトリとファイルを使用し、 データベースとテーブルの名前はケース依存です! (Windows ではデータベースとテーブル名はケース非依存です。 クエリ中のテーブルに対する問い合わせは全て、同じケースで書かなくてはなりません!)

SHOW TABLES を使用してデータベースのテーブルを確認できます. See section SHOW 構文.

Can't initialize character set xxx エラー

もし以下のようなエラーが出た場合:

MySQL Connection Failed: Can't initialize character set xxx

これは次を意味します:

File Not Found

ERROR '...' not found (Errcode: 23), Can't open file: ... (errno: 24)errcode 23 errno 24 のエラーを MySQL から得た場合、 これは MySQL に十分なファイル記述子が割り当てられなかったことを意味します。 perror ユーティリティはさらに読みやすい形式のエラーメッセージを与えます:

shell> perror 23
File table overflow
shell> perror 24
Too many open files
shell> perror 11
Resource temporarily unavailable

これは mysqld が多くのファイルを開こうとしたことに起因します。 mysqld に一度に開くファイル数を多く開かないようしたり、あるいは、 mysqld が扱えるファイル記述子の数を与えたりできます。

mysqld が一度に開くファイルの数を少なくするには、-O table_cache=32 オプション(デフォルトは64)を safe_mysqld に与えることで可能です。 また、max_connections の値(デフォルトは90)を少なくするならば、 開くファイル数も少なくできます。

To change the number of file descriptors available to mysqld, you can use the option --open-files-limit=# to safe_mysqld or -O open-files-limit=# to mysqld. See section SHOW VARIABLES. The easiest way to do that is to add the option to your option file. See section `my.cnf' オプションファイル. If you have an old mysqld version that doesn't support this, you can edit the safe_mysqld script. There is a commented-out line ulimit -n 256 in the script. You can remove the '#' character to uncomment this line, and change the number 256 to affect the number of file descriptors available to mysqld.

ulimitopen-files-limit はオペレーティングシステムの 制限内でしかファイル記述子の数を指定できません。 There is also a 'hard' limit that can only be overrided if you start safe_mysqld or mysqld as root (Just remember that you need to also use the --user=.. option in this case). もし OS の制限以上にファイル記述子のオープン数を増やしたい場合、 お使いのオペレーティングシステムのドキュメントを見て対処してください。

tcsh を使用している場合は ulimit は動かないことに注意してください! tcsh は現在の制限をあなたが問い合わせても、違った値を報告するでしょう。 この場合、safe_mysqldsh で起動すべきです!

Installation Related Issues

Problems When Linking with the MySQL Client Library

If you are linking your program and you get errors for unreferenced symbols that start with mysql_, like the following:

/tmp/ccFKsdPa.o: In function `main':
/tmp/ccFKsdPa.o(.text+0xb): undefined reference to `mysql_init'
/tmp/ccFKsdPa.o(.text+0x31): undefined reference to `mysql_real_connect'
/tmp/ccFKsdPa.o(.text+0x57): undefined reference to `mysql_real_connect'
/tmp/ccFKsdPa.o(.text+0x69): undefined reference to `mysql_error'
/tmp/ccFKsdPa.o(.text+0x9a): undefined reference to `mysql_close'

この場合には、-Lpath-to-the-mysql-library -lmysqlclient を、 リンクの 最後に 加えれば解決します。

もし undefined reference エラーで uncompresscompress が定義されていないエラーを受けたならば、 -lz をリンク ラインの 最後に 加えて再リンクしてください!

If you get undefined reference errors for functions that should exist on your system, like connect, check the man page for the function in question, for which libraries you should add to the link line!

If you get undefined reference errors for functions that don't exist on your system, like the following:

mf_format.o(.text+0x201): undefined reference to `__lxstat'

it usually means that your library is compiled on a system that is not 100% compatible with yours. In this case you should download the latest MySQL source distribution and compile this yourself. See section MySQL ソースディストリビューションのインストール.

If you are trying to run a program and you then get errors for unreferenced symbols that start with mysql_ or that the mysqlclient library can't be found, this means that your system can't find the share `libmysqlclient.so' library.

The fix for this is to tell your system to search after shared libraries where the library is located by one of the following methods:

他の解決方法は、あなたのプログラムを -static フラグで static にリンクするか、 動的な MySQL ライブラリをリンク前に移動してから、リンクします。 二つ目の場合は、他のプログラムがそのダイナミックライブラリを使用していないか 注意してください!

一般ユーザで MySQL を動かす方法

mysqld (MySQL サーバ) はいかなるユーザーでも開始し実行することが できます。mysqld をユーザ user_name で実行するように変更するためには、 次を行なう必要があります:

  1. Stop the server if it's running (use mysqladmin shutdown).
  2. user_name が読み書きできるように、データベースディレクトリとその中のファ イルのパーミッションを変更します。(これは UNIX root ユーザーで実行する必 要があるでしょう):
    shell> chown -R user_name /path/to/mysql/datadir
    
    MySQL データベースディレクトリのディレクトリーやファイルがシンボリック リンクの場合、 これらリンクの先のディレクトリとファイルも変更します。chown -R はシンボリ ックリンク先を変更してくれません。
  3. ユーザ user_name でサーバを起動します。または MySQL 3.22 以降を 使用する場合は、mysqld を UNIX root で起動し --user=user_name スイッチを使用します。 mysqld は、接続を許可する前に、与えられた UNIX user user_name で実 行するように切り替えます。
  4. To start the server as the given user name automatically at system startup time, add a user line that specifies the user name to the [mysqld] group of the `/etc/my.cnf' option file or the `my.cnf' option file in the server's data directory. For example:
    [mysqld]
    user=user_name
    

この時点で、あなたの mysqld プロセスは UNIX user user_name で正常 に動作します。

一つのことは変わりません。それは権限許可テーブルです。デフォルト (パーミッションテーブルインストールスクリプトmysql_install_db実行後の権限) では、mysqlデータベースへのアクセスやデータベースの作成、破棄はユーザ MySQL user root だけです。 これを変更しないと、それはそのままです。 root 以外の UNIX userでログインしている時でも、あなたは MySQL root user としてアクセスは可能です - ただプログラムに -u root をクライアントプログラムにオプション指定するだけです。

MySQL に root としてアクセスするには、 コマンドラインで -u root を使用するだけでいいことに注意してください。 UNIX root user や MySQL を走らせている UNIX ユーザーである必要は ないことに注意してください。 MySQL のアクセスパーミッションとMySQL のユーザは、 UNIX ユーザとは完全に別のものです。UNIX ユーザに関係するのは、クライアン トに -u オプションを使用しない場合だけです。この場合、クライアントは MySQL へのログインを、あなたの UNIX ログイン名で試みます。

あなたの UNIX マシンそれ自身が安全でない場合は、少なくとも MySQL ア クセステーブルの MySQL root ユーザにはパスワードを設定すべきです。 どこかの誰かが mysql -u root db_name を行ない、彼が望むことの全てを実行で きてしまうからです。

ファイルパーミッションの問題

ファイルパーミッションの問題がある場合、 例えば、テーブルの生成時に mysql が次を出力する場合:

ERROR: Can't find file: 'path/with/filename.frm' (Errcode: 13)

これは UMASK 環境変数が mysqld 起動時に間違ってセットされていると 考えられます。 デフォルトの umask は 0660 です. これは以下のようにして safe_mysqld 立ち上げ時に変更できます:

shell> UMASK=384  # = 600 in octal
shell> export UMASK
shell> /path/to/safe_mysqld &

By default MySQL will create database and RAID directories with permission type 0700. You can modify this behaviour by setting the UMASK_DIR variable. If you set this, new directories are created with the combined UMASK and UMASK_DIR. For example, if you want to give group access to all new directories, you can do:

shell> UMASK_DIR=504  # = 770 in octal
shell> export UMASK_DIR
shell> /path/to/safe_mysqld &

In MySQL Version 3.23.25 and above, MySQL assumes that the value for UMASK and UMASK_DIR is in octal if it starts with a zero.

See section Environment Variables.

Administration Related Issues

What To Do If MySQL Keeps Crashing

全ての MySQL バージョンはリリースの前に多くのプラットフォームで テストされます。 これは MySQL にいかなるバグもないということを 意味しますが、発見するのが困難で、わずかなバグがあるかもしれません。 もし問題があった場合、何がシステムをクラッシュしているかを見つけようとする事は、 問題を早く修正するためのより良い機会でもあります。

まず最初に, その問題で mysqld デーモンが死ななければならないかどうかか, また はその問題がクライアントで処理しなければならないかどうかを調べるべきです。 mysqladmin version を実行することにより、 mysqld サーバーが どれぐらい稼働していたかわかります。 もし mysqld が死んでいたなら、 を実行することによってあるのかをチェックすることができます. mysqldが死んだなら、 その原因を `mysql-data-directory/`hostname`.err' で見つけれるかもしれません。 See section The Error Log.

Many crashes of MySQL are caused by corrupted index / data files. MySQL will update the data on disk, with the write() system call, after every SQL statement and before the client is notified about the result. (This is not true if you are running with delay_key_write, in which case only the data is written.) This means that the data is safe even if mysqld crashes, as the OS will ensure that the not flushed data is written to disk. You can force MySQL to sync everything to disk after every SQL command by starting mysqld with --flush.

The above means that normally you shouldn't get corrupted tables unless:

何かがクラッシュする理由を知るのは非常に難しいので、まず、他の人で動くも のがあなたでクラッシュするのかどうかをチェックしてください。次のことを行っ てください。

忘れたパスワードをリセットする

If you never set a root password for MySQL, then the server will not require a password at all for connecting as root. It is recommended to always set a password for each user. See section MySQL をクラッカーに対して安全にする方法.

もし MySQL の root ユーザーのパスワードを忘れた場合、 これを以下のようにして入れ直すことが可能です。

  1. mysqld サーバーを kill で落とす。 (kill -9 ではありません!) PID 番号は通常 MySQL データディレクトリに `.pid' ファイルに 書かれています:
    shell> kill `cat /mysql-data-directory/hostname.pid`
    
    これを、 Unix root ユーザーか、MySQL サーバーを実行した ユーザーで行います。
  2. mysqld--skip-grant-tables オプションで起動。
  3. mysqladmin password コマンドでパスワードを変更します。
    shell> mysqladmin -u root password 'mynewpassword'
    
  4. Now you can either stop mysqld and restart it normally, or just load the privilege tables with:
    shell> mysqladmin -h hostname flush-privileges
    
  5. After this, you should be able to connect using the new password.

Alternatively, you can set the new password using the mysql client:

  1. Take down and restart mysqld with the --skip-grant-tables option as described above.
  2. Connect to the mysqld server with:
    shell> mysql -u root mysql
    
  3. Issue the following commands in the mysql client:
    mysql> UPDATE user SET Password=PASSWORD('mynewpassword')
        ->             WHERE User='root';
    mysql> FLUSH PRIVILEGES;
    
  4. After this, you should be able to connect using the new password.
  5. You can now stop mysqld and restart it normally.

MySQL はフルディスクをどのように扱うか?

ディスクフルが起きた場合 MySQL は次のことを行います:

この問題の場合、以下のようにします:

Exceptions to the above behaveour is when you use REPAIR or OPTIMIZE or when the indexes are created in a batch after an LOAD DATA INFILE or after an ALTER TABLE statement.

All of the above commands may use big temporary files that left to themself would cause big problems for the rest of the system. If MySQL gets disk full while doing any of the above operations, it will remove the big temporary files and mark the table as crashed (except for ALTER TABLE, in which the old table will be left unchanged).

MySQL が一時ファイルを格納する場所

MySQL は一時ファイルを格納する場所として TMPDIR 環境変数の値を 使用します。TMPDIR を設定していなければ、MySQL はシステムのデフォルトを 使用します。通常は `/tmp' または `/usr/tmp' です。TMPDIR が 小さすぎる場合、safe_mysqld を編集して、十分な領域がある他のディレクトリ を指すように TMPDIR を設定すべきです! --tmpdir オプションを mysqld に与えることで、一時ファイルディレク トリを指定することも可能です。

MySQL は全ての一時ファイルを ``隠しファイル'' として生成します。 これは mysqld が終了した場合に、一時ファイルが削除されないことを確実にし ます。隠しファイルを使用する '悪い' 側面は、小さすぎる一時ディスクを一杯 にする大きな一時ファイルを見つけられないことです。

ソート時 (ORDER BY または GROUP BY)、MySQL は通常一つまた は二つの一時ファイルを使用します。必要な最大のディスク容量は:

(length of what is sorted + sizeof(database pointer))
* number of matched rows
* 2

sizeof(database_pointer) は通常4ですが、将来本当に大きなテーブル のために大きくなることもあります。

いくつかの SELECT クエリは一時的な SQL テーブルも生成します。これらは隠 しファイルではなく、`SQL_*' という名前です。

ALTER TABLE は一時テーブルをオリジナルテーブルと同じディレクトリ 内に生成します。

If you use MySQL 4.1 or later you can spread load between several physical disks by setting --tmpdir to a list of paths separated by colon : (semicolon ; on Windows). They will be used in round-robin fashion. Note: These paths should end up on different physical disks, not different partitions of the same disk.

MySQL ソケットファイル `/tmp/mysql.sock' を変更する方法、削除から守る方法

もし誰かに MySQL のソケットファイル `/tmp/mysql.sock' が消されるな ら、ほとんどの UNIX がそうであるように、 `/tmp'sticky ビットをたてて 保護します。 root でログインして、以下のようにします:

shell> chmod +t /tmp

これはファイルのオーナーとスーパーユーザー(root) のみが、 `/tmp' のファイルを消すことができます。

sticky ビットが立っているか確認するには、 ls -ld /tmp を行います。 パーミッションの最後のビットが t ならば、セットされています。

You can change the place where MySQL uses / puts the socket file the following ways:

ソケットのテストをする場合、以下のようにします:

shell> mysqladmin --socket=/path/to/socket version

Time Zone Problems

もし SELECT NOW() があなたのローカル時間ではなく GMT を返すなら、 TZ 環境変数をローカルのTimezone に設定しなくてはなりません。 環境変数の設定は、サーバーを実行する前に行われなくてはなりません。 たとえば、safe_mysqldmysql.server スクリプトで 行います。 See section Environment Variables.

Query Related Issues

検索時のケース依存

デフォルトでは MySQL フィールドはケース非依存です (しかし、ケース非依 存にならないいくつかの文字セットはありますsuch as czech)。 これは、col_name LIKE 'a%' で検索した場合、A または a で始まる全てのフィールドを得ることを 意味します。検索をケース依存にしたいのなら、始まりをチェックするには INDEX(column, "A")=1 のようなことを、また、文字列全体が同じかどう かには STRCMP(column, "A") = 0 を使用してください。

単純な比較操作 >=, >, =, <, <=、ソートそしてグループ化は、文字 ``sort val ue'' 上で行われます。同じソート値の文字 (like E, e and 'e)は同じ文字と して扱われます!

In older MySQL versions LIKE comparisons where done on the uppercase value of each character (E == e but E <> 'e. In newer MySQL versions LIKE works just like the other comparison operators.

あるフィールドをいつでもケース依存で扱いたい場合は、それを BINARY として宣言してください。 See section CREATE TABLE 構文.

big5 エンコーディングと呼ばれる中国語データを使用している場合は、全ての 文字項目を BINARY にしてください。これは、big5 エンコーディング文 字のソート順が ascii コードが基になっているため、機能します。

DATE フィールド使用時の問題

日付 DATE の形式は 'YYYY-MM-DD' です。ANSI SQL に従って実際には他 のは許されま せん。更新または SELECT 文中の WHERE 節内ではこの形式を使用すべきです。す なわち:

mysql> SELECT * FROM tbl_name WHERE date >= '1997-05-05';

利便のため MySQL は、日付が数値の文脈で使用されると、日付を自動的に数 値に変換します。これにより、更新と TIMESTAMP, DATE または DATETIME フィールドでの WHERE 時に、わりと自由に日付を指定すること ができます。 (この記述を許すため、句読記号を日付のセパレーターとして使用します。 例えば、'1998-08-15''1998#08#15' は同一です.) もしろんセパレーターのない記述(例:'19980815')も日付として変換してくれま す。

特別な日付 '0000-00-00''0000-00-00' として格納され取り出されま す。 MyODBC を通して '0000-00-00' 日付を使用する時、MyODBC 2 .50.12 以上では自動的に NULL に変換されます。ODBC はこの日付の種類を扱え ないためです。

Because MySQL performs the conversions described above, the following statements work:

mysql> INSERT INTO tbl_name (idate) VALUES (19970505);
mysql> INSERT INTO tbl_name (idate) VALUES ('19970505');
mysql> INSERT INTO tbl_name (idate) VALUES ('97-05-05');
mysql> INSERT INTO tbl_name (idate) VALUES ('1997.05.05');
mysql> INSERT INTO tbl_name (idate) VALUES ('1997 05 05');
mysql> INSERT INTO tbl_name (idate) VALUES ('0000-00-00');

mysql> SELECT idate FROM tbl_name WHERE idate >= '1997-05-05';
mysql> SELECT idate FROM tbl_name WHERE idate >= 19970505;
mysql> SELECT MOD(idate,100) FROM tbl_name WHERE idate >= 19970505;
mysql> SELECT idate FROM tbl_name WHERE idate >= '19970505';

次は動きません

mysql> SELECT idate FROM tbl_name WHERE STRCMP(idate,'19970505')=0;

STRCMP() は文字列関数で、idate を文字に変換して、文字比較を行いま す。 '19970505' は日付には変換してくれず、日付の比較も行いません。

MySQL は日付が正しいかどうかをチェックしないことに注意してください。 間違った日付(例えば '1998-2-31')を格納すると、その間違った日付が格 納されます。

Because MySQL packs dates for storage, it can't store any given date as it would not fit onto the result buffer. The rules for accepting a date are:

If the date cannot be converted to any reasonable value, a 0 is stored in the DATE field, which will be retrieved as 0000-00-00. This is both a speed and convenience issue as we believe that the database's responsiblity is to retrieve the same date you stored (even if the data was not logically correct in all cases). We think it is up to the application to check the dates, and not the server.

NULL 値での問題

SQL の初心者のありがちな混乱は、NULL 値が空文字列 "" と同じ物だと 考えることです。これは正しくありません! 例えば、次のステートメントは全く別の ものです:

mysql> INSERT INTO my_table (phone) VALUES (NULL);
mysql> INSERT INTO my_table (phone) VALUES ("");

両方の文とも phone フィールドに値を挿入していますが、 初めのは NULL 値を挿入し、二番目のは空文字列を挿入しています。 初めのは ``電話番号を知らない'' と見なされ、二番目のは ``彼女は電話を 持っていない'' と見なされます。

SQL では、 NULL は他の全ての値(たとえ NULL でも)と比較した時に、 常に偽になる値です。 NULL を含む式は、特に断りがなければ、常に NULL 値を生成します。次の項目は全て NULL を返します:

mysql> SELECT NULL,1+NULL,CONCAT('Invisible',NULL);

NULL 値がセットされている項目を検索する場合、 =NULL テストを行わないでください。 これは expr = NULL が FALSE なので、なんの行も返しません。 例えば以下の例:

mysql> SELECT * FROM my_table WHERE phone = NULL;

NULL 値を持つフィールドを検索したい場合は、IS NULL テストを使用し なくてはいけま せん。次は NULL 電話番号と空の電話番号を見つける方法を示しています:

mysql> SELECT * FROM my_table WHERE phone IS NULL;
mysql> SELECT * FROM my_table WHERE phone = "";

Note that you can only add an index on a column that can have NULL values if you are using MySQL Version 3.23.2 or newer and are using the MyISAM or InnoDB table type. Version 3.23.2 以前の MySQL では、他の多くの SQL サーバのように、NULL 値を持つ インデックスフィールドを持てません。これらのフィールドは NOT NULL と宣言 しなくてはいけません。

LOAD DATA INFILE でデータを読み込むときは、空のフィールドは '' で 更新されます。 項目を NULL 値にしたい場合は、テキストファイル中に \N を使用すべき です。 リテラルとしての 'NULL' 語が、ある状況下で使用されています。 See section LOAD DATA INFILE 構文.

When using ORDER BY, NULL values are presented first. In versions prior to 4.0.2, if you sort in descending order using DESC, NULL values are presented last. When using GROUP BY, all NULL values are regarded as equal.

To help with NULL handling, you can use the IS NULL and IS NOT NULL operators and the IFNULL() function.

ORDER BY 使用時, NULL 値は最初に提示されます. DESC を使用して降順にソートする時、NULL 値は最後になります。 GROUP BY 使用時, 全ての NULL 値は等しいと見なされます。

NULL 処理を手助けするため、次の関数を使用できます: IS NULL, IS NOT NULL, IFNULL().

いくつかの項目型では、NULL 値はハンドルとして扱われます。 もしテーブル内の最初の TIMESTAMP 項に NULL を挿入するなら、 現在の日付と時刻が挿入されます。もし AUTO_INCREMENT 項にNULL 値を 挿入するなら、 次のシーケンス番号が挿入されます。

alias の問題

GROUP BY, ORDER BY, HAVING 節において 項目を参照するに当たりエイリアスが使用できます。 エイリアスは項目としてより良い名称を与えるのに使用されます:

SELECT SQRT(a*b) as rt FROM table_name GROUP BY rt HAVING rt > 0;
SELECT id,COUNT(*) AS cnt FROM table_name GROUP BY id HAVING cnt > 0;
SELECT id AS "Customer identity" FROM table_name;

ANSI SQL が WHERE 節内でエイリアスを参照することを 許可していないことに注意してください。これは WHERE が実行される時点で 項目の値がまだ決定されていないからです。例えば、以下のクエリは あやまり です

SELECT id,COUNT(*) AS cnt FROM table_name WHERE cnt > 0 GROUP BY id;

どの行が GROUP BY に含まれるかを決めるために WHERE 構文が 実行される一方で、 得られた結果のどの行を使うか確定するために HAVING が使用されます。

Deleting Rows from Related Tables

MySQL は現在 副問い合わせ は未サポート(バージョン4.1以上)です。また、 Version 4.0 以前では DELETE 構文で複数のテーブルを扱う事もサポートしていません。 したがって、2つのテーブルに関連するレコードを消すには、以下のようにして行います:

  1. いくつかの WHERE 条件を使用して、基本となるテーブルから行を SELECT
  2. 同じ条件下で、基本となるテーブルに含まれる行を DELETE
  3. DELETE FROM related_table WHERE related_column IN (selected_rows).

related_column のクエリの合計文字数が、1,048,576 (デフォルトは max_ allowed_packet の値) をこえる場合、 それをいくつかに分割して、複数の DELETE 構文にしなくてはなりません。

related_column がインデックスで、100-1000 のrelated_columnだけを消 す場合、よりはやく DELETE できます。 もし related_column がインデックスでない場合、その速度は IN 節の引 数の数に無関係になります。

Solving Problems with No Matching Rows

複雑なクエリーを行って、もしなんの結果も返さなければ、 そのクエリーの何が悪いかを見つけるため、以下の手続きを行います:

  1. EXPLAIN を使用してクエリーをテストし、明白な間違いを見つけます。 See section EXPLAIN 構文 (SELECTについての情報を得る).
  2. WHERE 節で使用されているフィールドだけを Select してみます
  3. 結果が返ってくるまで、一つ一つクエリーからテーブルを取り除いていきます。 テーブルが大きい場合、LIMIT 10 をクエリーで使用することは良くありません。
  4. 行にマッチすべきであろう項を SELECT してみます。 その場合、select するのは、上記で最後に取り除いたテーブルに対して行います。
  5. If you are comparing FLOAT or DOUBLE columns with numbers that have decimals, you can't use '='. This problem is common in most computer languages because floating-point values are not exact values. In most cases, changing the FLOAT to a DOUBLE will fix this. See section Problems with Floating-Point Comparison.
  6. もしなにも悪いところを見つけることができなかった場合、 小さなテストをつくって mysql test < query.sql を行ってみてください。 mysqldump --quick database tables > query.sql でテストファイルを作成でき ます。 このファイルをエディターで編集し、いくつかのinsert行を(多すぎるなら)消します。 そしてファイルの最後にselect構文を付け足します。 テストを行うには:
    shell> mysqladmin create test2
    shell> mysql test2 < query.sql
    
    mysqlbug を使用して mysql@lists.mysql.com にテストを投稿してくだ さい。

Problems with Floating-Point Comparison

floating-point numbers cause confusion sometimes, because these numbers are not stored as exact values inside computer architecture. What one can see on the screen usually is not the exact value of the number.

Field types FLOAT, DOUBLE and DECIMAL are such.

CREATE TABLE t1 (i INT, d1 DECIMAL(9,2), d2 DECIMAL(9,2));
INSERT INTO t1 VALUES (1, 101.40, 21.40), (1, -80.00, 0.00),
(2, 0.00, 0.00), (2, -13.20, 0.00), (2, 59.60, 46.40),
(2, 30.40, 30.40), (3, 37.00, 7.40), (3, -29.60, 0.00),
(4, 60.00, 15.40), (4, -10.60, 0.00), (4, -34.00, 0.00),
(5, 33.00, 0.00), (5, -25.80, 0.00), (5, 0.00, 7.20),
(6, 0.00, 0.00), (6, -51.40, 0.00);

mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b
    -> FROM t1 GROUP BY i HAVING a <> b;
+------+--------+-------+
| i    | a      | b     |
+------+--------+-------+
|    1 |  21.40 | 21.40 |
|    2 |  76.80 | 76.80 |
|    3 |   7.40 |  7.40 |
|    4 |  15.40 | 15.40 |
|    5 |   7.20 |  7.20 |
|    6 | -51.40 |  0.00 |
+------+--------+-------+

The result is correct. Although the first five records look like they shouldn't pass the comparison test, they may do so because the difference between the numbers show up around tenth decimal, or so depending on computer architecture.

The problem cannot be solved by using ROUND() (or similar function), because the result is still a floating-point number. Example:

mysql> SELECT i, ROUND(SUM(d1), 2) AS a, ROUND(SUM(d2), 2) AS b
    -> FROM t1 GROUP BY i HAVING a <> b;
+------+--------+-------+
| i    | a      | b     |
+------+--------+-------+
|    1 |  21.40 | 21.40 |
|    2 |  76.80 | 76.80 |
|    3 |   7.40 |  7.40 |
|    4 |  15.40 | 15.40 |
|    5 |   7.20 |  7.20 |
|    6 | -51.40 |  0.00 |
+------+--------+-------+

This is what the numbers in column 'a' look like:

mysql> SELECT i, ROUND(SUM(d1), 2)*1.0000000000000000 AS a,
    -> ROUND(SUM(d2), 2) AS b FROM t1 GROUP BY i HAVING a <> b;
+------+----------------------+-------+
| i    | a                    | b     |
+------+----------------------+-------+
|    1 |  21.3999999999999986 | 21.40 |
|    2 |  76.7999999999999972 | 76.80 |
|    3 |   7.4000000000000004 |  7.40 |
|    4 |  15.4000000000000004 | 15.40 |
|    5 |   7.2000000000000002 |  7.20 |
|    6 | -51.3999999999999986 |  0.00 |
+------+----------------------+-------+

Depending on the computer architecture you may or may not see similar results. Each CPU may evaluate floating-point numbers differently. For example in some machines you may get 'right' results by multiplaying both arguments with 1, an example follows.

WARNING: NEVER TRUST THIS METHOD IN YOUR APPLICATION, THIS IS AN EXAMPLE OF A WRONG METHOD!!!

mysql> SELECT i, ROUND(SUM(d1), 2)*1 AS a, ROUND(SUM(d2), 2)*1 AS b
    -> FROM t1 GROUP BY i HAVING a <> b;
+------+--------+------+
| i    | a      | b    |
+------+--------+------+
|    6 | -51.40 | 0.00 |
+------+--------+------+

The reason why the above example seems to be working is that on the particular machine where the test was done, the CPU floating-point arithmetics happens to round the numbers to same, but there is no rule that any CPU should do so, so it cannot be trusted.

The correct way to do floating-point number comparison is to first decide on what is the wanted tolerance between the numbers and then do the comparsion against the tolerance number. For example, if we agree on that floating-point numbers should be regarded the same, if they are same with precision of one of ten thousand (0.0001), the comparsion should be done like this:

mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b FROM t1
    -> GROUP BY i HAVING ABS(a - b) > 0.0001;
+------+--------+------+
| i    | a      | b    |
+------+--------+------+
|    6 | -51.40 | 0.00 |
+------+--------+------+
1 row in set (0.00 sec)

And vice versa, if we wanted to get rows where the numbers are the same, the test would be:

mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b FROM t1
    -> GROUP BY i HAVING ABS(a - b) < 0.0001;
+------+-------+-------+
| i    | a     | b     |
+------+-------+-------+
|    1 | 21.40 | 21.40 |
|    2 | 76.80 | 76.80 |
|    3 |  7.40 |  7.40 |
|    4 | 15.40 | 15.40 |
|    5 |  7.20 |  7.20 |
+------+-------+-------+

Table Definition Related Issues

Problems with ALTER TABLE.

ALTER TABLE changes a table to the current character set. If you get a duplicate key error during ALTER TABLE, then the cause is either that the new character sets maps two keys to the same value or that the table is corrupted, in which case you should run REPAIR TABLE on the table.

もし ALTER TABLE が以下のようなエラーで死んだ場合:

Error on rename of './database/name.frm' to './database/B-a.frm' (Errcode: 17)

これは以前の ALTER TABLE で MySQL がクラッシュしており、 `A-something'`B-something' という名前の、誤った情報を流している 古いテーブルが存在しています。 この場合、MySQL データディレクトリに入り、A-B- で始まる 名前を持つファイルを全て消します。 (消す代わりにどこかに移動しても構いません。)

ALTER TABLE は以下のように動作します:

もし名称変更の際に問題があると、MySQL は変更を取り消すように動きます。 致命的な問題が起きた場合(ありえませんが)、MySQL は元の古いテーブルを `B-xxx' という名前のままにしておきます。単にシステムレベルで名称変更すれば データは戻ります。

テーブル中でフィールドの順序を入れ替える方法

SQLの主な目的はデータフォーマットからアプリケーションを切り離してしまうことにあります。そのため、常に取り出したいデータの順序を常に指定する必要があります。例えば、次のような文:

SELECT col_name1, col_name2, col_name3 FROM tbl_name;

これは、col_name1, col_name2, col_name3, の順序でデータを返します。ここで、

SELECT col_name1, col_name3, col_name2 FROM tbl_name;

こうすると、col_name1, col_name3, col_name2, の順序でデータを返します。

アプリケージョン内でSELECT *やそのテーブル内での位置に依存してしまうような 取り出し方はけっしてするべきではありません。 というのは取り出されるデータの順序が常に保障されるものではないからです。 単にフィールドの情報が変更されただけでアプリケーションがエラーが発生する可能性を有しているのです。

にもかかわらずフィールドの順序を変えたい場合には次のような方法があります。

  1. 新しいテーブルを望んでいるフィールドの順序で作成します。
  2. INSERT INTO new_table SELECT fields-in-new_table-order FROM old_table. を実行します。
  3. old_tableをドロップするかリネームして下さい。
  4. ALTER TABLE new_table RENAME old_table. を実行します。

You should never, in an application, use SELECT * and retrieve the columns based on their position, because the order and position in which columns are returned cannot may not remain the same (if you add/move/delete columns). A simple change to your database structure would then cause your application to fail. Of course SELECT * is quite suitable for testing queries.

TEMPORARY TABLE 問題

TEMPORARY TABLESを用いる処理における制限を以下に示します。

Contributed Programs

Many users of MySQL have contributed very useful support tools and add-ons.

A list of some software available from the MySQL website (or any mirror) is shown here.

You can also visit our online listing of MySQL-related software at http://www.mysql.com/portal/software/. The community facilities there also allow for your input!

If you want to build MySQL support for the Perl DBI/DBD interface, you should fetch the Data-Dumper, DBI, and Msql-Mysql-modules files and install them. See section Perl Installation Comments.

Note: The programs listed here can be freely downloaded and used. They are copyrighted by their respective owners. Please see individual product documentation for more details on licensing and terms. MySQL AB assumes no liability for the correctness of the information in this chapter or for the proper operation of the programs listed herein.

APIs

Converters

Utilities

Credits

This appendix lists the developers, contributors, and supporters that have helped to make MySQL what it is today.

Developers at MySQL AB

These are the developers that are or have been employed by MySQL AB to work on the MySQL database software, roughly in the order they started to work with us. Following each developer is a small list of the tasks that the developer is responsible for, or the accomplishments they have made. All developers are involved in support.

Michael (Monty) Widenius
David Axmark
Jani Tolonen
Sinisa Milivojevic
Tonu Samuel (past developer)
Sasha Pachev
Matt Wagner
Miguel Solorzano
Timothy Smith (past developer)
Sergei Golubchik
Jeremy Cole
Indrek Siitan
Jorge del Conde
Venu Anuganti
Arjen Lentz
Alexander (Bar) Barkov, Alexey (Holyfoot) Botchkov, and Ramil Kalimullin
Oleksandr (Sanja) Byelkin
Aleksey (Walrus) Kishkin and Alexey (Ranger) Stroganov
Zak Greant
Carsten Pedersen
Lenz Grimmer
Peter Zaitsev
Alexander (Salle) Keremidarski
Per-Erik Martin
Jim Winstead
Mark Matthews

Contributors to MySQL

While MySQL AB owns all copyrights in the MySQL server and the MySQL manual, we wish to recognise those who have made contributions of one kind or another to the MySQL distribution. Contributors are listed here, in somewhat random order:

Paul DuBois
Ongoing help with making this manual correct and understandable. That includes rewriting Monty's and David's attempts at English into English as other people know it.
Gianmassimo Vigazzola qwerg@mbox.vol.it or qwerg@tin.it
The initial port to Win32/NT.
Kim Aldale
Helped to rewrite Monty's and David's early attempts at English into English.
Per Eric Olsson
For more or less constructive criticism and real testing of the dynamic record format.
Irena Pancirov irena@mail.yacc.it
Win32 port with Borland compiler. mysqlshutdown.exe and mysqlwatch.exe
David J. Hughes
For the effort to make a shareware SQL database. At TcX, the predecessor of MySQL AB, we started with mSQL, but found that it couldn't satisfy our purposes so instead we wrote a SQL interface to our application builder Unireg. mysqladmin and mysql client are programs that were largely influenced by their mSQL counterparts. We have put a lot of effort into making the MySQL syntax a superset of mSQL. Many of the API's ideas are borrowed from mSQL to make it easy to port free mSQL programs to the MySQL API. The MySQL software doesn't contain any code from mSQL. Two files in the distribution (`client/insert_test.c' and `client/select_test.c') are based on the corresponding (non-copyrighted) files in the mSQL distribution, but are modified as examples showing the changes necessary to convert code from mSQL to MySQL Server. (mSQL is copyrighted David J. Hughes.)
Fred Fish
For his excellent C debugging and trace library. Monty has made a number of smaller improvements to the library (speed and additional options).
Richard A. O'Keefe
For his public domain string library.
Henry Spencer
For his regex library, used in WHERE column REGEXP regexp.
Free Software Foundation
From whom we got an excellent compiler (gcc), the libc library (from which we have borrowed `strto.c' to get some code working in Linux), and the readline library (for the mysql client).
Free Software Foundation & The XEmacs development team
For a really great editor/environment used by almost everybody at MySQL AB/TcX/detron.
Patrick Lynch
For helping us acquire http://www.mysql.com/.
Fred Lindberg
For setting up qmail to handle the MySQL mailing list and for the incredible help we got in managing the MySQL mailing lists.
Igor Romanenko igor@frog.kiev.ua
mysqldump (previously msqldump, but ported and enhanced by Monty).
Yuri Dario
For keeping up and extending the MySQL OS/2 port.
Tim Bunce, Alligator Descartes
For the DBD (Perl) interface.
Tim Bunce
Author of mysqlhotcopy.
Andreas Koenig a.koenig@mind.de
For the Perl interface for MySQL Server.
Eugene Chan eugene@acenet.com.sg
For porting PHP for MySQL Server.
Michael J. Miller Jr. mke@terrapin.turbolift.com
For the first MySQL manual. And a lot of spelling/language fixes for the FAQ (that turned into the MySQL manual a long time ago).
Yan Cailin
First translator of the MySQL Reference Manual into simplified chinese in early 2000 on which the Big5 and HK coded (http://mysql.hitstar.com/) versions were based. Personal home page at linuxdb.yeah.net.
Giovanni Maruzzelli maruzz@matrice.it
For porting iODBC (Unix ODBC).
Chris Provenzano
Portable user level pthreads. From the copyright: This product includes software developed by Chris Provenzano, the University of California, Berkeley, and contributors. We are currently using version 1_60_beta6 patched by Monty (see `mit-pthreads/Changes-mysql').
Xavier Leroy Xavier.Leroy@inria.fr
The author of LinuxThreads (used by the MySQL Server on Linux).
Zarko Mocnik zarko.mocnik@dem.si
Sorting for Slovenian language and the `cset.tar.gz' module that makes it easier to add other character sets.
"TAMITO" tommy@valley.ne.jp
The _MB character set macros and the ujis and sjis character sets.
Joshua Chamas joshua@chamas.com
Base for concurrent insert, extended date syntax, debugging on NT, and answering on the MySQL mailing list.
Yves Carlier Yves.Carlier@rug.ac.be
mysqlaccess, a program to show the access rights for a user.
Rhys Jones rhys@wales.com (And GWE Technologies Limited)
For JDBC, a module to extract data from a MySQL Database with a Java client.
Dr Xiaokun Kelvin ZHU X.Zhu@brad.ac.uk
Further development of the JDBC driver and other MySQL-related Java tools.
James Cooper pixel@organic.com
For setting up a searchable mailing list archive at his site.
Rick Mehalick Rick_Mehalick@i-o.com
For xmysql, a graphical X client for MySQL Server.
Doug Sisk sisk@wix.com
For providing RPM packages of MySQL for RedHat Linux.
Diemand Alexander V. axeld@vial.ethz.ch
For providing RPM packages of MySQL for RedHat Linux-Alpha.
Antoni Pamies Olive toni@readysoft.es
For providing RPM versions of a lot of MySQL clients for Intel and SPARC.
Jay Bloodworth jay@pathways.sde.state.sc.us
For providing RPM versions for MySQL Version 3.21.
Jochen Wiedmann wiedmann@neckar-alb.de
For maintaining the Perl DBD::mysql module.
Therrien Gilbert gilbert@ican.net, Jean-Marc Pouyot jmp@scalaire.fr
French error messages.
Petr Snajdr, snajdr@pvt.net
Czech error messages.
Jaroslaw Lewandowski jotel@itnet.com.pl
Polish error messages.
Miguel Angel Fernandez Roiz
Spanish error messages.
Roy-Magne Mo rmo@www.hivolda.no
Norwegian error messages and testing of Version 3.21.#.
Timur I. Bakeyev root@timur.tatarstan.ru
Russian error messages.
brenno@dewinter.com & Filippo Grassilli phil@hyppo.com
Italian error messages.
Dirk Munzinger dirk@trinity.saar.de
German error messages.
Billik Stefan billik@sun.uniag.sk
Slovak error messages.
Stefan Saroiu tzoompy@cs.washington.edu
Romanian error messages.
Peter Feher
Hungarian error messages.
Roberto M. Serqueira
Portugise error messages.
Carsten H. Pedersen
Danish error messages.
Arjen G. Lentz
Dutch error messages, completing earlier partial translation (also work on consistency and spelling).
David Sacerdote davids@secnet.com
Ideas for secure checking of DNS hostnames.
Wei-Jou Chen jou@nematic.ieo.nctu.edu.tw
Some support for Chinese(BIG5) characters.
Wei He hewei@mail.ied.ac.cn
A lot of functionality for the Chinese(GBK) character set.
Zeev Suraski bourbon@netvision.net.il
FROM_UNIXTIME() time formatting, ENCRYPT() functions, and bison advisor. Active mailing list member.
Luuk de Boer luuk@wxs.nl
Ported (and extended) the benchmark suite to DBI/DBD. Have been of great help with crash-me and running benchmarks. Some new date functions. The mysql_setpermissions script.
Jay Flaherty fty@mediapulse.com
Big parts of the Perl DBI/DBD section in the manual.
Paul Southworth pauls@etext.org, Ray Loyzaga yar@cs.su.oz.au
Proof-reading of the Reference Manual.
Alexis Mikhailov root@medinf.chuvashia.su
User-definable functions (UDFs); CREATE FUNCTION and DROP FUNCTION.
Andreas F. Bobak bobak@relog.ch
The AGGREGATE extension to UDF functions.
Ross Wakelin R.Wakelin@march.co.uk
Help to set up InstallShield for MySQL-Win32.
Jethro Wright III jetman@li.net
The `libmysql.dll' library.
James Pereria jpereira@iafrica.com
Mysqlmanager, a Win32 GUI tool for administrating MySQL Server.
Curt Sampson cjs@portal.ca
Porting of MIT-pthreads to NetBSD/Alpha and NetBSD 1.3/i386.
Antony T. Curtis antony.curtis@olcs.net
Porting of the MySQL Database software to OS/2.
Martin Ramsch m.ramsch@computer.org
Examples in the MySQL Tutorial.
Steve Harvey
For making mysqlaccess more secure.
Konark IA-64 Centre of Persistent Systems Private Limited
http://www.pspl.co.in/konark/. Help with the Win64 port of the MySQL server.
Albert Chin-A-Young.
Configure updates for Tru64, large file support and better TCP wrappers support.
John Birrell
Emulation of pthread_mutex() for OS/2.
Benjamin Pflugmann
Extended MERGE tables to handle INSERTS. Active member on the MySQL mailing lists.
Guilhem Bichot
Fixed handling of exponents for DECIMAL. Author of mysql_tableinfo.
Jocelyn Fournier
Excellent spotting and reporting innumerable bugs (especially in the MySQL 4.1 subquery code).
Georg Richter
MySQL 4.1 testing and bug hunting. New PHP 5.0 mysqli extension (API) for use with MySQL 4.1 and up.
Marc Liyanage
Maintaining the Mac OS X packages and providing invaluable feedback on how to create Mac OS X PKGs.

Other contributors, bugfinders, and testers: James H. Thompson, Maurizio Menghini, Wojciech Tryc, Luca Berra, Zarko Mocnik, Wim Bonis, Elmar Haneke, jehamby@lightside, psmith@BayNetworks.com, duane@connect.com.au, Ted Deppner ted@psyber.com, Mike Simons, Jaakko Hyvatti.

And lots of bug report/patches from the folks on the mailing list.

A big tribute goes to those that help us answer questions on the mysql@lists.mysql.com mailing list:

Daniel Koch dkoch@amcity.com
Irix setup.
Luuk de Boer luuk@wxs.nl
Benchmark questions.
Tim Sailer tps@users.buoy.com
DBD-mysql questions.
Boyd Lynn Gerber gerberb@zenez.com
SCO-related questions.
Richard Mehalick RM186061@shellus.com
xmysql-related questions and basic installation questions.
Zeev Suraski bourbon@netvision.net.il
Apache module configuration questions (log & auth), PHP-related questions, SQL syntax-related questions and other general questions.
Francesc Guasch frankie@citel.upc.es
General questions.
Jonathan J Smith jsmith@wtp.net
Questions pertaining to OS-specifics with Linux, SQL syntax, and other things that might need some work.
David Sklar sklar@student.net
Using MySQL from PHP and Perl.
Alistair MacDonald A.MacDonald@uel.ac.uk
Not yet specified, but is flexible and can handle Linux and maybe HP-UX. Will try to get user to use mysqlbug.
John Lyon jlyon@imag.net
Questions about installing MySQL on Linux systems, using either `.rpm' files or compiling from source.
Lorvid Ltd. lorvid@WOLFENET.com
Simple billing/license/support/copyright issues.
Patrick Sherrill patrick@coconet.com
ODBC and VisualC++ interface questions.
Randy Harmon rjharmon@uptimecomputers.com
DBD, Linux, some SQL syntax questions.

Supporters to MySQL

While MySQL AB owns all copyrights in the MySQL server and the MySQL manual, we wish to recognise the following companies, which helped us finance the development of the MySQL server, such as by paying us for developing a new feature or giving us hardware for development of the MySQL server.

VA Linux / Andover.net
Funded replication.
NuSphere
Editing of the MySQL manual.
Stork Design studio
The MySQL web site in use between 1998-2000.
Intel
Contributed to development on Windows and Linux platforms.
Compaq
Contributed to Development on Linux/Alpha.
SWSoft
Development on the embedded mysqld version.
FutureQuest
--skip-show-database

MySQL Change History

This appendix lists the changes from version to version in the MySQL source code.

We are now working actively on MySQL 4.1 & 5.0 and will only provide critical bug fixes for MySQL 4.0 and MySQL 3.23. We update this section as we add new features, so that everybody can follow the development.

Our TODO section contains what further plans we have for 4.1 & 5.0. See section MySQL and The Future (The TODO).

新しい変更を MySQL に施すと同時に、マニュアルを変更することに注意してください。 もしマニュアルにかかれているのに MySQL download page (http://www.mysql.com/downloads/) に 新しいバージョンの MySQL が見つからない場合、そのバージョンはまだリリースされていません!

Changes in release 5.0.0 (Development)

Version 5.0 is for the moment only available on for MySQL developers. It will be publicly available as soon we are confident that the base for stored procedures is sound and working.

The following changelog shows what is already done in the 5.0 tree:

Changes in release 4.1.x (Alpha)

Version 4.1 of the MySQL server includes many enhancements and new features: This version is available from our public bk tree and will be available as a binary shortly

For a full list of changes, please refer to the changelog sections for each individual 4.1.x release.

Changes in release 4.1.0

Changes in release 4.0.x (Gamma)

Version 4.0 of the MySQL server includes many enhancements and new features:

For a full list of changes, please refer to the changelog sections for each individual 4.0.x release.

Changes in release 4.0.12 (not released yet)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.11 (20 Feb 2003)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.10 (29 Jan 2003)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.9 (09 Jan 2003)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.8 (2003-01-07)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.7 (2002-12-20)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.6 (2002-12-14: Gamma)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.5 (2002-11-13)

Functionality added or changed:

Bugs fixed:

Changes in release 4.0.4 (2002-09-29)

Changes in release 4.0.3 (2002-08-26: Beta)

Changes in release 4.0.2 (2002-07-01)

Changes in release 4.0.1 (2001-12-23)

Changes in release 4.0.0 (2001-10-16: Alpha)

Changes in release 3.23.x (Stable)

The 3.23 release has several major features that are not present in previous versions. We have added three new table types:

MyISAM
A new ISAM library which is tuned for SQL and supports large files.
InnoDB
A transaction-safe storage engine that supports row level locking, and many Oracle-like features.
BerkeleyDB or BDB
Uses the Berkeley DB library from Sleepycat Software to implement transaction-safe tables.

Note that only MyISAM is available in the standard binary distribution.

The 3.23 release also includes support for database replication between a master and many slaves, full-text indexing, and much more.

All new features are being developed in the 4.x version. Only bug fixes and minor enhancements to existing features will be added to 3.23.

The replication code and BerkeleyDB code is still not as tested and as the rest of the code, so we will probably need to do a couple of future releases of 3.23 with small fixes for this part of the code. As long as you don't use these features, you should be quite safe with MySQL 3.23!

Note that the above doesn't mean that replication or Berkeley DB don't work. We have done a lot of testing of all code, including replication and BDB without finding any problems. It only means that not as many users use this code as the rest of the code and because of this we are not yet 100% confident in this code.

Changes in release 3.23.57 (not released yet)

Changes in release 3.23.56 (13 Mar 2003)

Changes in release 3.23.55 (23 Jan 2003)

Changes in release 3.23.54 (2002-12-05)

Changes in release 3.23.53 (2002-10-09)

Changes in release 3.23.52 (2002-08-14)

Changes in release 3.23.51 (2002-05-31)

Changes in release 3.23.50 (2002-04-21)

Changes in release 3.23.49 (2002-02-16)

Changes in release 3.23.48 (2002-02-07)

Changes in release 3.23.47 (2001-12-27)

Changes in release 3.23.46 (2001-11-29)

Changes in release 3.23.45 (2001-11-22)

Changes in release 3.23.44 (2001-10-31)

The following changes are for InnoDB tables:

Changes in release 3.23.43 (2001-10-04)

Changes in release 3.23.42 (2001-09-08)

Changes in release 3.23.41 (2001-08-11)

Changes in release 3.23.40 (2001-07-22)

Changes in release 3.23.39 (2001-06-12)

Changes in release 3.23.38 (2001-05-09)

Changes in release 3.23.37 (2001-04-17)

Changes in release 3.23.36 (2001-03-27)

Changes in release 3.23.35 (2001-03-15)

Changes in release 3.23.34a (2001-03-12)

Changes in release 3.23.34 (2001-03-10)

Changes in release 3.23.33 (2001-02-09)

Changes in release 3.23.32 (2001-01-22; Stable)

Changes in release 3.23.31 (2001-01-17)

Changes in release 3.23.30 (2001-01-04)

Changes in release 3.23.29 (2000-12-16)

Changes in release 3.23.28 (2000-11-22; Gamma)

Changes in release 3.23.27 (2000-10-24)

Changes in release 3.23.26 (2000-10-18)

Changes in release 3.23.25 (2000-09-29)

Changes in release 3.23.24 (2000-09-08)

Changes in release 3.23.23 (2000-09-01)

Changes in release 3.23.22 (2000-07-31)

Changes in release 3.23.21 (2000-07-05)

Changes in release 3.23.20

Changes in release 3.23.19

Changes in release 3.23.18 (2000-06-15)

Changes in release 3.23.17

Changes in release 3.23.16

Changes in release 3.23.15 (2000-05-10; Beta)

Changes in release 3.23.14 (2000-04-10)

Changes in release 3.23.13

Changes in release 3.23.12 (07 Mar 2000)

Changes in release 3.23.11

Changes in release 3.23.10

Changes in release 3.23.9

Changes in release 3.23.8 (02 Jan 2000)

Changes in release 3.23.7 (10 Dec 1999)

Changes in release 3.23.6

Changes in release 3.23.5 (20 Oct 1999)

Changes in release 3.23.4 (28 Sep 1999)

Changes in release 3.23.3

Changes in release 3.23.2 (1999-08-09)

Changes in release 3.23.1

Changes in release 3.23.0 (1999-06-05; Alpha)

Changes in release 3.22.x (Old; discontinued)

3.22 は 3.21 より早く、より安全なコードをもち、たくさんの新しい機能が盛り込まれています。 これらの変更を 3.21 に行わないのは、3.21 の安定度を保つためにはとても多くの変更が必要とされるからです。 これらの変更はメジャーバージョンの変更ではないので、簡単に障害もなく 3.22 にアップグレードができます。 See section バージョン 3.21 から バージョン 3.22 へのアップグレード.

3.22 は新しい DBD-mysql (1.20xx) ドライバーのみを新しい接続プロトコルに対して使用します!

Changes in release 3.22.35

Changes in release 3.22.34

Changes in release 3.22.33

Changes in release 3.22.32 (2000-02-14)

Changes in release 3.22.31

Changes in release 3.22.30 (2000-01-12 stable)

Changes in release 3.22.29 (02 Jan 2000)

Changes in release 3.22.28 (20 Oct 1999)

Changes in release 3.22.27

Changes in release 3.22.26 (16 Sep 1999)

Changes in release 3.22.25

Changes in release 3.22.24 (1999-07-05)

Changes in release 3.22.23 (08 Jun 1999)

Changes in release 3.22.22 (30 Apr 1999)

Changes in release 3.22.21

Changes in release 3.22.20 (1999-03-18)

Changes in release 3.22.19 (1999-03-02)

Changes in release 3.22.18

Changes in release 3.22.17

Changes in release 3.22.16 (1999-02-07)

Changes in release 3.22.15

Changes in release 3.22.14

Changes in release 3.22.13 (1998-12-17)

Changes in release 3.22.12 (1998-12-10)

Changes in release 3.22.11 (1998-11-25)

Changes in release 3.22.10 (1998-11-05)

Changes in release 3.22.9

Changes in release 3.22.8

Changes in release 3.22.7 (1998-09: Beta)

Changes in release 3.22.6 (1998-07-11)

Changes in release 3.22.5

Changes in release 3.22.4

Changes in release 3.22.3

Changes in release 3.22.2

Changes in release 3.22.1 (1998-06-17)

Changes in release 3.22.0

Changes in release 3.21.x

Version 3.21 is quite old now, and should be avoided if possible. This information is kept here for historical purposes only.

Changes in release 3.21.33 (1998-07-11)

Changes in release 3.21.32

Changes in release 3.21.31 (1998-06-17)

Changes in release 3.21.30 (1998-05-11 stable)

Changes in release 3.21.29 (1998-04-10)

Changes in release 3.21.28 (1998-04-01)

Changes in release 3.21.27 (1998-03-28 gamma)

Changes in release 3.21.26

Changes in release 3.21.25

Changes in release 3.21.24

Changes in release 3.21.23

Changes in release 3.21.22

Changes in release 3.21.21a

Changes in release 3.21.21

Changes in release 3.21.20

Changes in release 3.21.19

Changes in release 3.21.18

Changes in release 3.21.17 (1997-12-20)

Changes in release 3.21.16 (1997-12-10 beta)

Changes in release 3.21.15 (1997-12-01)

Changes in release 3.21.14b

Changes in release 3.21.14a (1997-11-12)

Changes in release 3.21.13

Changes in release 3.21.12

Changes in release 3.21.11 (1997-10-16)

Changes in release 3.21.10

Changes in release 3.21.9 (1997-09-28)

Changes in release 3.21.8

Changes in release 3.21.7

Changes in release 3.21.6

Changes in release 3.21.5

Changes in release 3.21.4

Changes in release 3.21.3

Changes in release 3.21.2

Changes in release 3.21.0

Changes in release 3.20.x

Version 3.20 is quite old now, and should be avoided if possible. This information is kept here for historical purposes only.

Changes from 3.20.18 to 3.20.32b are not documented here because the 3.21 release branched here. And the relevant changes are also documented as changes to the 3.21 version.

Changes in release 3.20.18

Changes in release 3.20.17 (1997-04-13)

Changes in release 3.20.16

Changes in release 3.20.15

Changes in release 3.20.14

Changes in release 3.20.13

Changes in release 3.20.11

Changes in release 3.20.10

Changes in release 3.20.9 (1997-02-13)

Changes in release 3.20.8

Changes in release 3.20.7

Changes in release 3.20.6 (1997-01-31)

Changes in release 3.20.3

Changes in release 3.20.0

Changes in release 3.19.x

Version 3.19 is quite old now, and should be avoided if possible. This information is kept here for historical purposes only.

Changes in release 3.19.5

Changes in release 3.19.4

Changes in release 3.19.3

Changes in release 3.11

MySQL バージョン 3.11 は、MySQL がネット上で公開された初めてのバージョンです

他のシステムへの移植について

This appendix will help you port MySQL to other operationg systems. Do check the list of currently supported operating systems first. See section MySQL がサポートする OS. If you have created a new port of MySQL, please let us know so that we can list it here and on our web site (http://www.mysql.com/), recommending it to other users.

Note: If you create a new port of MySQL, you are free to copy and distribute it under the GPL license, but it does not make you a copyright holder of MySQL.

移植先のシステムには POSIX 仕様のスレッドライブラリが必要となります。 我々は Solaris 2.5 では Sun PThreads (2.4以前でサポートされていたネイティブthreadは良くなかった)を、 Linux では Xavier Leroy, Xavier.Leroy@inria.fr による LinuxThreads を使っています。

良いネイティブスレッドを持たない新種の Unix に移植する場合、 多分もっとも大変な作業は MIT-pthreads を導入する部分です。 `mit-pthreads/README'http://www.humanfactor.com/pthreads/をご覧下さい。

MySQL の配布ファイルには MIT の Provenzano's Pthreads パッチ済みバージョン (http://www.mit.edu:8001/people/proven/pthreads.htmlをご覧下さい。) が含まれています。 これは POSIX 仕様の Threads を持たない OS に使用可能と思われます。

もう1つのユーザレベル thread パッケージ、FSU Pthreads も使用可能と思われます (http://www.informatik.hu-berlin.de/~mueller/pthreads.htmlをご覧下さい。)。 これはSCOへの移植に使用可能です。

そういった問題に関するテストやサンプルのプログラムを作成する場合には `mysys' ディレクトリの `thr_lock.c'`thr_alarm.c' 等のプログラムをご覧下さい。

移植にはサーバー、クライアントともに C++ コンパイラを必要とします (ちなみに我々はgccを使っています。SPARCWorks(C++)は試しました。)。 Irix ccも使用できることが確かめられています。

クライアントしか必要無い場合は./configure --without-serverとコンパイルしてください。

サーバのみコンパイルする方法は今のところありません。必要性が生じるまでは今のままです。

`Makefile' か コンフィギャスクリプトに何らかの変更をする必要が生じたなら Automake と Autoconf を使わなくてはいけません。 ちなみに、我々は automake-1.2autoconf-2.12 を使っています。

変更の手順は全て基本的なファイルからやり直す必要があります。

/bin/rm */.deps/*.P
/bin/rm -f config.cache
aclocal
autoheader
aclocal
automake
autoconf
./configure --with-debug=full --prefix='your installation directory'

# 上記手順によって生成されるmakefileファイル群はGNU make 3.75以上
# (以下、gmakeと記述します。)を必要とします。
gmake clean all install init-db

新しい移植で問題が発生すればデバッグの必要が生じる場合もあります。

See section MySQL server のデバッグ.

Note: mysqldのデバッグを開始する前にmysys/thr_alarmmysys/thr_clockが動くかどうかチェックしてください。これにより貴方のインストールしたthread環境の動作可能性が多少でもあるのかどうかを確かめることができます。

MySQL server のデバッグ

もしあなたが MySQL のとても新しいある機能を使っている場合、 --skip-new (これは全く新しい、潜在的に危険な機能を無効にします) または --safe-mode (これは問題を生じさせるかもしれない多くの最適化を無効にします) オプションで mysqld を実行させることができます。 See section What To Do If MySQL Keeps Crashing.

もし mysqld が起動しないようなら、 `my.cnf' が無いかチェックしてください。 `my.cnf' の引数は mysqld --print-defaults でチェックできます。 また mysqld --no-defaults ... で起動することにより、 `my.cnf' を無視することが可能です。

もし mysqld が CPU や メモリー を食い始めたり、``ハング'' したりするなら、 mysqladmin processlist status を使用して誰かが多くの時間のかかる クエリを実行しているか確かめることが出来ます。 パフォーマンスの問題や新しいクライアントが接続できないときの問題と もしあなたが考えるなら、 いくつかのウインドウで mysqladmin -i10 processlist status を 実行するのはよい考えでしょう。

mysqladmin debug コマンドは使用中のロック、使用しているメモり、 クエリの使用の情報を、mysql ログファイルにいくつかダンプします これはいくつかの問題解決に役立ちます。 このコマンドは、 MySQL を デバッグ可能でコンパイルしていなくても、いくつかの役立つ情報も提供します。

いくつかのテーブルでだんだん遅くなる問題であるなら、 OPTIMIZE TABLEmyisamchk でテーブルを修復し、最適化を試みるべきです。 遅いクエリは、 EXPLAIN でもチェックできます。 See section データベース管理. You should also check the slow queries with EXPLAIN.

このマニュアルの OS 固有の問題 の節も読むべきです。 See section Operating System Specific Notes.

Compiling MySQL for Debugging

もしあるとても特殊な問題があれば、あなたは、いつも MySQL を デバッグするよう試みることができます。 これを行うには、 MySQL を --with-debug オプションか --with-debug=full オプション付きで configure しなくてはなりません。 MySQL がデバッギングを有効にしてコンパイルされているかを 知るには、 mysqld --help とします。 もし --debug フラグが リストされていればデバッグが有効です。 mysqladmin vermysqld のバージョンをリストできます。 この場合は mysql ... --debug と、バージョン番号に表示されるでしょう。

gcc か egcs の場合、推奨する configure のラインは:

CC=gcc CFLAGS="-O2" CXX=gcc CXXFLAGS="-O2 -felide-constructors \
   -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql \
   --with-debug --with-extra-charsets=complex

This will avoid problems with the libstdc++ library and with C++ exceptions (many compilers have problems with C++ exceptions in threaded code) and compile a MySQL version with support for all character sets.

If you suspect a memory overrun error, you can configure MySQL with --with-debug=full, which will install a memory allocation (SAFEMALLOC) checker. Running with SAFEMALLOC is however quite slow, so if you get performance problems you should start mysqld with the --skip-safemalloc option. This will disable the memory overrun checks for each call to malloc and free.

If mysqld stops crashing when you compile it with --with-debug, you have probably found a compiler bug or a timing bug within MySQL. In this case you can try to add -g to the CFLAGS and CXXFLAGS variables above and not use --with-debug. If mysqld now dies, you can at least attach to it with gdb or use gdb on the core file to find out what happened.

MySQL をデバッグで configure すると、自動で多くの安全な検査関数が enable になります。 これは mysqld の状態をモニターできます。 もしそれら関数がなにか ``予期せぬこと'' を発見したら、それらを stderr に書き出します。 これは safe_mysqld が受け取って error ログに 書き出します! このことはどういうことかというと、 MySQL に予期せぬことが 起きた場合、まず最初にすべきことは、 MySQL をデバッグ有効にして configure することです! (次に、もちろん、 mysql@lists.mysql.com に メールを送り、help を聞くことです。 全てのバグレポート、MySQL のバージョンに 関連する質問は、 mysqlbug スクリプトを使用してください!)

In the Windows MySQL distribution, mysqld.exe is by default compiled with support for trace files.

Creating Trace Files

If the mysqld server doesn't start or if you can cause the mysqld server to crash quickly, you can try to create a trace file to find the problem.

To do this you have to have a mysqld that is compiled for debugging. You can check this by executing mysqld -V. If the version number ends with -debug, it's compiled with support for trace files.

Start the mysqld server with a trace log in `/tmp/mysqld.trace' (or `C:\mysqld.trace' on Windows):

mysqld --debug

On Windows you should also use the --standalone flag to not start mysqld as a service:

In a DOS window do:

mysqld --debug --standalone

After this you can use the mysql.exe command-line tool in a second DOS window to reproduce the problem. You can take down the above mysqld server with mysqladmin shutdown.

Note that the trace file will get very big! If you want to have a smaller trace file, you can use something like:

mysqld --debug=d,info,error,query,general,where:O,/tmp/mysqld.trace

which only prints information with the most interesting tags in `/tmp/mysqld.trace'.

If you make a bug report about this, please only send the lines from the trace file to the appropriate mailing list where something seems to go wrong! If you can't locate the wrong place, you can ftp the trace file, together with a full bug report, to ftp://support.mysql.com/pub/mysql/secret/ so that a MySQL developer can take a look a this.

The trace file is made with the DBUG package by Fred Fish. See section The DBUG Package.

Debugging mysqld under gdb

ほとんどのシステムでは、もし mysqld がクラッシュするなら、 gdb から mysqld を起動させて多くの情報を得ることが可能です。

Linux 上でのいくつかの gdb バージョンでは、 mysqld スレッドのデバッグを可能にする場合、 run --one-thread を使用しなくてはなりません。 この場合、一度にただ一つのactiveなスレッドだけを持つことになります。 We recommend you to upgrade to gdb 5.1 ASAP as thread debugging works much better with this version!

When running mysqld under gdb, you should disable the stack trace with --skip-stack-trace to be able to catch segfaults within gdb.

It's very hard to debug MySQL under gdb if you do a lot of new connections the whole time as gdb doesn't free the memory for old threads. You can avoid this problem by starting mysqld with -O thread_cache_size= 'max_connections +1'. In most cases just using -O thread_cache_size=5' will help a lot!

If you want to get a core dump on Linux if mysqld dies with a SIGSEGV signal, you can start mysqld with the --core-file option. This core file can be used to make a backtrace that may help you find out why mysqld died:

shell> gdb mysqld core
gdb>   backtrace full
gdb>   exit

See section What To Do If MySQL Keeps Crashing.

もし Linux 上で gdb 4.17.x を使用しているなら、 `.gdb' ファイルを いかにしたがって、カレントのディレクトリーにインストールすべきです:

set print sevenbit off
handle SIGUSR1 nostop noprint
handle SIGUSR2 nostop noprint
handle SIGWAITING nostop noprint
handle SIGLWP nostop noprint
handle SIGPIPE nostop
handle SIGALRM nostop
handle SIGHUP nostop
handle SIGTERM nostop noprint

If you have problems debugging threads with gdb, you should download gdb 5.x and try this instead. The new gdb version has very improved thread handling!

以下は mysqld のデバッグ例です:

shell> gdb /usr/local/libexec/mysqld
gdb> run
...
backtrace full # mysqld がクラッシュした際、これを行います

上記の出力を、 mysqlbug で作成したメールに含み、 そして mysql@lists.mysql.com. に送ってください。

もし mysqld がハングするなら、 strace/usr/proc/bin/pstack のような システムツールを使用して mysqld がどこでハングしているか 調べることができます。

strace /tmp/log libexec/mysqld

もし Perl DBI を使用しているなら、 trace メソッド、あるいはDBI_TRACE 環境変数で デバッグ情報を有効にできます。 See section The DBI Interface.

Using a Stack Trace

On some operating systems, the error log will contain a stack trace if mysqld dies unexpectedly. You can use this to find out where (and maybe why) mysqld died. See section The Error Log. To get a stack trace, you must not compile mysqld with the -fomit-frame-pointer option to gcc. See section Compiling MySQL for Debugging.

If the error file contains something like the following:

mysqld got signal 11;
The manual section 'Debugging a MySQL server' tells you how to use a
stack trace and/or the core file to produce a readable backtrace that may
help in finding out why mysqld died
Attemping backtrace. You can use the following information to find out
where mysqld died.  If you see no messages after this, something went
terribly wrong
stack range sanity check, ok, backtrace follows
0x40077552
0x81281a0
0x8128f47
0x8127be0
0x8127995
0x8104947
0x80ff28f
0x810131b
0x80ee4bc
0x80c3c91
0x80c6b43
0x80c1fd9
0x80c1686

you can find where mysqld died by doing the following:

  1. Copy the above numbers to a file, for example `mysqld.stack'.
  2. Make a symbol file for the mysqld server:
    nm -n libexec/mysqld > /tmp/mysqld.sym
    
    Note that many MySQL binary distributions comes with the above file, named mysqld.sym.gz. In this case you must unpack this by doing:
    gunzip < bin/mysqld.sym.gz > /tmp/mysqld.sym
    
  3. Execute resolve_stack_dump -s /tmp/mysqld.sym -n mysqld.stack. This will print out where mysqld died. If this doesn't help you find out why mysqld died, you should make a bug report and include the output from the above commend with the bug report. Note however that in most cases it will not help us to just have a stack trace to find the reason for the problem. To be able to locate the bug or provide a workaround, we would in most cases need to know the query that killed mysqld and preferable a test case so that we can repeat the problem! See section バグや問題を報告する方法.

Using Log Files to Find Cause of Errors in mysqld

--logを使用してmysqldを起動する際は、事前にmyisamchk を使用して全てのテーブルをチェックするようにしてください。 See section データベース管理.

もし mysqld が死んだりハングしたりするなら、 mysqld--log で起動すべきです。 再び mysqld が死んだら、 あなたはログファイル中の、 mysqld を kill するクエリをチェックします。

If you are using --log without a file name, the log is stored in the database directory as 'hostname'.log In most cases it's the last query in the log file that killed mysqld, but if possible you should verify this by restarting mysqld and executing the found query from the mysql command-line tools. If this works, you should also test all complicated queries that didn't complete.

mysqld が適切にインデックスを使用するのに時間がとてもかかる全ての SELECT 文を EXPLAIN で実行することを試みます。 See section EXPLAIN 構文 (SELECTについての情報を得る).

You can find the queries that take a long time to execute by starting mysqld with --log-slow-queries. See section The Slow Query Log (3.23.28以上).

もしエラーログファイル(通常 `hostname.err' という名前)中に mysqld restarted という文があるなら、 mysqld を失敗させるクエリを見つけます。 もしこれが起きるなら、myisamchk (see section データベース管理) で 全てのテーブルをチェックし、MySQL ログファイルにあるそのクエリをテストすべきです。 もしそのようなクエリをみつけたなら、まず最初に最新の MySQL にアップグレード してみてください。 もしそれでもだめで、かつ mysql メーリングリストの アーカイブにもなにも見つけることが出来なかったなら、 mysql@lists.mysql.com に バグレポートを出すべきです。 メーリングリストのアーカイブへのリンクは http://www.mysql.com/.

If you have started mysqld with myisam-recover, MySQL will automatically check and try to repair MyISAM tables if they are marked as 'not closed properly' or 'crashed'. If this happens, MySQL will write an entry in the hostname.err file 'Warning: Checking table ...' which is followed by Warning: Repairing table if the table needs to be repaired. If you get a lot of these errors, without mysqld having died unexpectedly just before, then something is wrong and needs to be investigated further. See section mysqld コマンド行オプション.

It's of course not a good sign if mysqld did died unexpectedly, but in this case one shouldn't investigate the Checking table... messages but instead try to find out why mysqld died.

Making a Test Case When You Experience Table Corruption

もし不正なテーブルをえたり、 mysqld が常にいくつかの update コマンドで 失敗するなら、以下のようにしてこのバグの再現をテストします:

You can also use the script mysql_find_rows to just execute some of the update statements if you want to narrow down the problem.

Debugging a MySQL client

To be able to debug a MySQL client with the integrated debug package, you should configure MySQL with --with-debug or --with-debug=full. See section 典型的な configure オプション.

Before running a client, you should set the MYSQL_DEBUG environment variable:

shell> MYSQL_DEBUG=d:t:O,/tmp/client.trace
shell> export MYSQL_DEBUG

This causes clients to generate a trace file in `/tmp/client.trace'.

If you have problems with your own client code, you should attempt to connect to the server and run your query using a client that is known to work. Do this by running mysql in debugging mode (assuming you have compiled MySQL with debugging on):

shell> mysql --debug=d:t:O,/tmp/client.trace

This will provide useful information in case you mail a bug report. See section バグや問題を報告する方法.

If your client crashes at some 'legal' looking code, you should check that your `mysql.h' include file matches your mysql library file. A very common mistake is to use an old `mysql.h' file from an old MySQL installation with new MySQL library.

The DBUG Package

The MySQL server and most MySQL clients are compiled with the DBUG package originally made by Fred Fish. When one has configured MySQL for debugging, this package makes it possible to get a trace file of what the program is debugging. See section Creating Trace Files.

One uses the debug package by invoking the program with the --debug="..." or the -#... option.

Most MySQL programs has a default debug string that will be used if you don't specify an option to --debug. The default trace file is usually /tmp/programname.trace on Unix and \programname.trace on Windows.

The debug control string is a sequence of colon separated fields as follows:

<field_1>:<field_2>:...:<field_N>

Each field consists of a mandatory flag character followed by an optional "," and comma-separated list of modifiers:

flag[,modifier,modifier,...,modifier]

The currently recognised flag characters are:

Flag Description
d Enable output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros.
D Delay after each debugger output line. The argument is the number of tenths of seconds to delay, subject to machine capabilities. That is, -#D,20 is delay two seconds.
f Limit debugging and/or tracing, and profiling to the list of named functions. Note that a null list will disable all functions. The appropriate "d" or "t" flags must still be given, this flag only limits their actions if they are enabled.
F Identify the source file name for each line of debug or trace output.
i Identify the process with the pid or thread id for each line of debug or trace output.
g Enable profiling. Create a file called 'dbugmon.out' containing information that can be used to profile the program. May be followed by a list of keywords that select profiling only for the functions in that list. A null list implies that all functions are considered.
L Identify the source file line number for each line of debug or trace output.
n Print the current function nesting depth for each line of debug or trace output.
N Number each line of dbug output.
o Redirect the debugger output stream to the specified file. The default output is stderr.
O As O but the file is really flushed between each write. When needed the file is closed and reopened between each write.
p Limit debugger actions to specified processes. A process must be identified with the DBUG_PROCESS macro and match one in the list for debugger actions to occur.
P Print the current process name for each line of debug or trace output.
r When pushing a new state, do not inherit the previous state's function nesting level. Useful when the output is to start at the left margin.
S Do function _sanity(_file_,_line_) at each debugged function until _sanity() returns something that differs from 0. (Mostly used with safemalloc to find memory leaks)
t Enable function call/exit trace lines. May be followed by a list (containing only one modifier) giving a numeric maximum trace level, beyond which no output will occur for either debugging or tracing macros. The default is a compile time option.

Some examples of debug control strings which might appear on a shell command-line (the "-#" is typically used to introduce a control string to an application program) are:

-#d:t
-#d:f,main,subr1:F:L:t,20
-#d,input,output,files:n
-#d:t:i:O,\\mysqld.trace

In MySQL, common tags to print (with the d option) are: enter,exit,error,warning,info and loop.

Locking methods

Currently MySQL only supports table locking for ISAM/MyISAM and HEAP tables, page-level locking for BDB tables and row-level locking for InnoDB tables. See section MySQL はどのようにテーブルをロックするか. With MyISAM tables one can freely mix INSERT and SELECT without locks, if the INSERTs are non-conflicting (i.e. whenever they append to the end of the table file rather than filling freespace from deleted rows/data).

Starting in version 3.23.33, you can analyse the table lock contention on your system by checking Table_locks_waited and Table_locks_immediate environment variables.

To decide if you want to use a table type with row-level locking, you will want to look at what the application does and what the select/update pattern of the data is.

Pros for row locking:

Cons:

Table locks are superior to page level / row level locks in the following cases:

Other options than row / page level locking:

Versioning (like we use in MySQL for concurrent inserts) where you can have one writer at the same time as many readers. This means that the database/table supports different views for the data depending on when one started to access it. Other names for this are time travel, copy on write or copy on demand.

Copy on demand is in many case much better than page or row level locking; the worst case does, however, use much more memory than when using normal locks.

Instead of using row level locks one can use application level locks (like get_lock/release_lock in MySQL). This works of course only in well-behaved applications.

In many cases one can do an educated guess which locking type is best for the application, but generally it's very hard to say that a given lock type is better than another; everything depends on the application and different part of the application may require different lock types.

Here are some tips about locking in MySQL:

Most web applications do lots of selects, very few deletes, updates mainly on keys, and inserts in some specific tables. The base MySQL setup is very well tuned for this.

Concurrent users are not a problem if one doesn't mix updates with selects that need to examine many rows in the same table.

If one mixes inserts and deletes on the same table then INSERT DELAYED may be of great help.

One can also use LOCK TABLES to speed up things (many updates within a single lock is much faster than updates without locks). Splitting thing to different tables will also help.

If you get speed problems with the table locks in MySQL, you may be able to solve these by converting some of your tables to InnoDB or BDB tables. See section InnoDB テーブル (3.23.6以上). See section BDB or BerkeleyDB Tables.

The optimisation section in the manual covers a lot of different aspects of how to tune applications. See section 最適化に関するその他の助言.

Comments about RTS threads

I have tried to use the RTS thread packages with MySQL but stumbled on the following problems:

They use an old version of a lot of POSIX calls and it is very tedious to make wrappers for all functions. I am inclined to think that it would be easier to change the thread libraries to the newest POSIX specification.

Some wrappers are already written. See `mysys/my_pthread.c' for more info.

At least the following should be changed:

pthread_get_specific should use one argument. sigwait should take two arguments. A lot of functions (at least pthread_cond_wait, pthread_cond_timedwait) should return the error code on error. Now they return -1 and set errno.

Another problem is that user-level threads use the ALRM signal and this aborts a lot of functions (read, write, open...). MySQL should do a retry on interrupt on all of these but it is not that easy to verify it.

The biggest unsolved problem is the following:

To get thread-level alarms I changed `mysys/thr_alarm.c' to wait between alarms with pthread_cond_timedwait(), but this aborts with error EINTR. I tried to debug the thread library as to why this happens, but couldn't find any easy solution.

If someone wants to try MySQL with RTS threads I suggest the following:

スレッドパッケージ間の違いは何?

MySQL は使用されるスレッドパッケージに非常に依存しています。 そのため、MySQL に良いプラットフォームを選択する時には、 スレッドパッケージが非常に重要です。

少なくとも3つのタイプのスレッドパッケージがあります:

いくつかのシステムでは、カーネルスレッドは、システムライブラリ内で、 ユーザレベルスレッドの統合によって管理されます。 この場合、スレッド切替えはスレッドライブラリによってだけ行なわれ、 カーネルは実際には 'thread aware' ではありません。

Environment Variables

MySQLで直接又は間接的に使用されている全ての環境変数リストを示します。これらのほとんどはこのマニュアルのどこかで使用されています。

コマンドラインオプションで指定される環境変数はコンフィギュレーションファイルで指定されるものよりも優先されます。また、コンフィギュレーションファイルで指定される環境変数はシェルで設定された環境変数よりも優先されます。

MySQLの振る舞いを指定する場合、環境変数はシェルで設定するよりもにコンフィギュレーションファイルで設定される方が望ましいことが多いです。See section `my.cnf' オプションファイル.

Variable Description
CCX Set this to your C++ compiler when running configure.
CC Set this to your C compiler when running configure.
CFLAGS Flags for your C compiler when running configure.
CXXFLAGS Flags for your C++ compiler when running configure.
DBI_USER The default user name for Perl DBI.
DBI_TRACE Used when tracing Perl DBI.
HOME The default path for the mysql history file is `$HOME/.mysql_history'.
LD_RUN_PATH Used to specify where your `libmysqlclient.so' is.
MYSQL_DEBUG Debug-trace options when debugging.
MYSQL_HISTFILE The path to the mysql history file.
MYSQL_HOST Default host name used by the mysql command-line client.
MYSQL_PS1 Command prompt to use in the mysql command-line client. See section mysql, コマンドラインツール.
MYSQL_PWD The default password when connecting to mysqld. Note that use of this is insecure!
MYSQL_TCP_PORT The default TCP/IP port.
MYSQL_UNIX_PORT The default socket; used for connections to localhost.
PATH Used by the shell to finds the MySQL programs.
TMPDIR The directory where temporary tables/files are created.
TZ This should be set to your local time zone. See section Time Zone Problems.
UMASK_DIR The user-directory creation mask when creating directories. Note that this is ANDed with UMASK!
UMASK The user-file creation mask when creating files.
USER The default user on Windows to use when connecting to mysqld.

MySQL の正規表現

A regular expression (regex) is a powerful way of specifying a complex search.

MySQL は正規表現の regular Henry Spencers 実装を使用します。 そしてこれは POSIX 1003.2 に一致することが 目的です。MySQL は拡張 バージョンを使用します。

これは詳細を省いた簡単なリファレンスです。 さらに正確な情報は Henry Spencers regex(7) マニュアルを見てください。 これはソース配布に含まれています。 See section Credits.

正規表現は文字列の組み合わせて記述されます。 もっとも簡単な場合は、非特殊文字の一文字です。例えば、 regexp hellohello と適合し、 他には適合しません。

簡単でない正規表現は、1つの文字列以上に適合できるような、いくつかの 特殊な構成を使用します。例えば、regexp hello|word は 文字列 hello と文字列 word に適合します。

そしてさらに複雑な例 regexp B[an]*s は、 文字列 Bananas, Baaaaas, Bs のどれか、 そして B で始まり an が 任意の数続き、s で終わるような他の文字列に適合します。

正規表現では、次の特殊文字/構成が使用できます:

^
文字列全体の始まり。
mysql> SELECT "fo\nfo" REGEXP "^fo$";           -> 0
mysql> SELECT "fofo" REGEXP "^fo";              -> 1
$
文字列全体の終り。
mysql> SELECT "fo\no" REGEXP "^fo\no$";         -> 1
mysql> SELECT "fo\no" REGEXP "^fo$";            -> 0
.
任意の文字 (改行含む)。
mysql> SELECT "fofo" REGEXP "^f.*";             -> 1
mysql> SELECT "fo\nfo" REGEXP "^f.*";           -> 1
a*
0個以上の文字 a の並び。
mysql> SELECT "Ban" REGEXP "^Ba*n";             -> 1
mysql> SELECT "Baaan" REGEXP "^Ba*n";           -> 1
mysql> SELECT "Bn" REGEXP "^Ba*n";              -> 1
a+
文字 a が 1個以上並ぶ。
mysql> SELECT "Ban" REGEXP "^Ba+n";             -> 1
mysql> SELECT "Bn" REGEXP "^Ba+n";              -> 0
a?
0 または 1個の文字 a
mysql> SELECT "Bn" REGEXP "^Ba?n";              -> 1
mysql> SELECT "Ban" REGEXP "^Ba?n";             -> 1
mysql> SELECT "Baan" REGEXP "^Ba?n";            -> 0
de|abc
deabc にマッチ。
mysql> SELECT "pi" REGEXP "pi|apa";             -> 1
mysql> SELECT "axe" REGEXP "pi|apa";            -> 0
mysql> SELECT "apa" REGEXP "pi|apa";            -> 1
mysql> SELECT "apa" REGEXP "^(pi|apa)$";        -> 1
mysql> SELECT "pi" REGEXP "^(pi|apa)$";         -> 1
mysql> SELECT "pix" REGEXP "^(pi|apa)$";        -> 0
(abc)*
文字列 abc の 0 回以上の並びにマッチ。
mysql> SELECT "pi" REGEXP "^(pi)*$";            -> 1
mysql> SELECT "pip" REGEXP "^(pi)*$";           -> 0
mysql> SELECT "pipi" REGEXP "^(pi)*$";          -> 1
{1}
{2,3}
多くの発生に適合する regexp の記述する一般的な方法。 The is a more general way of writing regexps that match many occurrences of the previous atom.
a*
Can be written as a{0,}.
a+
Can be written as a{1,}.
a?
Can be written as a{0,1}.
さらに正確には、1つの整数 i とコンマ無しを含む修飾が続くアトムは、 厳密にアトムに適合する i 回の並びに適合します。 整数 i とコンマを含む修飾が続くアトムは、 アトムに適合する i 回以上の並びに適合します。 整数 ij を含む装飾が続くアトムは、 アトムに適 合する i 回から j 回までの並びに適合します。 両方の引数は 0 から RE_DUP_MAX (default 255) の間でなければなりません。 そして引数が2つある場合、2番目は1番目よりも大きいか同じでなければなりません。
[a-dX]
[^a-dX]
a, b, c, d, X のどれかの文字 (^ を使用するとどれでもない文字) にマッチ。 ] 文字を含めるには、 [ のあとに続いてすぐに書く必要があります。 - 文字を含めるには最初か最後に書く必要があります。 [0-9] は任意 の10進数値に適合します。 [] ペア内部の定義された 意味を持たない全ての文字は、特殊な意味を持たず、それ自身にだけ適合します。
mysql> SELECT "aXbc" REGEXP "[a-dXYZ]";         -> 1
mysql> SELECT "aXbc" REGEXP "^[a-dXYZ]$";       -> 0
mysql> SELECT "aXbc" REGEXP "^[a-dXYZ]+$";      -> 1
mysql> SELECT "aXbc" REGEXP "^[^a-dXYZ]+$";     -> 0
mysql> SELECT "gheis" REGEXP "^[^a-dXYZ]+$";    -> 1
mysql> SELECT "gheisa" REGEXP "^[^a-dXYZ]+$";   -> 0
[[.characters.]]
照合要素(collating element)の文字の並び。 並びは括弧表現リストの一つの要素です。 複数文字の照合要素を含む括弧表現は一つ以上の文字に適合します。 例えば、照合並びが ch 照合要素を含む場合、 正規表現 [[.ch.]]*cchchcc の最初の5文字に適合します。
[=character_class=]
同等のクラス。その一つと等しい全ての照合要素の文字の並びを表します。それ自身も含みます。 例えば、o(+) が同等クラスのメンバである場合、 [[=o=]], [[=(+)=]], [[=(+)=]] は全て同義語です。 同等クラスは範囲の終了位置にはなりません。
[:character_class:]
括弧表現の内部で、[::] で括られた文字クラスの名前は、 そのクラスに属する全ての文字のリストを表します。標準文字クラス名は:
Name Name Name
alnum digit punct
alpha graph space
blank lower upper
cntrl print xdigit
これらは ctype(3) マニュアルページに記載されている文字クラスを表します。 ロケールが他のを提供することもあります。文字クラスは範囲の終了位置としては使えません。
mysql> SELECT "justalnums" REGEXP "[[:alnum:]]+";       -> 1
mysql> SELECT "!!" REGEXP "[[:alnum:]]+";               -> 0
[[:<:]]
[[:>:]]
それぞれ、単語の始めと終りの空文字列に適合します。単語は、単語文字が前後 にない単語文字の並びとして定義されます。単語文字は alnum 文字 (ctype(3) で定義されます) と下線(underscore ; _)です。
mysql> SELECT "a word a" REGEXP "[[:<:]]word[[:>:]]";      -> 1
mysql> SELECT "a xword a" REGEXP "[[:<:]]word[[:>:]]";     -> 0
mysql> SELECT "weeknights" REGEXP "^(wee|week)(knights|nights)$"; -> 1

GNU General Public License

Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  1. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) Each licensee is addressed as ``you''. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
  2. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
  3. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    1. You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
    2. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
    3. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
    These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
  4. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
    1. Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    2. Accompany it with a written offer, valid for at least three years, to give any third-party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    3. Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
    The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
  5. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
  6. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
  7. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
  8. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
  9. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
  10. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
  11. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

    NO WARRANTY

  12. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  13. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found.

one line to give the program's name and a brief idea of what it does.
Copyright (C) yyyy  name of author

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this when it starts in an interactive mode:

Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the program, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.

signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice

This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.

GNU Lesser General Public License

Version 2.1, February 1999

Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place -- Suite 330, Boston, MA 02111-1307, USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
as the successor of the GNU Library Public License, version 2, hence the
version number 2.1.]

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.

This license, the Lesser General Public License, applies to some specially designated software--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.

When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.

To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.

For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.

We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.

To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.

Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.

We call this license the Lesser General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a ``work based on the library'' and a ``work that uses the library''. The former contains code derived from the library, whereas the latter must be combined with the library in order to run.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  1. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called ``this License''). Each licensee is addressed as ``you''. A ``library'' means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The ``Library'', below, refers to any such software library or work which has been distributed under these terms. A ``work based on the Library'' means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) ``Source code'' for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
  2. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
  3. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    1. The modified work must itself be a software library.
    2. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
    3. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
    4. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
    These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
  4. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
  5. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
  6. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a ``work that uses the Library''. Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a ``work that uses the Library'' with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a ``work that uses the library''. The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a ``work that uses the Library'' uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether they are linked directly with the Library itself.
  7. As an exception to the Sections above, you may also combine or link a ``work that uses the Library'' with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
    1. Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable ``work that uses the Library'', as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
    2. Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at runtime a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
    3. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
    4. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
    5. Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
    For an executable, the required form of the ``work that uses the Library'' must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
  8. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
    1. Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
    2. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
  9. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
  10. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
  11. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
  12. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
  13. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
  14. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
  15. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

    NO WARRANTY

  16. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  17. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Libraries

If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).

To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found.

one line to give the library's name and an idea of what it does.
Copyright (C) year  name of author

This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.

This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
USA.

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the library, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in the library
`Frob' (a library for tweaking knobs) written by James Random Hacker.

signature of Ty Coon, 1 April 1990
Ty Coon, President of Vice

That's all there is to it!

SQL command, type and function index

  • ! (logical NOT)
  • != (not equal)
  • "
  • % (modulo)
  • % (wildcard character)
  • & (bitwise AND)
  • && (logical AND)
  • () (parentheses)
  • (Control-Z) \z
  • * (multiplication)
  • + (addition)
  • - (subtraction)
  • - (unary minus)
  • -p option
  • -password option
  • .my.cnf file, .my.cnf file, .my.cnf file, .my.cnf file, .my.cnf file, .my.cnf file, .my.cnf file
  • .mysql_history file
  • .pid (process ID) file
  • / (division)
  • /etc/passwd
  • `/etc/passwd'
  • < (less than)
  • <<
  • << (left shift)
  • <= (less than or equal)
  • <=> (Equal to)
  • <> (not equal)
  • = (equal)
  • > (greater than)
  • >= (greater than or equal)
  • >> (right shift)
  • \" (double quote)
  • \' (single quote)
  • \0 (ASCII 0)
  • \\ (escape)
  • \b (backspace)
  • \n (newline)
  • \r (carriage return)
  • \t (tab)
  • \z (Control-Z) ASCII(26)
  • ^ (bitwise XOR)
  • _ (wildcard character)
  • `
  • A

  • ABS()
  • ACOS()
  • ADDDATE()
  • addition (+)
  • AES_DECRYPT()
  • AES_ENCRYPT()
  • alias
  • ALTER COLUMN
  • ALTER TABLE, ALTER TABLE, ALTER TABLE
  • ANALYZE TABLE
  • AND, bitwise
  • AND, logical
  • arithmetic functions
  • AS, AS
  • ASCII()
  • ASIN()
  • ATAN()
  • ATAN2()
  • AVG()
  • B

  • backspace (\b)
  • BACKUP TABLE
  • BEGIN
  • BENCHMARK()
  • BETWEEN ... AND
  • BIGINT
  • BIN()
  • BINARY
  • BIT
  • bit functions
  • BIT_AND()
  • BIT_COUNT
  • BIT_COUNT()
  • BIT_LENGTH()
  • BIT_OR
  • BIT_OR()
  • BLOB, BLOB
  • BOOL
  • C

  • carriage return (\r)
  • CASE
  • CAST
  • casts
  • CC environment variable
  • CC environment variable, CC environment variable
  • CCX environment variable
  • CEILING()
  • CFLAGS environment variable, CFLAGS environment variable
  • CHAR, CHAR
  • CHAR VARYING
  • CHAR()
  • CHAR_LENGTH()
  • CHARACTER
  • CHARACTER VARYING
  • CHARACTER_LENGTH()
  • CHECK TABLE
  • ChopBlanks DBI method
  • COALESCE()
  • command-line options
  • Comment syntax
  • COMMIT, COMMIT
  • comparison operators
  • CONCAT()
  • CONCAT_WS()
  • configure option, --with-charset
  • configure option, --with-extra-charsets
  • connect() DBI method
  • CONNECTION_ID()
  • control flow functions
  • CONV()
  • CONVERT
  • COS()
  • COT()
  • COUNT()
  • COUNT(DISTINCT)
  • CREATE DATABASE
  • CREATE FUNCTION
  • CREATE INDEX
  • CREATE TABLE
  • CROSS JOIN
  • CURDATE()
  • CURRENT_DATE
  • CURRENT_TIME
  • CURRENT_TIMESTAMP
  • CURRENT_USER()
  • CURTIME()
  • CXX environment variable
  • CXX environment variable, CXX environment variable, CXX environment variable
  • CXXFLAGS environment variable, CXXFLAGS environment variable, CXXFLAGS environment variable, CXXFLAGS environment variable
  • D

  • data_sources() DBI method
  • DATABASE()
  • DATE, DATE, DATE
  • date and time functions
  • DATE_ADD()
  • DATE_FORMAT()
  • DATE_SUB()
  • DATETIME, DATETIME
  • DAYNAME()
  • DAYOFMONTH()
  • DAYOFWEEK()
  • DAYOFYEAR()
  • DBI->connect()
  • DBI->data_sources()
  • DBI->disconnect
  • DBI->do()
  • DBI->execute
  • DBI->fetchall_arrayref
  • DBI->fetchrow_array
  • DBI->fetchrow_arrayref
  • DBI->fetchrow_hashref
  • DBI->finish
  • DBI->prepare()
  • DBI->quote
  • DBI->quote()
  • DBI->rows
  • DBI->trace, DBI->trace
  • DBI->{ChopBlanks}
  • DBI->{insertid}
  • DBI->{is_blob}
  • DBI->{is_key}
  • DBI->{is_not_null}
  • DBI->{is_num}
  • DBI->{is_pri_key}
  • DBI->{length}
  • DBI->{max_length}
  • DBI->{NAME}
  • DBI->{NULLABLE}
  • DBI->{NUM_OF_FIELDS}
  • DBI->{table}
  • DBI->{type}
  • DBI_TRACE environment variable, DBI_TRACE environment variable, DBI_TRACE environment variable
  • DBI_USER environment variable
  • DEC
  • DECIMAL
  • DECODE()
  • DEGREES()
  • DELAYED
  • DELETE
  • DES_DECRYPT()
  • DES_ENCRYPT()
  • DESC
  • DESCRIBE, DESCRIBE
  • disconnect DBI method
  • DISTINCT, DISTINCT, DISTINCT
  • division (/)
  • DO
  • do() DBI method
  • DOUBLE
  • DOUBLE PRECISION
  • double quote (\")
  • DROP DATABASE
  • DROP FUNCTION
  • DROP INDEX, DROP INDEX
  • DROP PRIMARY KEY
  • DROP TABLE
  • DUMPFILE
  • E

  • ELT()
  • ENCODE()
  • ENCRYPT()
  • ENUM, ENUM
  • environment variable, CC
  • Environment variable, CC
  • environment variable, CC
  • Environment variable, CCX
  • environment variable, CFLAGS
  • Environment variable, CFLAGS
  • Environment variable, CXX
  • environment variable, CXX
  • environment variable, CXX
  • environment variable, CXXFLAGS, environment variable, CXXFLAGS, environment variable, CXXFLAGS
  • Environment variable, CXXFLAGS
  • Environment variable, DBI_TRACE, Environment variable, DBI_TRACE, Environment variable, DBI_TRACE
  • Environment variable, DBI_USER
  • environment variable, HOME
  • Environment variable, HOME
  • environment variable, LD_RUN_PATH
  • Environment variable, LD_RUN_PATH, Environment variable, LD_RUN_PATH, Environment variable, LD_RUN_PATH
  • Environment variable, MYSQL_DEBUG, Environment variable, MYSQL_DEBUG
  • environment variable, MYSQL_DEBUG
  • Environment variable, MYSQL_HISTFILE
  • environment variable, MYSQL_HISTFILE
  • Environment variable, MYSQL_HOST
  • environment variable, MYSQL_HOST
  • Environment variable, MYSQL_PS1
  • environment variable, MYSQL_PWD, environment variable, MYSQL_PWD
  • Environment variable, MYSQL_PWD
  • environment variable, MYSQL_TCP_PORT, environment variable, MYSQL_TCP_PORT
  • environment variable, MYSQL_TCP_PORT
  • Environment variable, MYSQL_TCP_PORT
  • environment variable, MYSQL_UNIX_PORT, environment variable, MYSQL_UNIX_PORT
  • Environment variable, MYSQL_UNIX_PORT, Environment variable, MYSQL_UNIX_PORT
  • environment variable, MYSQL_UNIX_PORT
  • Environment variable, PATH
  • environment variable, PATH
  • Environment variable, TMPDIR, Environment variable, TMPDIR
  • Environment variable, TZ, Environment variable, TZ
  • Environment variable, UMASK, Environment variable, UMASK
  • Environment variable, UMASK_DIR, Environment variable, UMASK_DIR
  • environment variable, USER
  • Environment variable, USER
  • Environment variables, CXX
  • equal (=)
  • escape (\\)
  • execute DBI method
  • EXP()
  • EXPLAIN
  • EXPORT_SET()
  • EXTRACT(), EXTRACT()
  • F

  • fetchall_arrayref DBI method
  • fetchrow_array DBI method
  • fetchrow_arrayref DBI method
  • fetchrow_hashref DBI method
  • FIELD()
  • FILE
  • FIND_IN_SET()
  • finish DBI method
  • FLOAT, FLOAT
  • FLOAT(M,D)
  • FLOAT(precision), FLOAT(precision)
  • FLOOR()
  • FLUSH
  • FORCE INDEX, FORCE INDEX
  • FORMAT()
  • FOUND_ROWS()
  • FROM_DAYS()
  • FROM_UNIXTIME(), FROM_UNIXTIME()
  • functions, arithmetic
  • functions, bit
  • functions, control flow
  • functions, date and time
  • functions, GROUP BY
  • functions, mathematical
  • functions, miscellaneous
  • functions, string
  • functions, string comparison
  • Functions, user-defined
  • G

  • GET_LOCK()
  • GRANT
  • GRANT statement, GRANT statement
  • GRANTS
  • greater than (>)
  • greater than or equal (>=)
  • GREATEST()
  • GROUP BY functions
  • H

  • HANDLER
  • HEX()
  • hexadecimal values
  • HOME environment variable
  • HOME environment variable
  • host.frm, problems finding
  • HOUR()
  • I

  • identifiers, quoting
  • IF()
  • IFNULL()
  • IGNORE INDEX, IGNORE INDEX
  • IGNORE KEY, IGNORE KEY
  • IN
  • INET_ATON()
  • INET_NTOA()
  • INNER JOIN
  • INSERT, INSERT
  • INSERT ... SELECT
  • INSERT DELAYED
  • INSERT statement, grant privileges
  • INSERT()
  • insertid DBI method
  • INSTR()
  • INT
  • INTEGER
  • INTERVAL()
  • IS NOT NULL
  • IS NULL
  • IS NULL, and indexes
  • is_blob DBI method
  • IS_FREE_LOCK()
  • is_key DBI method
  • is_not_null DBI method
  • is_num DBI method
  • is_pri_key DBI method
  • ISNULL()
  • ISOLATION LEVEL
  • J

  • JOIN
  • K

  • KILL
  • L

  • LAST_INSERT_ID()
  • LAST_INSERT_ID([expr])
  • LCASE()
  • LD_RUN_PATH environment variable, LD_RUN_PATH environment variable, LD_RUN_PATH environment variable, LD_RUN_PATH environment variable
  • LEAST()
  • LEFT JOIN, LEFT JOIN
  • LEFT OUTER JOIN
  • LEFT()
  • length DBI method
  • LENGTH()
  • less than (<)
  • less than or equal (<=)
  • LIKE
  • LIKE, and indexes
  • LIKE, and wildcards
  • LIMIT, LIMIT
  • LN()
  • LOAD DATA INFILE, LOAD DATA INFILE
  • LOAD_FILE()
  • LOCATE(), LOCATE()
  • LOCK TABLES
  • LOG()
  • LOG10()
  • LOG2()
  • Logical operators
  • LONGBLOB
  • LONGTEXT
  • LOWER()
  • LPAD()
  • LTRIM()
  • M

  • MAKE_SET()
  • MASTER_POS_WAIT()
  • MATCH ... AGAINST()
  • mathematical functions
  • MAX()
  • max_length DBI method
  • MD5()
  • MEDIUMBLOB
  • MEDIUMINT
  • MEDIUMTEXT
  • MID()
  • MIN()
  • minus, unary (-)
  • MINUTE()
  • miscellaneous functions
  • MOD()
  • modulo (%)
  • MONTH()
  • MONTHNAME()
  • multiplication (*)
  • my_init()
  • my_ulonglong C type
  • my_ulonglong values, printing
  • MYSQL C type
  • mysql_affected_rows()
  • mysql_change_user()
  • mysql_character_set_name()
  • mysql_close()
  • mysql_connect()
  • mysql_create_db()
  • mysql_data_seek()
  • MYSQL_DEBUG environment variable, MYSQL_DEBUG environment variable
  • MYSQL_DEBUG environment variable
  • mysql_debug()
  • mysql_drop_db()
  • mysql_dump_debug_info()
  • mysql_eof()
  • mysql_errno()
  • mysql_error()
  • mysql_escape_string()
  • mysql_fetch_field()
  • mysql_fetch_field_direct()
  • mysql_fetch_fields()
  • mysql_fetch_lengths()
  • mysql_fetch_row()
  • MYSQL_FIELD C type
  • mysql_field_count(), mysql_field_count()
  • MYSQL_FIELD_OFFSET C type
  • mysql_field_seek()
  • mysql_field_tell()
  • mysql_free_result()
  • mysql_get_client_info()
  • mysql_get_host_info()
  • mysql_get_proto_info()
  • mysql_get_server_info()
  • mysql_get_server_version()
  • MYSQL_HISTFILE environment variable
  • MYSQL_HISTFILE environment variable
  • MYSQL_HOST environment variable
  • MYSQL_HOST environment variable
  • mysql_info(), mysql_info(), mysql_info(), mysql_info()
  • mysql_info()
  • mysql_init()
  • mysql_insert_id()
  • mysql_insert_id()
  • mysql_kill()
  • mysql_list_dbs()
  • mysql_list_fields()
  • mysql_list_processes()
  • mysql_list_tables()
  • mysql_num_fields()
  • mysql_num_rows()
  • mysql_options()
  • mysql_ping()
  • MYSQL_PS1 environment variable
  • MYSQL_PWD environment variable
  • MYSQL_PWD environment variable, MYSQL_PWD environment variable
  • mysql_query(), mysql_query()
  • mysql_real_connect()
  • mysql_real_escape_string()
  • mysql_real_escape_string()
  • mysql_real_query()
  • mysql_reload()
  • MYSQL_RES C type
  • MYSQL_ROW C type
  • mysql_row_seek()
  • mysql_row_tell()
  • mysql_select_db()
  • mysql_server_end()
  • mysql_server_init()
  • mysql_shutdown()
  • mysql_stat()
  • mysql_store_result(), mysql_store_result()
  • MYSQL_TCP_PORT environment variable, MYSQL_TCP_PORT environment variable
  • MYSQL_TCP_PORT environment variable, MYSQL_TCP_PORT environment variable
  • mysql_thread_end()
  • mysql_thread_id()
  • mysql_thread_init()
  • mysql_thread_safe()
  • MYSQL_UNIX_PORT environment variable, MYSQL_UNIX_PORT environment variable, MYSQL_UNIX_PORT environment variable
  • MYSQL_UNIX_PORT environment variable, MYSQL_UNIX_PORT environment variable
  • mysql_use_result()
  • N

  • NAME DBI method
  • NATIONAL CHAR
  • NATURAL LEFT JOIN
  • NATURAL LEFT OUTER JOIN
  • NATURAL RIGHT JOIN
  • NATURAL RIGHT OUTER JOIN
  • NCHAR
  • newline (\n)
  • NOT BETWEEN
  • not equal (!=)
  • not equal (<>)
  • NOT IN
  • NOT LIKE
  • NOT REGEXP
  • NOT, logical
  • NOW()
  • NUL
  • NULL, NULL
  • NULL value
  • NULLABLE DBI method
  • NULLIF()
  • NUM_OF_FIELDS DBI method
  • NUMERIC
  • O

  • OCT()
  • OCTET_LENGTH()
  • OLD_PASSWORD()
  • Operators, logical
  • OPTIMIZE TABLE
  • OR, bitwise
  • OR, logical
  • ORD()
  • ORDER BY
  • P

  • parentheses ( and )
  • PASSWORD(), PASSWORD(), PASSWORD(), PASSWORD()
  • PATH environment variable, PATH environment variable
  • PERIOD_ADD()
  • PERIOD_DIFF()
  • PI()
  • POSITION()
  • POW()
  • POWER()
  • prepare() DBI method
  • PRIMARY KEY, PRIMARY KEY
  • PROCESSLIST
  • Q

  • QUARTER()
  • QUOTE()
  • quote() DBI method
  • quoting of identifiers
  • R

  • RADIANS()
  • RAND()
  • REAL
  • REGEXP
  • RELEASE_LOCK()
  • RENAME TABLE
  • REPAIR TABLE
  • REPEAT()
  • REPLACE
  • REPLACE ... SELECT
  • REPLACE()
  • REQUIRE GRANT option
  • RESTORE TABLE
  • return (\r)
  • REVERSE()
  • REVOKE
  • RIGHT JOIN
  • RIGHT OUTER JOIN
  • RIGHT()
  • RLIKE
  • ROLLBACK, ROLLBACK
  • ROUND(), ROUND()
  • rows DBI method
  • RPAD()
  • RTRIM()
  • S

  • SEC_TO_TIME()
  • SECOND()
  • SELECT
  • SELECT INTO TABLE
  • SELECT speed
  • SELECT, optimizing
  • SESSION_USER()
  • SET
  • SET OPTION
  • SET PASSWORD statement
  • SET TRANSACTION
  • SHA()
  • SHA1()
  • SHOW COLUMNS
  • SHOW CREATE TABLE, SHOW CREATE TABLE
  • SHOW DATABASE INFO
  • SHOW DATABASES
  • SHOW FIELDS
  • SHOW GRANTS, SHOW GRANTS
  • SHOW INDEX
  • SHOW KEYS
  • SHOW MASTER LOGS
  • SHOW MASTER STATUS
  • SHOW PRIVILEGES
  • SHOW PROCESSLIST, SHOW PROCESSLIST
  • SHOW SLAVE STATUS
  • SHOW STATUS
  • SHOW TABLE STATUS
  • SHOW TABLE TYPES, SHOW TABLE TYPES
  • SHOW TABLES
  • SHOW VARIABLES
  • SHOW WARNINGS, SHOW WARNINGS
  • SIGN()
  • SIN()
  • single quote (\')
  • SMALLINT
  • SOUNDEX()
  • SOUNDS LIKE
  • SPACE()
  • SQL_CACHE
  • SQL_NO_CACHE
  • SQRT()
  • START TRANSACTION
  • statements, GRANT
  • statements, INSERT
  • STD()
  • STDDEV()
  • STRAIGHT_JOIN
  • STRCMP()
  • string comparison functions
  • string functions
  • SUBDATE()
  • SUBSTRING(), SUBSTRING()
  • SUBSTRING_INDEX()
  • subtraction (-)
  • SUM()
  • SYSDATE()
  • SYSTEM_USER()
  • T

  • tab (\t)
  • table DBI method
  • table_cache
  • TAN()
  • TEXT, TEXT
  • threads
  • TIME, TIME
  • TIME_FORMAT()
  • TIME_TO_SEC()
  • TIMESTAMP, TIMESTAMP
  • TINYBLOB
  • TINYINT
  • TINYTEXT
  • TMPDIR environment variable, TMPDIR environment variable
  • TO_DAYS()
  • trace DBI method, trace DBI method
  • TRIM()
  • TRUNCATE
  • TRUNCATE()
  • type DBI method
  • Types
  • TZ environment variable, TZ environment variable
  • U

  • UCASE()
  • UDF functions
  • ulimit
  • UMASK environment variable, UMASK environment variable
  • UMASK_DIR environment variable, UMASK_DIR environment variable
  • unary minus (-)
  • UNION, UNION
  • UNIQUE
  • UNIX_TIMESTAMP()
  • UNLOCK TABLES
  • UPDATE
  • UPPER()
  • USE
  • USE INDEX, USE INDEX
  • USE KEY, USE KEY
  • USER environment variable
  • USER environment variable
  • USER()
  • User-defined functions
  • V

  • VARCHAR, VARCHAR
  • VARIANCE()
  • VERSION()
  • W

  • WEEK()
  • WEEKDAY()
  • WHERE
  • Wildcard character (%)
  • Wildcard character (_)
  • without-server option
  • X

  • XOR, bitwise
  • XOR, logical
  • Y

  • YEAR, YEAR
  • YEAR()
  • | (bitwise OR)
  • || (logical OR)
  • ~
  • Concept Index

    A

  • aborted clients
  • aborted connection
  • access control
  • access denied errors
  • access privileges
  • Access program
  • ACID
  • ACID
  • ACLs
  • ActiveState Perl
  • adding, character sets
  • adding, native functions
  • adding, new functions
  • adding, new user privileges
  • adding, new users
  • adding, procedures
  • adding, user-definable functions
  • administration, server
  • ADO program
  • age, calculating
  • alias names, case-sensitivity
  • aliases, for expressions
  • aliases, for tables
  • aliases, in GROUP BY clauses
  • aliases, in ORDER BY clauses
  • aliases, names
  • aliases, on expressions
  • anonymous user, anonymous user, anonymous user, anonymous user
  • ANSI mode, running
  • ANSI SQL, differences from
  • ANSI SQL92, extensions to
  • answering questions, etiquette
  • Apache
  • APIs
  • APIs, Perl
  • applying, patches
  • argument processing
  • arithmetic expressions
  • AUTO-INCREMENT, ODBC
  • AUTO_INCREMENT
  • AUTO_INCREMENT, using with DBI
  • AUTO_INCREMENT, and NULL values
  • B

  • backing up, databases, backing up, databases
  • backslash, escape character
  • backups
  • backups, database
  • batch mode
  • batch, mysql option
  • BDB table type
  • BDB tables
  • benchmark suite
  • benchmarks
  • BerkeleyDB table type
  • Big5 Chinese character encoding
  • binary distributions
  • binary distributions, installing
  • binary distributions, on HP-UX
  • binary distributions, on Linux
  • binary log
  • Binlog_Dump
  • bit_functions, example
  • BitKeeper tree
  • BLOB columns, default values
  • BLOB columns, indexing
  • BLOB, inserting binary data
  • BLOB, size
  • Borland Builder 4 program
  • Borland C++ compiler
  • brackets, square
  • buffer sizes, client
  • buffer sizes, mysqld server
  • bug reports, criteria for
  • bug reports, email address
  • bugs, known
  • bugs, reporting
  • building, client programs
  • C

  • C API, datatypes
  • C API, functions
  • C API, linking problems
  • C++
  • C++ APIs
  • C++ Builder
  • C++ compiler cannot create executables
  • C++ compiler, gcc
  • caches, clearing
  • calculating, dates
  • calling sequences for aggregate functions, UDF
  • calling sequences for simple functions, UDF
  • can't create/write to file
  • case-sensitivity, in access checking
  • case-sensitivity, in names
  • case-sensitivity, in searches
  • case-sensitivity, in string comparisons
  • case-sensitivity, of database names
  • case-sensitivity, of table names
  • cast operators
  • casts
  • cc1plus problems
  • certification
  • ChangeLog
  • changes to privileges
  • changes, log
  • changes, version 3.22
  • changes, version 3.23
  • changes, version 4.0
  • changes, version 4.1
  • changes, version 5.0
  • changing socket location, changing socket location, changing socket location
  • changing, column
  • changing, column order
  • changing, field
  • changing, table, changing, table, changing, table
  • character sets, character sets
  • character sets, adding
  • character-sets-dir, mysql option
  • characters, multi-byte
  • check options, myisamchk
  • checking, tables for errors
  • checksum errors
  • Chinese
  • choosing types
  • choosing, a MySQL version
  • clearing, caches
  • client programs, building
  • client tools
  • clients, debugging
  • clients, threaded
  • closing, tables
  • ColdFusion program
  • collating, strings
  • column names, case-sensitivity
  • column, changing
  • columns, changing
  • columns, displaying
  • columns, indexes
  • columns, names
  • columns, other types
  • columns, selecting
  • columns, storage requirements
  • columns, types
  • command syntax
  • command-line history
  • command-line options, mysql
  • command-line tool
  • commands out of sync
  • commands, for binary distribution
  • commands, list of
  • commands, replication
  • comments, adding
  • comments, starting
  • commercial support, types
  • communications protocols
  • comparisons, MySQL vs. others
  • compatibility, between MySQL versions, compatibility, between MySQL versions, compatibility, between MySQL versions, compatibility, between MySQL versions
  • compatibility, with ANSI SQL
  • compatibility, with mSQL
  • Compatibility, with ODBC
  • compatibility, with ODBC, compatibility, with ODBC, compatibility, with ODBC, compatibility, with ODBC, compatibility, with ODBC, compatibility, with ODBC
  • compatibility, with Oracle, compatibility, with Oracle, compatibility, with Oracle
  • compatibility, with PostgreSQL
  • compatibility, with Sybase
  • compiler, C++ gcc
  • compiling, on Windows
  • compiling, optimizing
  • compiling, problems
  • compiling, speed
  • compiling, statically
  • compiling, user-defined functions
  • compliance, Y2K
  • compress, mysql option
  • compressed tables, compressed tables
  • config-file option
  • config.cache
  • config.cache file
  • configuration files
  • configuration options
  • configure option, --with-low-memory
  • configure script
  • configure, running after prior invocation
  • connect_timeout variable
  • connecting, remotely with SSH
  • connecting, to the server, connecting, to the server
  • connecting, verification
  • connection, aborted
  • constant table, constant table
  • consulting
  • contact information
  • contributed programs
  • contributing companies, list of
  • contributors, list of
  • control access
  • conventions, typographical
  • converters
  • converting, tools
  • copyrights
  • costs, support
  • counting, table rows
  • crackers, security against
  • crash
  • crash, recovery
  • crash, repeated
  • crash-me
  • crash-me program, crash-me program
  • creating, bug reports
  • creating, databases
  • creating, default startup options
  • creating, tables
  • customer support, mailing address
  • customers, of MySQL
  • CVS tree
  • D

  • data, character sets
  • data, importing
  • data, loading into tables
  • data, retrieving
  • data, size
  • database design
  • database names, case-sensitivity, database names, case-sensitivity
  • database, deleting
  • database, mysql option
  • databases, backups
  • databases, creating
  • databases, defined
  • databases, displaying
  • databases, dumping, databases, dumping
  • databases, information about
  • databases, MySQL vs. others
  • databases, names
  • databases, replicating
  • databases, selecting
  • databases, symbolic links
  • databases, using
  • DataJunction
  • datatypes, C API
  • Date and Time types
  • date calculations
  • DATE columns, problems
  • date functions, Y2K compliance
  • date types
  • date types, Y2K issues
  • date values, problems
  • db table, sorting
  • DBUG package
  • debug-info, mysql option
  • debug, mysql option
  • debugging, client
  • debugging, server
  • decimal point
  • default hostname
  • default installation location
  • default options
  • default values, default values, default values
  • default values, BLOB and TEXT columns
  • default values, suppression
  • default, privileges
  • default-character-set, mysql option
  • defaults, embedded
  • delayed_insert_limit
  • deleting, database
  • deleting, function
  • deleting, index, deleting, index
  • deleting, primary key
  • deleting, rows
  • deleting, table
  • deletion, mysql.sock
  • Delphi
  • Delphi program
  • design, choices
  • design, issues
  • design, limitations
  • developers, list of
  • development source tree
  • digits
  • directory structure, default
  • disconnecting, from the server
  • disk full
  • disk issues
  • disks, splitting data across
  • display size
  • displaying, database information
  • displaying, information, SHOW
  • displaying, table status
  • DNS
  • downgrading
  • downloading
  • dumping, databases, dumping, databases
  • dynamic table characteristics
  • E

  • e-mail lists
  • Eiffel Wrapper
  • embedded MySQL server library
  • employment with MySQL
  • employment, contact information
  • enable-named-commands, mysql option
  • entering, queries
  • ENUM, size
  • environment variables, environment variables, environment variables, environment variables
  • environment variables, list of
  • Errcode
  • errno
  • error mesaages, can't find file
  • error messages, displaying
  • error messages, languages
  • errors, access denied
  • errors, checking tables for
  • errors, common
  • errors, directory checksum
  • errors, handling for UDFs
  • errors, known
  • errors, linking
  • errors, list of
  • errors, reporting, errors, reporting, errors, reporting
  • escape characters
  • estimating, query performance
  • example option
  • examples, compressed tables
  • examples, myisamchk output
  • examples, queries
  • Excel
  • execute, mysql option
  • expression aliases, expression aliases
  • expressions, extended
  • extensions, to ANSI SQL
  • extracting, dates
  • F

  • fatal signal 11
  • features of MySQL
  • field, changing
  • files, binary log
  • files, config.cache
  • files, error messages
  • files, log, files, log
  • files, not found message
  • files, permissions
  • files, query log
  • files, repairing
  • files, script
  • files, size limits
  • files, slow query log
  • files, text
  • files, tmp
  • files, update log
  • files,`my.cnf'
  • floating-point number
  • floats
  • flush tables
  • force, mysql option
  • foreign keys, foreign keys, foreign keys
  • free licensing
  • FreeBSD troubleshooting
  • full disk
  • full-text search
  • FULLTEXT
  • function, deleting
  • functions for SELECT and WHERE clauses
  • functions, C API
  • functions, grouping
  • functions, native, adding
  • functions, new
  • functions, user-definable, adding
  • functions, user-defined
  • G

  • gcc
  • gdb, using
  • general information
  • General Public License
  • General Public License, MySQL
  • getting MySQL
  • global privileges
  • goals of MySQL
  • GPL, General Public License
  • GPL, GNU General Public License
  • GPL, MySQL
  • grant tables
  • grant tables, re-creating
  • grant tables, sorting, grant tables, sorting
  • granting, privleges
  • GROUP BY, aliases in
  • GROUP BY, extensions to ANSI SQL, GROUP BY, extensions to ANSI SQL
  • grouping, expressions
  • H

  • handling, errors
  • HEAP table type
  • help option
  • help, mysql option
  • hints, hints, hints, hints, hints
  • history file
  • history of MySQL
  • host table
  • host table, sorting
  • host, mysql option
  • hostname caching
  • hostname, default
  • HP-UX, binary distribution
  • html, mysql option
  • I

  • ID, unique
  • ignore-space, mysql option
  • importing, data
  • increasing, performance
  • increasing, speed
  • index, deleting, index, deleting
  • indexes
  • indexes, and BLOB columns
  • indexes, and IS NULL
  • indexes, and LIKE
  • indexes, and NULL values
  • indexes, and TEXT columns
  • indexes, block size
  • indexes, columns
  • indexes, leftmost prefix of
  • indexes, multi-column
  • indexes, multi-part
  • indexes, names
  • indexes, use of
  • InnoDB table type
  • InnoDB tables
  • INSERT DELAYED
  • inserting, speed of
  • installation layouts
  • installation overview
  • Installing many servers
  • installing, binary distribution
  • installing, Linux RPM packages
  • installing, Mac OS X PKG packages
  • installing, overview
  • installing, Perl
  • installing, Perl on Windows
  • installing, source distribution
  • installing, user-defined functions
  • integers
  • internal compiler errors
  • internal locking
  • internals
  • Internet Relay Chat
  • Internet Service Providers
  • IRC
  • ISAM table type
  • ISP services
  • J

  • Java connectivity
  • JDBC
  • jobs at MySQL
  • K

  • key space, MyISAM
  • keys
  • keys, foreign, keys, foreign
  • keys, multi-column
  • keys, searching on two
  • keywords
  • known errors
  • L

  • language support
  • last row, unique ID
  • layout of installation
  • leftmost prefix of indexes, leftmost prefix of indexes
  • legal names
  • LGPL, GNU Lesser General Public License
  • LGPL, GNU Library General Public License
  • LGPL, Lesser General Public License
  • LGPL, Library General Public License
  • libmysqld
  • library, mysqlclient
  • licenses
  • licensing costs
  • licensing policy
  • licensing terms
  • licensing, contact information
  • licensing, examples
  • licensing, free
  • limitations, design
  • limits, file-size
  • linking
  • linking, errors
  • linking, problems
  • linking, speed
  • links, symbolic
  • Linux, binary distribution
  • literals
  • loading, tables
  • locking
  • locking methods
  • locking, row-level
  • locking, tables
  • log files
  • Log files
  • log files, maintaining
  • log files, names
  • log option
  • log, changes
  • logos
  • M

  • Mac OS X, installation
  • mailing address, for customer support
  • mailing list address
  • mailing lists
  • mailing lists, archive location
  • mailing lists, guidelines
  • main features of MySQL
  • maintaining, log files
  • maintaining, tables
  • make_binary_distribution
  • manual, available formats
  • manual, online location
  • manual, typographical conventions
  • master-slave setup
  • matching, patterns
  • max memory used
  • max_allowed_packet
  • max_join_size
  • memory usage, myisamchk
  • memory use, memory use
  • MERGE table type
  • MERGE tables, defined
  • messages, languages
  • methods, locking
  • mirror sites
  • MIT-pthreads
  • modes, batch
  • modules, list of
  • monitor, terminal
  • mSQL compatibility
  • mSQL vs. MySQL, protocol
  • mSQL, MySQL vs mSQL, overview
  • msql2mysql
  • multi mysqld
  • multi-byte character sets
  • multi-byte characters
  • multi-column indexes
  • multi-part index
  • multiple servers
  • My, derivation
  • `my.cnf' file
  • MyISAM table type
  • MyISAM, compressed tables, MyISAM, compressed tables
  • MyISAM, size
  • myisamchk, myisamchk
  • myisamchk, example output
  • myisamchk, options
  • myisampack, myisampack, myisampack
  • MyODBC
  • MyODBC, reporting problems
  • mysql
  • MySQL AB, defined
  • MySQL binary distribution
  • MySQL certification
  • mysql command-line options
  • MySQL consulting
  • MySQL history
  • MySQL mailing lists
  • MySQL name
  • MySQL source distribution
  • MySQL table types
  • MySQL tools, conversion
  • MySQL training
  • MySQL version
  • MySQL, defined
  • MySQL, introduction
  • MySQL, pronunciation
  • mysql.sock, changing location of
  • mysql.sock, protection
  • mysql_fix_privilege_tables
  • mysql_install_db
  • mysql_install_db script
  • mysqlaccess
  • mysqladmin, mysqladmin, mysqladmin, mysqladmin, mysqladmin, mysqladmin, mysqladmin
  • mysqladmin option
  • mysqlbinlog, mysqlbinlog
  • mysqlbug
  • mysqlbug script
  • mysqlbug script, location
  • mysqlclient library
  • mysqld
  • mysqld option
  • mysqld options
  • mysqld options
  • mysqld server, buffer sizes
  • mysqld, starting
  • mysqld-max
  • mysqld_multi
  • mysqld_safe
  • mysqldump, mysqldump, mysqldump
  • mysqlimport, mysqlimport, mysqlimport, mysqlimport
  • mysqlshow
  • mysqltest, MySQL Test Suite
  • N

  • named pipes
  • names
  • names, case-sensitivity
  • names, variables
  • naming, releases of MySQL
  • native functions, adding
  • native thread support
  • negative values
  • net etiquette, net etiquette
  • net_buffer_length
  • netmask notation, in mysql.user table
  • new procedures, adding
  • new users, adding
  • no matching rows
  • no-auto-rehash, mysql option
  • no-beep, mysql option
  • no-log option
  • no-named-commands, mysql option
  • no-pager, mysql option
  • no-tee, mysql option
  • non-delimited strings
  • Non-transactional tables
  • NULL value
  • NULL values, and indexes
  • NULL values, vs. empty values
  • NULL, testing for null, NULL, testing for null, NULL, testing for null, NULL, testing for null
  • NULL values, and AUTO_INCREMENT columns
  • NULL values, and TIMESTAMP columns
  • numbers
  • numeric types
  • O

  • ODBC
  • ODBC compatibility, ODBC compatibility, ODBC compatibility, ODBC compatibility, ODBC compatibility, ODBC compatibility, ODBC compatibility
  • ODBC, administrator
  • odbcadmin program
  • OLEDB
  • one-database, mysql option
  • online location of manual
  • Open Source, defined
  • open tables, open tables
  • opening, tables
  • opens
  • OpenSSL
  • operating systems, file-size limits
  • operating systems, supported
  • operating systems, Windows versus Unix
  • operations, arithmetic
  • operators, cast, operators, cast
  • optimising, tables
  • optimization, tips
  • optimizations
  • optimizing, DISTINCT
  • optimizing, LEFT JOIN
  • optimizing, LIMIT
  • option files
  • options, command-line
  • options, command-line, mysql
  • options, configure
  • options, myisamchk
  • options, provided by MySQL
  • options, replication
  • Oracle compatibility, Oracle compatibility, Oracle compatibility
  • ORDER BY, aliases in
  • overview
  • P

  • pack_isam
  • pager, mysql option
  • parameters, server
  • partnering with MySQL AB
  • password encryption, reversibility of
  • password option
  • password, root user
  • password, mysql option
  • passwords, for users
  • passwords, forgotten
  • passwords, resetting
  • passwords, security
  • passwords, setting, passwords, setting, passwords, setting
  • patches, applying
  • pattern matching
  • performance, benchmarks
  • performance, disk issues
  • performance, estimating
  • performance, improving, performance, improving
  • Perl API
  • Perl DBI/DBD, installation problems
  • Perl, installing
  • Perl, installing on Windows
  • Perl, modules
  • permission checks, effect on speed
  • perror
  • PHP API
  • port, mysql option
  • portability
  • portability, types
  • porting, to other systems
  • post-install, many servers
  • post-installation, setup and testing
  • PostgreSQL compatibility
  • PostgreSQL vs. MySQL, benchmarks
  • PostgreSQL vs. MySQL, features
  • PostgreSQL vs. MySQL, overview
  • PostgreSQL vs. MySQL, strategies
  • prices, support
  • primary key, deleting
  • privilege information, location
  • privilege system
  • privilege system, described
  • privilege, changes
  • privileges, access
  • privileges, adding
  • privileges, default
  • privileges, display
  • privileges, granting
  • privileges, revoking
  • problems, access denied errors
  • problems, common errors
  • problems, compiling
  • problems, DATE columns
  • problems, date values
  • problems, installing on IBM-AIX
  • problems, installing on Solaris
  • problems, installing Perl
  • problems, linking
  • problems, ODBC
  • problems, reporting
  • problems, starting the server
  • problems, table locking
  • problems, timezone
  • procedures, adding
  • procedures, stored
  • process support
  • processes, display
  • processing, arguments
  • products, selling
  • programs, client
  • programs, contributed
  • programs, crash-me
  • programs, list of, programs, list of
  • prompt command
  • prompt, mysql option
  • prompts, meanings
  • pronunciation, MySQL
  • Protocol mismatch
  • protocol, mysql option, protocol, mysql option
  • Python APIs
  • Q

  • queries, C API results
  • queries, entering
  • queries, estimating performance
  • queries, examples
  • queries, speed of
  • queries, Twin Studeis project
  • Query Cache
  • query log
  • questions
  • questions, answering
  • quick, mysql option
  • quotes, in strings
  • quoting
  • quoting binary data
  • quoting strings
  • R

  • raw, mysql option
  • re-creating, grant tables
  • reconfiguring, reconfiguring
  • reconnect, mysql option
  • recovery, from crash
  • reducing, data size
  • references
  • regex
  • regular expression syntax, described
  • relational databases, defined
  • release numbers
  • releases, naming scheme
  • releases, testing
  • releases, updating
  • reordering, columns
  • repair options, myisamchk
  • repairing, tables
  • replace
  • replication
  • replication, commands
  • replication, two-way
  • reporting, bugs
  • reporting, errors, reporting, errors
  • reporting, MyODBC problems
  • reserved words, exceptions
  • restarting, the server
  • retrieving, data from tables
  • return values, UDFs
  • revoking, privleges
  • root password
  • root user, password resetting
  • rounding errors, rounding errors
  • rows, counting
  • rows, deleting
  • rows, locking
  • rows, matching problems
  • rows, selecting
  • rows, sorting
  • RPM file
  • RPM Package Manager, RPM Package Manager
  • RPM, defined
  • RTS-threads
  • running a web server
  • running configure after prior invocation
  • running, ANSI mode
  • running, batch mode
  • running, multiple servers
  • running, queries
  • S

  • safe-mode command
  • safe-updates, mysql option
  • safe_mysqld
  • script files
  • scripts, scripts, scripts
  • scripts, mysql_install_db
  • scripts, mysqlbug
  • searching, and case-sensitivity
  • searching, full-text
  • searching, MySQL web pages
  • searching, two keys
  • security system
  • security, against crackers
  • SELECT, Query Cache
  • select_limit
  • selecting, databases
  • selling products
  • sequence emulation
  • server administration
  • server, connecting, server, connecting
  • server, debugging
  • server, disconnecting
  • server, restart
  • server, shutdown
  • server, starting
  • server, starting and stopping
  • server, starting problems
  • servers, multiple
  • services, ISP
  • services, web
  • SET, size
  • set-variable, mysql option
  • setting, passwords
  • setup, post-installation
  • shell syntax
  • showing, database information
  • shutting down, the server
  • silent column changes
  • silent, mysql option
  • size of tables
  • sizes, display
  • skip-column-names, mysql option
  • skip-line-numbers, mysql option
  • slow queries
  • slow query log
  • socket location, changing
  • socket, mysql option
  • Solaris installation problems
  • Solaris troubleshooting
  • sorting, character sets
  • sorting, data
  • sorting, grant tables, sorting, grant tables
  • sorting, table rows
  • source distribution, installing
  • speed, compiling
  • speed, increasing
  • speed, inserting
  • speed, linking
  • speed, of queries, speed, of queries
  • SQL commands, replication
  • SQL, defined
  • sql_yacc.cc problems
  • square brackets
  • SSH
  • SSL and X509 Basics
  • SSL related options
  • stability
  • standards compatibility
  • Starting many servers
  • starting, comments
  • starting, mysqld
  • starting, the server
  • starting, the server automatically
  • startup options, default
  • startup parameters
  • startup parameters, mysql
  • startup parameters, tuning
  • statically, compiling
  • status command
  • status command, results
  • status, tables
  • stopping, the server
  • storage of data
  • storage requirements, column type
  • storage space, minimizing
  • stored procedures and triggers, defined
  • string collating
  • string comparisons, case-sensitivity
  • string types
  • strings, defined
  • strings, escaping characters
  • strings, non-delimited
  • strings, quoting
  • striping, defined
  • subSELECTs
  • superuser
  • support costs
  • support terms
  • support, for operating systems
  • support, licensing
  • support, mailing address
  • support, types
  • suppression, default values
  • Sybase compatibility
  • symbolic links, symbolic links
  • syntax, regular expression
  • system optimization
  • system table
  • system variables
  • system, privilege
  • system, security
  • T

  • table aliases
  • table cache
  • table is full, table is full
  • table names, case-sensitivity, table names, case-sensitivity
  • table types, choosing
  • table, changing, table, changing, table, changing
  • table, deleting
  • table, mysql option
  • tables, BDB
  • tables, Berkeley DB
  • tables, changing column order
  • tables, checking
  • tables, closing
  • tables, compressed
  • tables, compressed format
  • tables, constant, tables, constant
  • tables, counting rows
  • tables, creating
  • tables, defragment, tables, defragment
  • tables, defragmenting
  • tables, deleting rows
  • tables, displaying
  • tables, displaying status
  • tables, dumping, tables, dumping
  • tables, dynamic
  • tables, error checking
  • tables, flush
  • tables, fragmentation
  • tables, grant
  • tables, HEAP
  • tables, host
  • tables, improving performance
  • tables, information
  • tables, information about
  • tables, ISAM
  • tables, loading data
  • tables, locking
  • tables, maintenance regimen
  • tables, maximum size
  • tables, merging
  • tables, multiple
  • tables, names
  • tables, open
  • tables, opening
  • tables, optimising
  • tables, repairing
  • tables, retrieving data
  • tables, selecting columns
  • tables, selecting rows
  • tables, sorting rows
  • tables, symbolic links
  • tables, system
  • tables, too many
  • tables, unique ID for last row
  • tables, updating
  • tar, problems on Solaris
  • Tcl APIs
  • tcp-ip option
  • TCP/IP
  • technical support, licensing
  • technical support, mailing address
  • tee, mysql option
  • temporary file, write access
  • temporary tables, problems
  • terminal monitor, defined
  • testing mysqld, mysqltest
  • testing, connection to the server
  • testing, installation
  • testing, of MySQL releases
  • testing, post-installation
  • testing, the server
  • Texinfo
  • TEXT columns, default values
  • TEXT columns, indexing
  • text files, importing
  • TEXT, size
  • thread packages, differences between
  • thread support
  • thread support, non-native
  • threaded clients
  • threads, threads
  • threads, display
  • threads, RTS
  • time types
  • timeout, timeout, timeout
  • timeout, connect_timeout variable
  • TIMESTAMP, and NULL values
  • timezone problems
  • tips, optimization
  • ToDo list for MySQL
  • TODO, embedded server
  • TODO, symlinks
  • tools, command-line
  • tools, converting
  • tools, mysqld_multi
  • tools, safe_mysqld
  • trademarks
  • training
  • transaction-safe tables, transaction-safe tables
  • transactions, support, transactions, support
  • triggers, stored
  • troubleshooting, FreeBSD
  • troubleshooting, Solaris
  • tutorial
  • Twin Studies, queries
  • type conversions
  • types of support
  • types, columns, types, columns
  • types, date
  • types, Date and Time
  • types, numeric
  • types, of tables
  • types, portability
  • types, strings
  • types, time
  • typographical conventions
  • U

  • UDFs, compiling
  • UDFs, defined
  • UDFs, return values
  • unbuffered, mysql option
  • unique ID
  • unloading, tables
  • update log
  • updating, releases of MySQL
  • updating, tables
  • upgrading
  • upgrading, 3.20 to 3.21
  • upgrading, 3.21 to 3.22
  • upgrading, 3.22 to 3.23
  • upgrading, 3.23 to 4.0
  • upgrading, 4.0 to 4.1
  • upgrading, different architecture
  • uptime
  • URLS for downloading MySQL
  • user names, and passwords
  • user option
  • user privileges, adding
  • user table, sorting
  • user variables
  • user-defined functions, adding, user-defined functions, adding
  • user, mysql option
  • users, adding
  • users, root
  • uses, of MySQL
  • using multiple disks to start data
  • utilities
  • V

  • valid numbers, examples
  • VARCHAR, size
  • variables, mysqld
  • variables, status
  • variables, System
  • variables, user
  • variables, values
  • verbose, mysql option
  • version option
  • version, choosing
  • version, latest
  • version, mysql option
  • vertical, mysql option
  • views
  • virtual memory, problems while compiling
  • Visual Basic
  • W

  • wait, mysql option
  • web server, running
  • What is an X509/Certificate?
  • What is encryption
  • wildcards, and LIKE
  • wildcards, in mysql.columns_priv table
  • wildcards, in mysql.db table
  • wildcards, in mysql.host table
  • wildcards, in mysql.tables_priv table
  • wildcards, in mysql.user table
  • Windows
  • Windows, compiling on
  • Windows, open issues
  • Windows, versus Unix
  • Word program
  • wrappers, Eiffel
  • write access, tmp
  • X

  • xml, mysql option
  • Y

  • Year 2000 compliance
  • Year 2000 issues

  • This document was generated on 3 August 2004 using the texi2html translator version 1.52 (extended by davida@detron.se).