MySQL (TM)
ソフトウェアはとても高速で、マルチスレッド、マルチユーザの、頑丈な SQL
(Structured Query Language
)データベースサーバです。
MySQL Server
は、mass-deployed ソフトウェアへの組み込みのように、ミッションクリティ
カルで高負荷生産システム用に意図されています。
MySQL
は MySQL AB
の商標です。
MySQL
ソフトウェア は Dual Licensed
です。
あなたは、MySQL
を GNU GENERAL PUBLIC LICENSE
(http://www.gnu.org/licenses/) に従って、
Open Source
/Free Software
として利用できます。
あるいは、GPL の条件が合わない場合には、
コマーシャルライセンスを MySQL AB
から購入することも可能です。
See section MySQL ライセンスとサポート.
MySQL
ウェブサイト (http://www.mysql.com/) は MySQL
ソフトウェア
についての最新情報を提供しています。
次のリストはマニュアルのいくつかの有用なセクションを説明しています:
MySQL Database Server
の背景にある会社についての情報は、section MySQL AB とは何か を
参照してください。
MySQL Database Server
の能力の説明については、section MySQL の主な機能 を参照してください。
MySQL Database Software
を新しいアーキテクチャや OS に移行するためのヒントについては
section 他のシステムへの移植について を参照してください。
MySQL Database Server
導入のチュートリアルについては、section Tutorial Introduction を参照してください。
SQL
の例とベンチマーク情報についてはベンチマーキングのディレクトリを参照
してください。(`sql-bench' ディレクトリです)
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
バージョンは texi2dvi
と divps
を使用して提供されます。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
mysqladmin
がどのように動作するかを見るためには、
--help
オプションをつけて起動してください。''
コマンドが特定のプログラムによって実行されることを意味することを表す時、
コマンドと共に表示されるプロンプトによって、そのプログラムを表します。例えば、
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
は、もっとも有名な オープンソース
SQLデータベースで、
MySQL AB
によって開発、供給されています。MySQL AB
は
MySQL
データベースに関わるサービスを提供するビジネスを構築する
営利会社です。See section MySQL AB とは何か.
MySQL
ウェブサイト(http://www.mysql.com/)は、MySQL
と MySQL AB
に
ついての最新情報を提供しています。
MySQL
はデータベース管理システムです。
MySQL
サーバーのようなデータベース管理システムが必要です。コンピュー
タは大量のデータの処理にとても向いているので、データベース管理システムは
スタンドアロンユーティリティや他のアプリケーションの一部として、コンピュー
タの中で中心的な役割を演じています。
MySQL
の SQL
部分は "構造化ク
エリ言語 (Structured Query Language
)" を表しています。これは、データベー
スのアクセスに使用される最も有名な標準言語です。
オープンソース
です。
オープンソース
の意味は誰でも使用し変更することができるということです。誰
でも MySQL
ソフトウェアをインターネットからダウンロードし、無償で使
用することができます。その気があれば誰でも必要に応じてソースコードを調べ、
変更することができます。MySQL
ソフトウェア は GPL
(GNU General Public License
)
http://www.gnu.org/licenses/ に従います。これは、様々な状況でそ
のソフトウェアで行なえることと行なえないことを定義しています。もし GPL
を嫌だと感じていたり、MySQL
を商用アプリケーションに組み込む必
要があるなら、商用ライセンス版を我々から購入することができます。
See section MySQL Licenses.
MySQL Database Server
はとても速く、信頼でき、簡単に使用できます。それがあなた
が探しているものなら、試してみるべきです。MySQL Server
は、我々のユー
ザと協力して開発されたとても実用的な機能のセットを持っています。我々のベ
ンチマークページ上で、MySQL Server
と他のいくつかのデータベース管理シ
ステムの性能比較を見つけることができます。See section The MySQL Benchmark Suite.
MySQL Server
は、既存のソリューションよりも速くとても大きなデータベー
スを処理するために、そして、高い需要がある製品環境で何年間かの使用に耐え
るために、独創的に開発されました。一定の開発下で、MySQL Server
は今日、
豊富でとても有用な機能セットを提供します。MySQL は、結合性、速
度、セキュリティでインターネット上でのデータベースアクセスに高く適合しま
す。
MySQL Database Software
は、様々なバッ
クエンドをサポートするマルチスレッド SQL
サーバ、いくつかのクライアント
プログラム、ライブラリ、管理ツール、プログラミングインタフェース(API
s)から成る
クライアント/サーバシステムです。
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 Database Server
をサポートする、あなたの好きなアプリケー
ション/言語を見つけることができるでしょう。
MySQL
の公式な発音は ``My Ess Que Ell'' です(MY-SEQUEL ではあり
ません)。
しかし MY-SEQUEL と発音する人を正すことは避けています。
最初は、我々固有の速くて低レベルな (ISAM) ルーチンを使用したテーブルへ
接続するために、 mSQL
を使用するつもりでした。
しかし、いくつかのテストの後、我々は
mSQL
は我々が必要とするほど高速ではなく、柔軟度を持っていないとの
結論に至りました。この結果、mSQL
とほとんど同じ API インタフェー
スを持つ、我々のデータベースへの新しい SQL インタフェースに帰結しました。
この API はサードパーティコードの移植を簡単にするために選択されました。
MySQL
の名前の由来は完全には明らかではありません。我々のベース
ディレクトリと多くのライブラリとツールは接頭辞 ``my'' を 10 年以上も使っ
ています。しかし、Monty の娘(何年か若い)も My という名前です。そのため、
この2つのどちらが MySQL
に名前を与えたかは、我々にとっても未だ
謎です。
MySQL Database Software
の重要な特徴のいくつかを以下の項目に挙げます。
See section MySQL 4.x In A Nutshell.
MySQL
は市販のメモリリーク検出製品 Purify と
Valgrind, a GPL tool (http://developer.kde.org/~sewardj/) で
テストされています。
FLOAT
, DOUBLE
, CHAR
, VARCHAR
,
TEXT
, BLOB
, DATE
, TIME
, DATETIME
,
TIMESTAMP
, YEAR
, SET
, ENUM
型.
See section フィールド型.
INSERT
を使用でき、明示的に値が与えられていないフィールドはそのデ
フォルト値が設定されます。
SELECT
と WHERE
部内での全ての演算子と関数のサポー
ト。例:
mysql> SELECT CONCAT(first_name, " ", last_name) -> FROM tbl_name -> WHERE income/dependents > 10000 AND age > 30;
GROUP BY
と ORDER BY
節の完全なサポート。グループ関数
(COUNT()
, COUNT(DISTINCT ...)
,
COUNT(DISTINCT ...)
,
AVG()
, STD()
,
SUM()
, MAX()
and MIN()
) のサポート。
LEFT OUTER JOIN
, RIGHT OUTER JOIN
のサポート。
DELETE
, INSERT
, REPLACE
, UPDATE
は
変更された(影響を受けた)行の数を返します。
サーバ接続時にフラグを設定することにより、代わりに適合したレコード数を返す
ことも可能です。
MySQL
固有の SHOW
コマンドはデータベース、テーブル、イン
デックスについての情報を取出すために使用できます。EXPLAIN
コマン
ドはオプティマイザがどのようにクエリを解析するかを決定するために使用
できます。
ABS
は正しいフィールド
名です。制限は、関数呼び出しに、関数名とそれに続く `(' の間に空白が
許されないことだけです。 See section Is MySQL Picky About Reserved Words?.
MySQL Server
を使用しているユーザを知っています。
MySQL Server
のコンパイル時に変更できます)。インデックスは
CHAR
または VARCHAR
フィールドの先頭部分を使用できます。
MySQL
サーバと接続します。
ODBC
(Open-DataBase-Connectivity) (ソースつき)。全ての ODBC
2.5 関数と他の多く。あなたの MySQL
サーバに接続するために、例え
ば Access を使用できます。 See section MySQL ODBC サポート.
MySQL
サーバー起動時に、選択されたキャラクターセットに
に従って行なわれます。(デフォルトは、スウェーデン語の方法)。
ソース内に新しいソート順序配列を追加することで、こ
れは変更可能です。とても先進的なソートの例を見るには、Czech ソートコード
を見てください。 MySQL Server
は多くの種類のキャラクタセットをサポート
し、コンパイル時や実行時に指定できます。
myisamchk
を含んでいます。これは、テーブル検査、最適化、修復のため
のとても速いユーティリティです。
All of the functionality of myisamchk
is also available through the SQL interface as well.
See section データベース管理.
MySQL
プログラムはオンラインヘルプを得るために、
--help
と -?
オプションで呼び出すことができます。
この節では、``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
は複数の階層と様々な独立モジュールで書かれています。これ
らのモジュールは、それぞれがどのようにテストされているかとともに次にリス
トされています:
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
MySQL
4.0.
MyODBC 2.50
(uses ODBC SDK 2.5) -- Gamma
MyISAM
tables -- Gamma
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.
MyISAM
tables in MySQL
4.0 for faster
insert of many rows.
fcntl()
) を使用するため大きな問題があります。これらの場合では、
MySQL デーモンを --skip-external-locking
フラグつきで動かすべ
きです。知られている問題は、いくつかの Linux システムと NFS マウントされ
たファイルシステム使用時の SunOS です。
MySQL AB
は代金を支払った顧客のために 高サポートを提供しています。しかし
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_LENGTH
と MAX_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以上).
MySQL Server
自身は 2000 年問題(Y2K)に対して何の問題も持っていません:
MySQL Server
は UNIX 時間関数を使用し、2069
年まで日付には何の
問題もありません; 全ての2桁の年は 1970
から 2069
の範囲に
あると見なされます。これは、year
フィールド内に 01
を格納する場
合、MySQL Server
はそれを 2001
として扱うということを意味します。
MySQL
日付関数は一つのファイル `sql/time.cc' に格納
され、2000年安全にとても注意深くコード化されています。
MySQL
3.22 以降のバージョンでは、新しい YEAR
フィールド型は
0
と 1901
から 2155
までの年を1バイトで格納でき、2
桁または4桁で表示できます。
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)
これは、DATE
と DATETIME
型は未来のいかなる日付において
問題のないことををしめします (これら日付は 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 の創始者と主な開発者の会社です。
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 AB
は
MySQL
サーバソースコードの著作権, MySQL
logo の著作権, MySQL 商標権,
このMySQL マニュアルの著作権を所有します。
See section MySQL とは何か.
The MySQL
core values show our dedication to MySQL
and
Open Source
.
我々は MySQL Database Software
を次のようにしたいです。
MySQL AB と MySQL AB の人々は次を行ないます。
オープンソース
哲学を進展させ、オープンソース
コミュニティをサポートする
MySQL ウェブサイト(http://www.mysql.com/)は、MySQL と MySQL AB に ついての最新情報を提供しています。
私たちが最もよく受ける質問は:「`どのようにして無料で配布して採算を取っているので しょうか?」 というものです。それは、このようにしています。
MySQL AB
はサポート、サービス、商用ライセンス及びロイアリティで利益をあげます。
そして、私たちは製品開発とMySQL
の事業を展開するため、これらの収益を利用します。
MySQL AB は創業以来、利益が増えています。 2001年10月、私たちは有数のスカンジナビアの投資家 および数少ないビジネスエンジェルからのベンチャー投資に応じました。 この投資は、私たちのビジネス・モデルを固め、 持続的成長の基盤を構築するために使用されます。
MySQL AB
は、MySQL
データ・ベースの設立者及び主な開発者により管理・運営されます。
開発者は顧客及びその他のユーザの要望・課題を連絡をとり続けるためのサポートを提供することを約束します。
我々の全てのサポートは有能な開発者によって提供されます。実際に複雑な質問は、MySQLサーバー
の主要な著者
である Michael Monty
Widenius が答えます。
See section Support Offered by MySQL AB.
さらなる情報とサポートの依頼は、 http://www.mysql.com/support/ か、 我々の販売員 sales@mysql.com にご連絡ください。
MySQL AB
は MySQL
と関連したトレーニングを世界的に提供します。
我々は、一般公募するコースと、あなたの会社のニーズに合せた特別な社内研修の
両方を提供します。
MySQL トレーニング
はさらに、我々のパートナーである
MySQL 認定 トレーニング・センター
でも受講ができます。
我々のトレーニングの教材は、いくつかのデータベースの実例と資料・説明書、
そしてサンプル・アプリケーションを使用します。
また、教材は MySQL
の最新バージョンを反映するために常時更新されます。
我々の講師は、トレーニングの質と教材の開発を保証するため、常に開発チームにサポートされます。
これは、さらにトレーニング中の質問には必ず回答できることを保証します。
私たちのトレーニング講座に参加することにより、
あなたの目標と MySQL
アプリケーションを実現することができるでしょう。
さらに以下のことができるでしょう:
MySQL 認定試験
の準備になります。
参加予定者あるいはトレーニング・パートナーとして我々のトレーニングに興味を持っている場合、 http://www.mysql.com/training/ のトレーニング課にアクセスするか、あるいは training@mysql.com にメールで連絡をください。
MySQL 認定プログラム
についての詳細な情報は,
http://www.mysql.com/certification/ を参照してください。
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.
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以上).
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.
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.
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.
(訳注: ライセンスの章については、正確さをきすため原文を併記しています。 訳文だけでなく原文に目を通してください。 もし意味の取違いを見つけたなら、takeshi@SoftAgency.co.jp に連絡してください。)
このセクションでは、MySQL
のサポートとライセンス規定について説明します。
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 API
s, 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
.
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:
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.
GNU
getopt
library is covered by the
GNU Lesser General Public License
.
See section GNU Lesser General Public License.
regexp
library) are covered
by a Berkeley-style copyright.
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.
GPL
-style license.
Use of the manual is subject to the following terms:
MySQL AB
is required.
For information about how the MySQL
licenses work in practice,
please refer to section MySQL Licenses.
Also see section MySQL AB Logos and Trademarks.
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.
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:
GPL
code from the MySQL
software and don't want the resulting product to be GPL
, maybe
because you want to build a commercial product or keep the added
non-GPL
code closed source for other reasons. When purchasing
commercial licenses, you are not using the MySQL
software under
GPL
even though it's the same code.
GPL
application that only works with the
MySQL
software and ship it with the MySQL
software. This type
of solution is actually considered to be linking even if it's done over
a network.
MySQL
software without providing
the source code as required under the GPL
license.
MySQL
database even if you don't formally need a commercial license.
Purchasing support directly from MySQL AB
is another good way
of contributing to the development of the MySQL
software, with
immediate advantages for you.
See section Support Offered by MySQL AB.
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.
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:
MySQL
source code under the GPL
with your product.
MySQL
source code bundled with other
programs that are not linked to or dependent on the MySQL
system
for their functionality even if you sell the distribution commercially.
This is called mere aggregation in the GPL
license.
MySQL
system, you can use it for free.
MySQL
servers for your customers.
However, we do encourage people to use ISPs that have MySQL support,
as this will give them the confidence that if they have some problem
with the MySQL
installation, their ISP will in fact have the
resources to solve the problem for them.
Note that even if an ISP does not have a commercial license for
MySQL Server
, they should at least give their customers read
access to the source of the MySQL
installation so that the
customers can verify that it is patched correctly.
MySQL
Database Software in conjunction with a
web server, you do not need a commercial license (so long as it is not
a product you distribute). This is true even if you run a commercial
web server that uses MySQL Server
, because you are not
distributing any part of the MySQL
system. However, in this
case we would like you to purchase MySQL
support because the
MySQL
software is helping your enterprise.
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.)
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 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.
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:
MySQL AB
, are the creator and
owner of the site that displays the MySQL
trademark.
MySQL AB
or to the value of MySQL AB
trademarks. We reserve the right to
revoke the right to use the MySQL AB
trademark.
MySQL
database under GPL
in an
application, your application must be Open Source
and
be able to connect to a MySQL
server.
Contact us at trademark@mysql.com to inquire about special arrangements to fit your needs.
In the following cases you need a written permission from MySQL AB
before using MySQL
logos:
MySQL AB
logo anywhere except on your web site.
MySQL AB
logo except the Conditional Use
logos mentioned previously on web sites or elsewhere.
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
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.
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.
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
.
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.
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 開発ソースツリーからのインストール.
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.
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.
INSERT
s, searching on packed indexes, creation of
FULLTEXT
indexes, as well as COUNT(DISTINCT)
.
InnoDB
storage engine is now offered as a feature of the
standard MySQL server, including full support for transactions
and row-level locking
.
latin1_de
, which corrects the German sorting order,
placing German umlauts in the same order as German telephone books.
TRUNCATE TABLE
(like in Oracle) and IDENTITY
as a
synonym for automatically incremented keys (like in Sybase). Many users will
also be happy to learn that MySQL Server now supports the UNION
statement,
a long-awaited standard SQL feature.
DELETE
and UPDATE
statements.
By adding support for symbolic linking
to MyISAM
on the table
level (and not just the database level as before), as well as by enabling symlink
handling by default on Windows, we hope to show that we take enhancement
requests seriously.
Functions like SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
make it
possible to know how many rows a query would have returned without a
LIMIT
clause.
For the upcoming MySQL Server 4.x releases, expect the following features now still under development:
fail-safe replication
;
already existing in 4.0, the LOAD DATA FROM MASTER
command
will soon automate slave setup. The online backup
will make
it easy to add a new replication slave without taking down
the master, and have a very low performance penalty on
update-heavy systems.
mysqld
parameters (startup options) can soon be set without
taking down the servers.
FULLTEXT
search properties of MySQL Server 4.0 enable the
use of FULLTEXT
indexing of large text masses with both binary and
natural-language searching logic. Users can customise minimal word
length and define their own stop word lists in any human language,
enabling a new set of applications to be built on MySQL Server.
key cache
.
MySQL command help
in the client.
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.
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-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.com や mysql-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-subscribe@lists.mysql.com 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
internals-digest-subscribe@lists.mysql.com internals-digest
internals
リストのダイジェスト版です。
java-subscribe@lists.mysql.com java
java-digest-subscribe@lists.mysql.com java-digest
java
リストのダイジェスト版です。
win32-subscribe@lists.mysql.com win32
win32-digest-subscribe@lists.mysql.com win32-digest
win32
リストのダイジェスト版です。
myodbc-subscribe@lists.mysql.com myodbc
myodbc-digest-subscribe@lists.mysql.com myodbc-digest
myodbc
リストのダイジェスト版です。
mysqlcc-subscribe@lists.mysql.com mysqlcc
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
plusplus-digest-subscribe@lists.mysql.com plusplus-digest
plusplus
リストのダイジェスト版です。
msql-mysql-modules-subscribe@lists.mysql.com 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
ステー
トメント終端)を使用すべきです。
mysqladmin version
の
実行でわかります。mysqladmin
は MySQL のインストール
ディレクトリ配下の `bin' ディレクトリに見つけられます。
uname -a
の実行によってこの情報が得られます。
mysqld
が死んだ場合は、mysqld
がクラッシュしたクエリも
レポートしてください。通常、これはロギングが有効な mysqld
の実行に
よって、見つけられます。See section Using Log Files to Find Cause of Errors in mysqld。
mysqldump --no-data db_name tbl_name1 tbl_name2 ...
からの出力を含めて
ください。これはデータベース内の任意のテーブルについての情報を得るとても
簡単で強力な方法で、我々があなたの状況に一致するものを生成する手助けにな
ります。
SELECT
ステートメントでの速度に関するバグや問題では、
EXPLAIN SELECT ...
の出力と、少なくとも SELECT
ステートメ
ントが与える行の数を常に含めるべきです。あなたの状況について、より多くの
情報を、誰かがあなたを助けられるように、より適切に与えてください! 例え
ば、次はとても良いバグレポートの例です(もちろん mysqlbug
スクリプトで投
稿されてます):
mysql
コマンド行ツール配下での実行例(注意: 出力幅がディスプレイ装
置の80桁を超えるステートメントには、\G
ステートメント終端を使用し
てください):
mysql> SHOW VARIABLES; mysql> SHOW COLUMNS FROM ...\G <output from SHOW COLUMNS> mysql> EXPLAIN SELECT ...\G <output from EXPLAIN> mysql> FLUSH STATUS; mysql> SELECT ...; <A short version of the output from SELECT, including the time taken to run the query> mysql> SHOW STATUS; <output from SHOW STATUS>
mysqladmin variables extended-status processlist
の
出力結果をメールにを含むべきです。 これはあなたのシステムの情報を
提供します!
mysqldump
を使用し
てあなたのテーブルをダンプし、あなたの問題を説明した `README' ファ
イルを作るべきです。
tar
と gzip
または zip
を使用して、ファイルの圧縮アー
カイブを生成し、そのアーカイブを ftp
を使用して
ftp://support.mysql.com/pub/mysql/secret/ に転送してください。それか
ら問題の短い説明を mysql@lists.mysql.com に送ってください。
ftp
を使用して ftp://support.mysql.com/pub/mysql/secret/ にデー
タを転送することができます。データが本当に最高機密で我々にさえ見せたくな
い場合は、先に進んで、他の変数名等を使用してサンプルを作ってみてください。
しかしこれは最後の選択と思ってください。
mysqld
デーモン開始時に使用したオプションと
MySQL クライアントプログラム実行に使用したオプションを示してく
ださい。 mysqld
, mysql
または configure
スクリプト
へのオプションはしばしば回答へのキーになり、とても関連しています! とに
かくそれらを含めるというのは悪い考えではありません! Perl や PHP などの
モジュールを使用している場合、それらのバージョン番号も含めてください。
mysqlaccess
の出力、
mysqladmin reload
の出力、接続しようとした時に得られた全てのエラー
メッセージを含めてください! 権限をテストする時、まず mysqlaccess
を実行すべきです。その後、mysqladmin reload version
を実行し、最
後に問題が発生するプログラムでの接続を試みるべきです。mysqlaccess
はMySQL インストールディレクトリ配下の `bin' ディレクトリ
に見つけられます。
parse error
が発生する場合、構文を厳密にチェックしてください! 何
が間違っているのかを見つけられなければ、多分、使用しているクエリを
MySQL Server の現在のバージョンがサポートしていないということです。現
在のバージョンを使用していて、http://www.mysql.com/documentation/manual.php のマ
ニュアルがあなたの使用しているクエリ構文をカバーしていない場合は、これは
MySQL Server があなたのクエリをサポートしていないという意味です。この
場合、あなたの選択は、その構文をあなた自身で実装することか、
mysql-support@mysql.com に email でこれを実装するように申し込むこ
とです!
マニュアルがあなたの使用している構文をカバーしているのにMySQL
の古いバージョンを使用している場合、文法が実装された時期について
MySQL Server の変更履歴をチェックすべきです。See section MySQL Change History。この場合、よ
り新しいバージョンの MySQL へのアップグレードを選択できます。
myisamchk
か
CHECK TABLE
/REPAIR TABLE
文で検査し、修復を試みるべきです
See section データベース管理.
mysqld
は 更新の最中に kill されない限りは
テーブルを絶対に破壊しません! もしなぜ mysqld
が死ぬのか
見つけた場合は、我々があなたに問題解決のための修正を提供することが、
はるかに簡単になります!
See section How to Determine What Is Causing Problems
もしあなたがサポート顧客なら、より高い優先度で取り扱われるように、バグレポー トを mysql-support@mysql.com と、そして同様に、他の誰かが問題を経 験済み(そして、もしかしたら解決済み)かどうかを調べるために、適切なメーリン グリストにもクロスポストしてください。
MyODBC のバグ報告上の情報については、section MyODBC での問題をどのように報告すべきか? を参照 してください。
いくつかの一般的な問題の解決法のために → section Problems and Common Errors.
回答があなたに個人的に送られて、メーリングリストに送られていない時、回答 を要約し、あなたの問題の解決の手助けになった返事の恩恵を他の人にも与える ために、その要約をメーリングリストに送信することは、良いエチケットです!
あなたの回答が広く関心を持たれると考えられる場合、尋ねた人に個人的に直接 返事をする代わりに、メーリングリストに投稿したいと思うでしょう。オリジナ ルの投稿者以外の人もそれから恩恵を受けられるように十分一般的に回答を作成 することを試みてください。メーリングリストに投稿する場合は、あなたの回答 が以前の回答と重複していないか確認して下さい。
あなた返事の中で、質問の本質部分の要約を試みてください。質問全体を引用す ることを義務と感じないで下さい。
HTML モードを ON にしたブラウザからメールメッセージを投稿しないでくださ い! 多くのユーザはブラウザでメールを読んでいません!
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:
#mysql
Primarily MySQL questions but other database and SQL questions welcome.
#mysqlphp
Questions about MySQL+PHP, a popular combo.
#mysql
MySQL questions.
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 がどのように 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.
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.
If you start mysqld
with the --ansi
option, the following
behaviour of MySQL Server changes:
||
is string concatenation instead of OR
.
REAL
will be a synonym for FLOAT
instead of a synonym for
DOUBLE
.
SERIALIZABLE
.
See section SET TRANSACTION
構文.
GROUP BY
that is not in the
field list.
This is the same as using
--sql-mode=REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,
IGNORE_SPACE,SERIALIZE,ONLY_FULL_GROUP_BY
.
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 拡張を以下に示します:
MEDIUMINT
, SET
, ENUM
そして様々な
BLOB
と TEXT
型。
AUTO_INCREMENT
, BINARY
, NULL
, UNSIGNED
そして
ZEROFILL
。
BINARY
属性であなたのフィールドを宣言すべきです。これは、MySQL
サーバホストの上で使用される ASCII 順に従って比較が実行されるようになり
ます。
db_name.tbl_name
構文を使用して違うデータベースのテーブルにアクセスできます。
いくつかのSQLサーバーは同様の機能を提供しますが、これを User space
でコールします。
MySQL Server は以下のようなテーブルスペースをサポートしません:
create table ralph.my_table...IN my_tablespace
.
LIKE
が許されます。
SELECT
ステートメント内の INTO OUTFILE
と
STRAIGHT_JOIN
の使用。See section SELECT
構文.
SQL_SMALL_RESULT
option in a SELECT
statement.
EXPLAIN SELECT
。
CREATE TABLE
ス
テートメント内の INDEX
または KEY
の使用。
See section CREATE TABLE
構文.
CREATE TABLE
での TEMPORARY
か IF NOT EXISTS
の使用。
list
要素が一つ以上の COUNT(DISTINCT list)
の使用。
ALTER TABLE
ステートメント内の CHANGE col_name
, DROP col_name
,
DROP INDEX
, IGNORE
, RENAME
の使用。
See section ALTER TABLE
構文.
RENAME TABLE
の使用。See section RENAME TABLE
構文。
ALTER TABLE
ステートメント内の複数の ADD
, ALTER
,
DROP
, CHANGE
節の使用。
IF EXISTS
付きの DROP TABLE
の使用。
DROP TABLE
で破棄できる
DELETE
ステートメントの LIMIT
節。
INSERT
と REPLACE
ステートメントの DELAYED
節。
INSERT
, REPLACE
, DELETE
, UPDATE
ステートメント
の LOW_PRIORITY
節。
LOAD DATA INFILE
の使用。多くの場合、この構文は ORACLE の
LOAD DATA INFILE
と互換があります。See section LOAD DATA INFILE
構文.
ANALYZE TABLE
, CHECK TABLE
, OPTIMIZE TABLE
, and
REPAIR TABLE
ステートメント。
SHOW
ステートメント。
See section SHOW
構文.
SET
ステートメント。 See section SET
構文.
GROUP BY
部に全てのフィールドを持つ必要はありません。
This gives better performance for some very specific, but quite normal
queries.
See section Functions for Use with GROUP BY
Clauses.
GROUP BY
とともに ASC
と DESC
を記述できます。
||
と &&
演算子を、C プログラミング言語
のように、論理和と論理積を意味すると理解します。MySQL では
||
と OR
、&&
と AND
は同義語です。この良い構
文のため、MySQL Server は ANSI SQL の文字列結合演算子 ||
をサポー
トしません。CONCAT()
を代わりに使用してください。CONCAT()
は任意の数の引数を使用できるので、||
演算子の使用を
MySQL Server に変換するのは簡単です。
CREATE DATABASE
または DROP DATABASE
.
See section CREATE DATABASE
構文.
MOD()
と同義の %
。 N % M
は MOD(N,M)
と等価です。
%
は C プログラマーと PostgreSQL との互換のためにサポートされます。
=
, <>
, <=
,<
, >=
,>
,
<<
, >>
, <=>
, AND
, OR
, LIKE
演算子は、SELECT
文中で、FROM
の左側のフィールドの比較に
使用されます。
例えば:
mysql> SELECT col1=1 AND col2=2 FROM tbl_name;
LAST_INSERT_ID()
関数。
See section mysql_insert_id()
.
REGEXP
と NOT REGEXP
正規表現演算子
CONCAT()
または CHAR()
。
MySQL Server では、これらの関数は任意の数の引数を取ることができます。
BIT_COUNT()
, CASE
, ELT()
,
FROM_DAYS()
, FORMAT()
, IF()
, PASSWORD()
,
ENCRYPT()
, md5()
, ENCODE()
, DECODE()
,
PERIOD_ADD()
, PERIOD_DIFF()
, TO_DAYS()
,
WEEKDAY()
関数。
TRIM()
to trim substrings. ANSI SQL only supports removal
of single characters.
GROUP BY
関数 STD()
, BIT_OR()
そして BIT_AND()
。
DELETE
+ INSERT
の代わりの REPLACE
の使用。
See section REPLACE
構文.
FLUSH
, RESET
, DO
構文。
:=
でステートメント内での変数の設定が可能:
SELECT @a:=SUM(total),@b=COUNT(*),@a/@b AS avg FROM test_table; SELECT @t1:=(@t2:=1)+@t3:=4,@t1,@t2,@t3;
我々は MySQL Server を ANSI SQL 標準と ODBC SQL 標準に従うように試みてい ますが、いくつかのケースで MySQL Server には何らかの違いがあります:
--
は空白が続く場合だけコメントになります。
VARCHAR
フィールドでは、値が格納される時に末尾の空白が削除されます。
See section Known Errors and Design Deficiencies in MySQL。
CHAR
フィールドは黙って VARCHAR
フィール
ドに変更されます。See section 暗黙のフィールド定義変更。
REVOKE
を発行する必
要があります。See section GRANT
と REVOKE
構文.
NULL AND FALSE
は FALSE
ではなく NULL
と評価されます。
このケースで、多くの余計な条件を評価する必要があることは良いことではないと、
我々は考えているからです。
次の機能が MySQL Server の現在のバージョンにはありません。新しい拡張の 優先度については、次を参考にしてください http://www.mysql.com/doc/en/TODO.html. これはこのマニュアル中の TODO リストの最新バージョンです。 See section MySQL and The Future (The TODO).
SELECT
s
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
.
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 の機能をどのように使用するの でしょう? そして、トランザクション的パラダイムでこれらの機能をどのように 比較するのでしょう?
COMMIT
の代わりに ROLLBACK
の呼び出しに依存しているなら、
トランザクションはより便利になるでしょう。
おまけに、トランザクションは完了できなかった更新や不整合を起こした
データが、確実にデータベースに登録されないようにできます。
そのサーバーには、自動的な rollback をする機会が与えられ、
あなたのデータは守られるでしょう。
MySQL Server はほとんどの場合、更新前の簡単なチェックを含ませることができたり、
あるいはデータベースの矛盾を検査して自動修復や警告の表示を行ったりする
簡単なスクリプトを実行することができるような、
ポテンシャルをあなたに提供します。
MySQL ログの使用や外部へのログの追加を行ったりする事で、
通常、データに不整合のおきたテーブルを完全に修復できることに注意してください。
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.
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:
LOCK TABLES
, and you don't need cursors when you can update
records on the fly.
ROLLBACK
, you can use the following strategy:
LOCK TABLES ...
to lock all the tables you want to access.
UNLOCK TABLES
to release your locks.
ROLLBACK
s, although not always. The only situation
this solution doesn't handle is when someone kills the threads in the
middle of an update. In this case, all locks will be released but some
of the updates may not have been executed.
WHERE
clause in the UPDATE
statement. If the record wasn't
updated, we give the client a message: "Some of the data you have changed
has been changed by another user." Then we show the old row versus the new
row in a window, so the user can decide which version of the customer record
he should use.
This gives us something that is similar to column locking but is actually
even better because we only update some of the columns, using values that
are relative to their current values. This means that typical UPDATE
statements look something like these:
UPDATE tablename SET pay_back=pay_back+'relative change'; UPDATE customer SET customer_date='current_date', address='new address', phone='new phone', money_he_owes_us=money_he_owes_us+'new_money' WHERE customer_id=id AND address='old address' AND phone='old phone';As you can see, this is very efficient and works even if another client has changed the values in the
pay_back
or money_he_owes_us
columns.
ROLLBACK
and/or LOCK
TABLES
for the purpose of managing unique identifiers for some tables.
This can be handled much more efficiently by using an
AUTO_INCREMENT
column and either the SQL function
LAST_INSERT_ID()
or the C API function mysql_insert_id()
.
See section mysql_insert_id()
.
You can generally code around row-level locking. Some situations really
need it, but they are very few. InnoDB
tables support row-level
locking. With MyISAM, you can use a flag column in the table and do
something like the following:
UPDATE tbl_name SET row_flag=1 WHERE id=ID;MySQL returns 1 for the number of affected rows if the row was found and
row_flag
wasn't already 1 in the original row.
You can think of it as though MySQL Server changed the preceding query to:
UPDATE tbl_name SET row_flag=1 WHERE id=ID AND row_flag <> 1;
ストアドプロシジャは、サーバ内でコンパイルでき格納できる 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
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'.
LOCK TABLE
on multiple tables
and then in the same connection doing a DROP TABLE
on one of
them while another thread is trying to lock the table. One can however
do a KILL
on any of the involved threads to resolve this.
Fixed in 4.0.12.
SELECT MAX(key_column) FROM t1,t2,t3...
where one of the tables are
empty doesn't return NULL
but instead the maximum value for the
column. Fixed in 4.0.11.
The following problems are known and have a high priority to get fixed:
ANALYZE TABLE
on a BDB table may in some case make the table
unusable until one has restarted mysqld
. When this happens you will
see errors like the following in the MySQL error file:
001207 22:07:56 bdb: log_flush: LSN past current end-of-log
ALTER TABLE
on a BDB
table on which you are
running multi-statement transactions until all those transactions complete.
(The transaction will probably be ignored.)
ANALYZE TABLE
, OPTIMIZE TABLE
, and REPAIR TABLE
may
cause problems on tables for which you are using INSERT DELAYED
.
LOCK TABLE ...
and FLUSH TABLES ...
doesn't
guarantee that there isn't a half-finished transaction in progress on the
table.
mysql
client on the
database if you are not using the -A
option or if you are using
rehash
. This is especially notable when you have a big table
cache.
The following problems are known and will be fixed in due time:
RPAD
function, or any other string function that ends
up adding blanks to the right, in a query that has to use temporary
table to be resolved, then all resulting strings will be RTRIM'ed. This
is an example of the query:
SELECT RPAD(t1.field1, 50, ' ') AS f2, RPAD(t2.field2, 50, '
') AS f1 FROM table1 as t1 LEFT JOIN table2 AS t2 ON
t1.record=t2.joinID ORDER BY t2.record;
Final result of this bug is that use will not be able to get blanks on
the right side of the resulting field.
The above behaviour exists in all versions of MySQL.
The reason for this is due to the fact that HEAP tables, which are used
first for temporary tables, are not capable of handling VARCHAR columns.
This behaviour will be fixed in one of 4.1 releases.
SET CHARACTER SET
, one can't use translated
characters in database, table, and column names.
_
or %
with ESCAPE
in LIKE
... ESCAPE
.
DECIMAL
column with a number stored in different
formats (+01.00, 1.00, 01.00), GROUP BY
may regard each value
as a different value.
DELETE FROM merge_table
used without a WHERE
will only clear the mapping for the table, not delete everything in the
mapped tables.
BLOB
values can't ``reliably'' be used in GROUP BY
or
ORDER BY
or DISTINCT
.
これらの場合、 BLOB
の比較の際には最初の max_sort_length
バイト
(デフォルト1024)だけが使用されます。
これは mysqld
の -O max_sort_length
オプションで変更可能です。
A workaround for most cases is to use a substring:
SELECT DISTINCT LEFT(blob,2048) FROM tbl_name
.
BIGINT
or DOUBLE
(both are
normally 64 bits long). It depends on the function which precision one
gets. The general rule is that bit functions are done with BIGINT
precision, IF
, and ELT()
with BIGINT
or DOUBLE
precision and the rest with DOUBLE
precision. One should try to
avoid using unsigned long long values if they resolve to be bigger than
63 bits (9223372036854775807) for anything else than bit fields!
MySQL Server 4.0 has better BIGINT
handling than 3.23.
BLOB
と TEXT
はのぞいて、は、
検索されるときに最後についているスペースを自動で取り除きます。
CHAR
型ではこれは OK で、この特徴は ANSI SQL92 に従っていると見なされるでしょう。
MySQL Server のバグは、 VARCHAR
でも同様に行ってしまうことです。
ENUM
and SET
columns in one table.
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.
safe_mysqld
redirects all messages from mysqld
to the
mysqld
log. One problem with this is that if you execute
mysqladmin refresh
to close and reopen the log,
stdout
and stderr
are still redirected to the old log.
If you use --log
extensively, you should edit safe_mysqld
to
log to `'hostname'.err' instead of `'hostname'.log' so you can
easily reclaim the space for the old log by deleting the old one and
executing mysqladmin refresh
.
UPDATE
statement, columns are updated from left to right. If
you refer to an updated column, you will get the updated value instead of the
original value. For example:
mysql> UPDATE tbl_name SET KEY=KEY+1,KEY=KEY+1;This will update
KEY
with 2
instead of with 1
.
mysql> SELECT * FROM temporary_table, temporary_table AS t2;
RENAME
doesn't work with TEMPORARY
tables or tables used in a
MERGE
table.
DISTINCT
differently if you are using
'hidden' columns in a join or not. In a join, hidden columns are
counted as part of the result (even if they are not shown) while in
normal queries hidden columns don't participate in the DISTINCT
comparison. We will probably change this in the future to never compare
the hidden columns when executing DISTINCT
.
An example of this is:
SELECT DISTINCT mp3id FROM band_downloads WHERE userid = 9 ORDER BY id DESC;and
SELECT DISTINCT band_downloads.mp3id FROM band_downloads,band_mp3 WHERE band_downloads.userid = 9 AND band_mp3.id = band_downloads.mp3id ORDER BY band_downloads.id DESC;In the second case you may in MySQL Server 3.23.x get two identical rows in the result set (because the hidden
id
column may differ).
Note that this happens only for queries where you don't have the
ORDER BY columns in the result, something that you are not allowed
to do in ANSI SQL.
rollback
data, some things
behave a little differently in MySQL Server than in other SQL servers.
This is just to ensure that MySQL Server never needs to do a rollback
for a SQL command. This may be a little awkward at times as column
values must be checked in the application, but this will actually give
you a nice speed increase as it allows MySQL Server to do some
optimisations that otherwise would be very hard to do.
If you set a column to an incorrect value, MySQL Server will, instead of
doing a rollback, store the best possible value
in the column:
NULL
into a column that doesn't take
NULL
values, MySQL Server will store 0 or ''
(empty
string) in it instead. (This behaviour can, however, be changed with the
-DDONT_USE_DEFAULT_FIELDS compile option.)
DATE
and
DATETIME
columns (like 2000-02-31 or 2000-02-00). The idea is
that it's not the SQL server job to validate date. If MySQL can store a
date and retrieve exactly the same date, then MySQL will store the
date. If the date is totally wrong (outside the server's ability to store
it), then the special date value 0000-00-00 will be stored in the column.
ENUM
column to an unsupported value, it will be set to
the error value empty string
, with numeric value 0.
SET
column to an unsupported value, the value will
be ignored.
PROCEDURE
on a query that returns an empty set,
in some cases the PROCEDURE
will not transform the columns.
MERGE
doesn't check if the underlying
tables are of compatible types.
NaN
, -Inf
, and Inf
values in double. Using these will cause problems when trying to export
and import data. We should as an intermediate solution change NaN
to
NULL
(if possible) and -Inf
and Inf
to the
minimum respective maximum possible double
value.
LIMIT
on negative numbers are treated as big positive numbers.
ALTER TABLE
to first add a UNIQUE
index to a
table used in a MERGE
table and then use ALTER TABLE
to
add a normal index on the MERGE
table, the key order will be
different for the tables if there was an old key that was not unique in the
table. This is because ALTER TABLE
puts UNIQUE
keys before
normal keys to be able to detect duplicate keys as early as possible.
The following are known bugs in earlier versions of MySQL:
DROP TABLE
on a table that is
one among many tables that is locked with LOCK TABLES
.
LOCK table
with WRITE
.
FLUSH TABLES
.
UPDATE
that updated a key with
a WHERE
on the same key may have failed because the key was used to
search for records and the same row may have been found multiple times:
UPDATE tbl_name SET KEY=KEY+1 WHERE KEY > 100;A workaround is to use:
mysql> UPDATE tbl_name SET KEY=KEY+1 WHERE KEY+0 > 100;This will work because MySQL Server will not use an index on expressions in the
WHERE
clause.
For platform-specific bugs, see the sections about compiling and porting.
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.
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
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).
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).
SHOW COLUMNS FROM table_name
(used by mysql
client to allow
expansions of column names) should not open the table, only the
definition file. This will require less memory and be much faster.
ROLLUP
and CUBE
OLAP (Online Analytical Processing) grouping
options for data warehousing applications.
DELETE
on MyISAM
tables to use the record cache.
To do this, we need to update the threads record cache when we update
the `.MYD' file.
SET CHARACTER SET
we should translate the whole query
at once and not only strings. This will enable users to use the translated
characters in database, table, and column names.
RENAME TABLE
on a table used in an active
MERGE
table possibly corrupting the table.
RENAME DATABASE
. To make this safe for all storage engines,
it should work as follows:
RENAME
command.
VARCHAR
support (there is already support for this in
MyISAM
).
BIT
型を 1 bit 取るように最適化 (今 BIT
は一文字とります)
HEAP
) tables:
INSERT ... SELECT
to optionally use concurrent inserts.
SELECT MIN(column)
... GROUP BY
.
long_query_time
with a granularity
in microseconds.
myisampack
code into the server.
INSERT/DELETE/UPDATE
so that we
can gracefully recover if the index file gets full.
ALTER TABLE
を
実行した場合、一時テーブルをこの disk に作成するようにする
DATE/DATETIME
type that handles time zone information
properly so that dealing with dates in different time zones is easier.
MyISAM
)
without threads.
INSERT SQL_CONCURRENT
and mysqld --concurrent-insert
to do
a concurrent insert at the end of the file if the file is read-locked.
lockd
works with modern Linux kernels; if not, we have
to fix lockd
! To test this, start mysqld
with
--enable-locking
and run the different fork* test suits. They shouldn't
give any errors if lockd
works.
LIMIT
, like in LIMIT @a,@b
.
UPDATE
statements. For example:
UPDATE TABLE foo SET @a=a+b,a=@a, b=@a+c
.
GROUP BY
, as in the following example:
SELECT id, @a:=COUNT(*), SUM(sum_col)/@a FROM table_name GROUP BY id
.
DEFAULT
values to columns. Give an error when using
an INSERT
that doesn't contain a column that doesn't have a
DEFAULT
.
mysql_query()
commands in a row
without reading results or give a nice error message when one does this.
ctime()
が動かないか検証。
TIMESTAMP
と AUTO_INCREMENT
フィールドを更新しないように、
IMAGE
オプションを LOAD DATA INFILE
に追加。
LOAD DATE INFILE ... UPDATE
syntax.
LOAD DATA INFILE ... REPLACE INTO
now.
LOAD DATA INFILE
understand syntax like:
LOAD DATA INFILE 'file_name.txt' INTO TABLE tbl_name TEXT_FIELDS (text_field1, text_field2, text_field3) SET table_field1=CONCAT(text_field1, text_field2), table_field3=23 IGNORE text_field3This can be used to skip over extra columns in the text file, or update columns based on expressions of the read data.
LOAD DATA INFILE 'file_name' INTO TABLE 'table_name' ERRORS TO err_table_name
.
This would cause any errors and warnings to be logged into the
err_table_name
table. That table would have a structure like:
line_number - line number in datafile error_message - the error/warning message and maybe data_line - the line from the datafile
mysql
から自動的に Netscape に出力
LOCK DATABASES
. (いろいろなオプション付きで)
t1 JOIN t2 ON ...
と t1 JOIN t2 USING ...
の使用の追加。
現在、 LEFT JOIN
のみが使用できます。
show status
. Records reads and
updates. Selects on 1 table and selects with joins. Mean number of
tables in select. Number of ORDER BY
and GROUP BY
queries.
mysql
in the middle of a query, you should open
another connection and kill the old running query.
Alternatively, an attempt should be made to detect this in the server.
SHOW INFO FROM tbl_name
for basic table information
should be implemented.
SELECT a FROM crash_me LEFT JOIN crash_me2 USING (a)
; in this
case a
is assumed to come from the crash_me
table.
CONNECT BY PRIOR ...
to search hierarchy structures.
mysqladmin copy database new-database
; requires COPY
command to be added to mysqld
.
SHOW HOSTS
for printing information about the hostname cache.
DELETE
and REPLACE
options to the UPDATE
statement
(this will delete rows when one gets a duplicate key error while updating).
DATETIME
to store fractions of seconds.
NULL
for calculated columns.
Item_copy_string
on numerical values to avoid
number->string->number conversion in case of:
SELECT COUNT(*)*(id+0) FROM table_name GROUP BY id
ALTER TABLE
doesn't abort clients
that execute INSERT DELAYED
.
UPDATE
clause,
they contain the old values from before the update started.
pread()
/pwrite()
on Windows to enable
concurrent inserts.
SUM(DISTINCT)
.
ANY()
, EVERY()
, and SOME()
group functions. In
ANSI SQL these work only on boolean columns, but we can extend these to
work on any columns/expressions by applying: value == 0 -> FALSE and
value <> 0 -> TRUE.
MAX(column)
is the same as the column type:
mysql> CREATE TABLE t1 (a DATE); mysql> INSERT INTO t1 VALUES (NOW()); mysql> CREATE TABLE t2 SELECT MAX(a) FROM t1; mysql> SHOW COLUMNS FROM t2;
UPDATE
the row
if it exists and INSERT
a new row if the row didn't exist
(like REPLACE
works with INSERT
/ DELETE
).
get_changed_tables(timeout,table1,table2,...)
.
SET TIMESTAMP=#;
.
MyISAM
tables, probably after
the implementation of stored procedures with triggers.
MINUS
, INTERSECT
, and FULL OUTER JOIN
.
(Currently UNION
[in 4.0] and LEFT OUTER JOIN
are supported.)
SQL_OPTION MAX_SELECT_TIME=#
to put a time limit on a query.
LIMIT
to allow retrieval of data from the end of a result set.
safe_mysqld
: according to FSSTND (which
Debian tries to follow) PID files should go into `/var/run/<progname>.pid'
and log files into `/var/log'. It would be nice if you could put the
"DATADIR" in the first declaration of "pidfile" and "log", so the
placement of these files can be changed with a single statement.
zlib()
for gzip
-ed files to LOAD DATA INFILE
.
BLOB
columns (partly solved now).
AUTO_INCREMENT
value when one sets a column to 0.
Use NULL
instead.
JOIN
with parentheses.
GET_LOCK
. When doing this,
one must also handle the possible deadlocks this change will introduce.
Time is given according to amount of work, not real time.
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.
mSQL
mSQL
should be quicker at:
INSERT
operations into very simple tables with few columns and keys.
CREATE TABLE
and DROP TABLE
.
SELECT
on something that isn't an index. (A table scan is very
easy.)
mSQL
や多くの他の SQL 実装よりとても速いです:
SELECT
operations.
VARCHAR
上にインデックスを持つことができます。
SELECT
with many expressions.
SELECT
on large tables.
mSQL
では、全ての他の接続は、最初のもの - クエリが長いか短いかに
関わらず - が実行され、終わるまで待つ必要があります。その後次の接続が与
えられ、他の全ては再び待ちます。
mSQL
can become pathologically slow if you change the order of
tables in a SELECT
. In the benchmark suite, a time more than
15,000 times slower than MySQL Server was seen. This is due to mSQL
's
lack of a join optimiser to order tables in the optimal order.
However, if you put the tables in exactly the right order in
mSQL
2 and the WHERE
is simple and uses index columns,
the join will be relatively fast!
See section The MySQL Benchmark Suite.
ORDER BY
and GROUP BY
.
DISTINCT
.
TEXT
または BLOB
フィールドの使用。
GROUP BY
and HAVING
.
mSQL
does not support GROUP BY
at all.
MySQL Server supports a full GROUP BY
with both HAVING
and
the following functions: COUNT()
, AVG()
, MIN()
,
MAX()
, SUM()
, and STD()
. COUNT(*)
is
optimised to return very quickly if the SELECT
retrieves from
one table, no other columns are retrieved, and there is no
WHERE
clause. MIN()
and MAX()
may take string
arguments.
INSERT
and UPDATE
with calculations.
MySQL Server can do calculations in an INSERT
or UPDATE
.
For example:
mysql> UPDATE SET x=x*10+y WHERE x<20;
SELECT
with functions.
MySQL Server has many functions (too many to list here; see section SELECT
と WHERE
節で使用する関数).
MEDIUMINT
です。10,000,000 レコードを持つ場合、1レコードあたり1バイトの節約でもと
ても重要です。
mSQL2
は4つの型(char,text,int,real)しかないので、小さなテーブルを
得るのは難しいです。
mSQL
安定性の経験がありません。そのため、我々はこれにつ
いては何も言えません。
mSQL
よりも柔軟なライセンスを持っています。そして mSQL
よ
りもより安いです。少なくとも、あなたが使用を選択した製品全てに、ライセン
スまたは email サポートへの支払いを考慮することを覚えていて下さい。
MySQL を含めた製品を売る場合、もちろんこのライセンスの獲得が要求
されます。
mSQL
と同じ perl インタフェースと、いくつかの追
加機能を持ちます。
mSQL
has a JDBC driver, but we have too little
experience with it to compare.
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 への変換は通常、数分使用するだけです。
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:
msql2mysql
をソースに実行します。バイナリプログラム
replace
が必要です。これは MySQL で配布されます。
MySQL と mSQL
間の C API の違い:
MYSQL
構造体を接続型として使用します (mSQL
は
int
を使用します)。
mysql_connect()
は MYSQL
構造体へのポインタをパラメータとして使用します。そ
れをグローバルに定義したり、その獲得に malloc()
を使用するのは簡単です。
mysql_connect()
also takes two parameters for
specifying the user and password. You may set these to
NULL, NULL
for default use.
mysql_error()
は MYSQL
構造体をパラメータとして使用します。古いコードを移
行する場合、あなたの古い msql_error()
コードへパラメータを追加してください。
mSQL
はテキストのエラーメッセージしか返しません。
mSQL
and MySQL Client/Server Communications Protocols DifferThere 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:
mSQL
2.0 SQL Syntax Differs from MySQLColumn types
MySQL Server
CREATE TABLE
構文):
ENUM
type for one of a set of strings.
SET
type for many of a set of strings.
BIGINT
type for 64-bit integers.
UNSIGNED
option for integer and floating-point columns.
ZEROFILL
option for integer columns.
AUTO_INCREMENT
option for integer columns that are a
PRIMARY KEY
.
See section mysql_insert_id()
.
DEFAULT
value for all columns.
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
CREATE TABLE
statement.
mSQL
CREATE INDEX
statements.
To Insert a Unique Identifier into a Table
MySQL Server
AUTO_INCREMENT
as a column type
specifier.
See section mysql_insert_id()
.
mSQL
SEQUENCE
on a table and select the _seq
column.
To Obtain a Unique Identifier for a Row
MySQL Server
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
_rowid
column. Observe that _rowid
may change over time
depending on many factors.
To Get the Time a Column Was Last Modified
MySQL Server
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
_timestamp
column.
NULL
Value Comparisons
MySQL Server
NULL
is always NULL
.
mSQL
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
BINARY
attribute, which causes comparisons to be done according to the
ASCII order used on the MySQL server host.
mSQL
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
CLIKE
.
Handling of Trailing Spaces
MySQL Server
CHAR
and VARCHAR
columns. Use a TEXT
column if this behaviour is not desired.
mSQL
WHERE
Clauses
MySQL Server
AND
is evaluated
before OR
). To get mSQL
behaviour in MySQL Server, use
parentheses (as shown in an example later in this section).
mSQL
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
mSQL
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
.
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.
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:
MySQL
Server is generally much faster than PostgreSQL. MySQL
4.0.1 also has a query cache that can boost up the query speed for
mostly-read-only sites many times.
Cygwin
emulation. We have
heard that PostgreSQL is not yet that stable on Windows but we haven't
been able to verify this ourselves.
VACUUM
once in a while to reclaim space from UPDATE
and DELETE
commands and to perform statistics analyses that are critical to get
good performance with PostgreSQL. VACUUM
is also needed after
adding a lot of new rows to a table. On a busy system with lots of changes,
VACUUM
must be run very frequently, in the worst cases even
many times a day. During the VACUUM
run, which may take hours
if the database is big, the database is, from a production standpoint,
practically dead. Please note: in PostgreSQL version 7.2, basic vacuuming
no longer locks tables, thus allowing normal user access during the vacuum.
A new VACUUM FULL
command does old-style vacuum by locking the table
and shrinking the on-disk copy of the table.
crash-me
(http://www.mysql.com/information/crash-me.php), as well
as a benchmark suite. The test system is actively updated with code to
test each new feature and almost all reproduceable bugs that have come to
our attention. We test MySQL Server with these on a lot of platforms before
every release. These tests are more sophisticated than anything we have
seen from PostgreSQL, and they ensure that the MySQL Server is kept to a high
standard.
PostgreSQL
.
ALTER TABLE
.
HEAP
tables or disk based MyISAM
. See section MySQL テーブル型.
InnoDB
, and BerkeleyDB
. Because every
transaction engine performs differently under different conditions, this
gives the application writer more options to find an optimal solution for
his or her setup, if need be per individual table. See section MySQL テーブル型.
MERGE
tables gives you a unique way to instantly make a view over
a set of identical tables and use these as one. This is perfect for
systems where you have log files that you order, for example, by month.
See section MERGE
Tables (3.23.25以上).
myisampack
, MySQL の圧縮された読み込み専用テーブルジェネレータ.
INSERT
,
SELECT
, and UPDATE/DELETE
grants per user on a database or
a table, MySQL Server allows you to define a full set of different
privileges on the database, table, and column level. MySQL Server also
allows you to specify the privilege on host and user combinations.
See section GRANT
と REVOKE
構文.
InnoDB
) are implemented as files
(one table per file), which makes it really easy to back up, move, delete,
and even symlink databases and tables, even when the server is down.
MyISAM
tables (the most common
MySQL table type). A repair tool is only needed when a physical corruption
of a datafile happens, usually from a hardware failure. It allows a
majority of the data to be recovered.
Drawbacks with MySQL Server compared to PostgreSQL:
MyISAM
tables, is
in many cases faster than page locks, row locks, or versioning. The
drawback, however, is that if one doesn't take into account how table
locks work, a single long-running query can block a table for updates
for a long time. This can usually be avoided when designing the
application. If not, one can always switch the trouble table to use one
of the transactional table types. See section テーブル・ロッキングの問題.
UPDATE
and in MySQL Server 4.1 with subqueries.
In MySQL Server 4.0 one can use multi-table deletes to delete from many
tables at the same time. See section DELETE
構文.
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:
VACUUM
makes PostgreSQL hard to use in a 24/7 environment.
INSERT
, DELETE
, and UPDATE
.
For a complete list of drawbacks, you should also examine the first table in this section.
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 SELECT
s. 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.
Open Source
company like us to verify the benchmarks,
or even check how the benchmarks were really done. The tool is not even
a true benchmark tool, but an application/setup testing tool. To refer
to this as a ``standard'' benchmark tool is to stretch the truth a long way.
VACUUM
before the test) and tuned the startup for the tests,
something they hadn't done for any of the other databases involved. They
say ``This process optimises indexes and frees up disk space a bit. The
optimised indexes boost performance by some margin.'' Our benchmarks
clearly indicate that the difference in running a lot of selects on a
database with and without VACUUM
can easily differ by a factor
of 10.
SELECT
s and JOIN
s (especially
after a VACUUM
), but doesn't perform as well on INSERT
s or
UPDATE
s. The benchmarks seem to indicate that only SELECT
s
were done (or very few updates). This could easily explain the good results
for PostgreSQL in this test. The bad results for MySQL will be obvious a
bit down in this document.
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 を得、インストールするのかをのべます:
(訳注:もし RedHat 以外の Linux を使用しており、.rpm を、自分が使用している パッケージ管理システムの管理下におきたい場合、 alien : http://kitenet.net/programs/alien/ というツールを 使用します。これは RPM(Debian, Slackware) を自分が使用しているパッケージの形式に変換してくれます。)
RPM を使用して MySQL をインストールすることを推奨します。
MySQL RPM は SuSE Linux 7.3 で作成していますが、
他の rpm
と glibc
をサポートしている Linux でも動作するでしょう。
RPM file での問題, 例えば, ``Sorry, the host 'xxxx' could not be looked up
''
に遭遇した場合には → section Linux Notes for Binary Distributions.
以下が使用するであろう RPM files です:
MySQL-server-VERSION.i386.rpm
MySQL サーバー。
ただ単に他のマシン上で走っている MySQL サーバーに接続するだけなら、
これは不要でしょう。
Please note,
that this package was called MySQL-VERSION.i386.rpm
before
MySQL 4.0.10.
MySQL-client-VERSION.i386.rpm
MySQL クライアント標準プログラム。
このパッケージはほとんどの場合インストールすることになるでしょう。
MySQL-bench-VERSION.i386.rpm
Tests and benchmarks. Requires Perl and msql-mysql-modules RPMs.
MySQL-devel-VERSION.i386.rpm
他の MySQL クライアント(perlモジュールのような)をコンパイルするのに必要な
ライブラリーとインクルードファイルを含みます。
MySQL-shared-VERSION.i386.rpm
This package contains the shared libraries (libmysqlclient.so*
)
which certain languages and applications need to dynamically load and
use MySQL.
MySQL-embedded-VERSION.i386.rpm
The embedded MySQL server library (MySQL 4.x and onwards only).
MySQL-VERSION.src.rpm
上記全てのソース。これは他のアーキテクチャ用に RPM を作成する場合にのみ必要でしょう。
(例えば Alpha や SPARC).
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サーバ には,2つの配布形態があります。:
大雑把な言い方をすると,バイナリ配布を使用する方がいいでしょう。
You will need the following:
MAX_ROWS
and
AVG_ROW_LENGTH
when you create the table. See section CREATE TABLE
構文.
ZIP
program to unpack the distribution file.
ODBC
, you
will also need the MyODBC
driver. See section MySQL ODBC サポート.
C:\> NET STOP MySQLOtherwise, use:
C:\mysql\bin> mysqladmin -u root shutdown
C:\mysql\bin> mysqld-max-nt --remove
Browse
button to specify your
preferred directory.
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.
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.
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'.
現在のバージョンとダウンロードの指示についての情報は 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.
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
.
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.
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.
我々は GNU Autoconf を使用していますので、MySQL は POSIX スレッ ドと C++ コンパイラが動作する全ての新しいシステムに移植可能です。(クライ アントコードのコンパイルだけは C++ を必要としますが、スレッドは必要ではありません。) 我々は自身のソフトウェアを、最初に Sun Solaris (現在は 2.5 〜 2.7) 上と SuSE Linux Version 7.x で使用し開発します。
多くの OS では、ネイティブスレッドは最新バージョ ンだけで動作することに注意してください。 MySQL は次の OS/スレッドパッケージの組み合わせで、コンパイルの 成功が報告されています。
glibc
2.0.7+. See section Linux Notes (All Linux Versions).
全てのプラットフォームが MySQL Server をちゃんと動作させるものではありません。 我々は以下のような評価基準に基づいて重要な要件を任せるに足るプラットフォームで あるかを判断しています。:
pthread_mutex_lock()
の実装に
不安がある場合です。この場合は MySQL の実行をはなはだしく阻害します。
このことを考慮せずにいるとCPUを増設するほど MySQL の実行が遅くなる
事象を生じるでしょう。
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.
make を行う前に決める事は、あなたが最新の開発リリースを使用するのか、 または最新の安定リリースを使用するのかです:
make 前の2番目の決定事項は、ソースディストリビューションとバイナリディ ストリビューションのどちらを使用するかです。多くの場合、バイナリがプラッ トフォーム用に存在していれば、おそらくバイナリディストリビューションを使 用すべきです。通常、それはソースディストリビューションよりも簡単にインス トールできます。
次のケースでは、おそらくソースインストールの方が良いでしょう:
MySQL
クライアントは両方の MySQL バージョンに接続できます。
拡張 MySQL バイナリディストリビューションは -max
接尾語が
つけられていて、mysqld-max
と同じオプションで configure されていま
す。See section mysqld-max
, An Extended mysqld
Server.
MySQL-Max RPM を使用したい場合は、最初に標準 MySQL RPM をイ
ンストールすべきです。
mysqld
を、標準バイナリディストリビューションには無いいくつかの拡
張機能付きで configure したい場合。使用できる代表的な拡張オプションは次
の通りです:
--with-innodb
--with-berkeley-db
--with-raid
--with-libwrap
--with-named-z-lib (This is done for some of the binaries)
--with-debug[=full]
pgcc
のような)や、あなた
のプロセッサ用により最適化されたコンパイラオプションを使用できます。
MySQL の命名法では、リリース番号は3つの数値とサフィックスからな
ります。例えば、mysql-3.21.17-beta
のようなリリース名は次のように
解釈されます:
3
)はファイル形式を表します。全てのバージョン 3 リリー
スは同じファイルフォーマットを持ちます。
21
)はリリースレベルです。通常は二つから選択します。一
つはリリース/安定ブランチで(現在は 23
)、もう一つは開発ブランチです(現在は 4.0
)。
通常は両方とも安定ですが、開発バージョンはきまぐれで、ドキュメントがなく、いくつかのシ
ステムではコンパイルに失敗します。
17
)はリリースレベル内のバージョン番号です。これは新し
い配布の度に増加します。普通はあなたの選択したリリースレベルの最新バージョ
ンを求めます。
beta
)はリリースの安定レベルを表します:
alpha
は、100% テストされていないいくつかの新しい大きなコードセク
ションが存在することを示し、知られているバグは News 節に記述されています
(通常はありません)。See section MySQL Change History. 多くの alpha リリースには新しいコマ
ンドと拡張もあります。
大きなコード変更を含む開発中のものは、alpha リリース上に現れます。しかし
全てリリース前にテストされます。それぞれの MySQL リリースには既知
のバグはありません。
beta
は全ての新しいコードがテストされたことを意味します。大きな新
しいものは追加されません。知られているバグはありません。
alpha バージョンで、少なくとも一カ月間、致命的なバグが報告されなくて、古
いコマンドをより信頼できなくするような新しい機能を追加する計画がない時に、
alpha から beta にバージョンが変更されます。
gamma
は beta がしばらくして、正しく動くように見えるものです。
小さな修正だけが追加されます。
これは多くの他の会社がリリースと呼ぶものです。
MySQL の全てのバージョンは、比較的安全に使用できることを確かめ るため、我々は標準テストとベンチマークを通して確認しています。標準テス トは以前に見つかった全てのバグをチェックするように拡張されるため、テスト スイートはより良く保持されます。
全てのリリースは少なくても次のテストがされていることに注意してください:
crash-me
テスト
他のテストは我々の内部製品環境で最新の 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' | データベースとログファイル |
ソースインストールのレイアウトはバイナリインストールと次の点が異なります:
mysqld
サーバは `bin' ではなく
`libexec' ディレクトリにインストールされます。
mysql_install_db
は `/usr/local/mysql/scripts' ではなく
`/usr/local/bin' ディレクトリにインストールされます。
スクリプト `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 AB は MySQL のバイナリ配布を提供しています。 これらのコンパイルは MySQL AB 内部でおこなったり、我々にマシンの アクセスを提供してもらっている顧客のマシン上で行っています。
これらの配布物は Build-tools/Do-compile
で作成され (このスクリプトは
scripts/make_binary_distribution
を使用して
ソースをコンパイルし tar.gz
バイナリを作成します)、
以下のコンパイルオプションで調整されています。
Binaries built on MySQL AB development systems:
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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
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
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
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.
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
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
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
gcc
2.8.1
CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex
gcc
2.7.2.1
CC=gcc CXX=gcc CXXFLAGS=-O ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex
gcc
2.7.2
CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex
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 のインストール.
See also section Installing the Binaries, section Installing MySQL on Linux, and section Building Client Programs.
MySQL の バイナリ配布プログラムをインストールする際は以下のツールが必要になります:
gunzip
。ソースを伸長するのに必要です。
tar
。これもソースを展開するのに必要です。
GNU tar
の動作は確認されています。Sun tar
の使用には問題があります。
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
スクリプトを
使用できます。使用の際はDBI
とMsql-Mysql-modules
の
Perlモジュールをインストールする必要があります。
より詳細な情報をここから示します。
バイナリ配布のプログラムをインストールする際は以下に従ってください。 その後、section インストール後の設定とテストに進んでインストールの終了処理と動作試験を行ってください。
root
としてインストールを行う必要があります。
tar
形式で行われており、
`mysql-VERSION-OS.tar.gz' のような形式の名前が付けられています。
ここで、VERSION
はバージョン番号(例えば 3.21.15
)を
OS
はプラットホームとなるOS(例えば pc-linux-gnu-i586
)を示します。
-max
という表示があるものがありますが、
これはこのプログラムが transaction-safe 機能やその他の機能をサポート
していることを示しています。See section mysqld-max
, An Extended mysqld
Server。
全てのバイナリプログラムは同じソースファイルからmakeされたものです。
mysqld
が動作するためのユーザとグループを作成してください。
shell> groupadd mysql shell> useradd -g mysql mysqlこれらのコマンドは
mysql
グループと mysql
ユーザを作成するものです。
useradd
や groupadd
というコマンドもありますが、
これらは使用プラットホームによって使い方が若干異なります。
また、adduser
や addgroup
と呼ばれる場合もあります。
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最初のコマンドで `mysql-VERSION-OS' という名前のディレクトリを作成します。 次のコマンドはそのディレクトリへのシンボリックリンクを作成し、 ユーザに単純な `/usr/local/mysql' という名前での利用を可能にします。
shell> cd mysql複数のファイルが
mysql
以下のディレクトリに展開されているのが
おわかりになると思います。 中でもインストールに重要な役目を果たすものは
`bin' と `scripts' のサブディレクトリにあります。
PATH
environment variable so that your shell finds the MySQL
programs properly. See section Environment Variables.
mysql_install_db
という mysql
への
アクセス管理を行うデータベースを初期化するためのスクリプトが置いてあります。
mysqlaccess
を使う必要があり、なおかつ、標準ディレクトリとは異なる場所に
インストールを行いたい場合は、mysqlaccess
が mysql
クライアントを
起動できるように環境設定を行う必要があります。
`bin/mysqlaccess'の18行目位にある以下のような行を変更してください。
$MYSQL = '/usr/local/bin/mysql'; # path to mysql executableこれを実際に
mysql
がインストールされているディレクトリに変更してください。
これをしないと mysqlaccess
を使う際に Broken pipe
エラーが発生します。
shell> scripts/mysql_install_db使用する MySQL のバージョンが 3.22.10 より古い場合はこの操作をする時に MySQL サーバが 立ち上がっている必要がありましたが、現在のバージョンでは必要ありません。
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
になります。
DBI
、DBD
のインストールが必要ならsection Perl Installation Commentsの項をご覧下さい。
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 を作成しインストールするためには次のツールが必 要です:
gunzip
。配布の伸張のため。
tar
。配布の展開のため。GNU tar
は動くことが知られて
います。Sun の tar
は問題があることが知られています。
gcc
>= 2.95.2, egcs
>= 1.0.2
or egcs 2.91.66
, SGI C++, and SunPro C++ are some of the
compilers that are known to work. libg++
is not needed when
using gcc
. gcc
2.7.x has a bug that makes it impossible
to compile some perfectly legal C++ files, such as
`sql/sql_base.cc'. If you only have gcc
2.7.x, you must
upgrade your gcc
to be able to compile MySQL. gcc
2.8.1 is also known to have problems on some platforms, so it should be
avoided if a new compiler exists for the platform.
MySQL 3.23.x のコンパイル時は、gcc
>= 2.95.2 を推奨します。
make
プログラム。GNU make
は常に推奨され、時々は必要
とされます。問題があれば GNU make
3.75 以上を試すことをお勧めしま
す。
-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バイナリを作成します
もし DBI
と Msql-Mysql-modules
Perl モジュールをインストールするなら、
bin/mysql_setpermission
スクリプトが使用する新しいユーザーを
追加することができます。
次にさらに詳細な説明を行ないます:
ソース配布のインストールには、次のステップに従い、それから インストール 後の初期化とテストのために section インストール後の設定とテスト に進んでください。
BDB
or BerkeleyDB
Tables.
MySQL ソース配布は圧縮された tar
アーカイブとして提供さ
れ、`mysql-VERSION.tar.gz' のような名前を持ちます。ここで
VERSION
は のような番号です。
mysqld
を実行するユーザーとグループを追加します:
shell> groupadd mysql shell> useradd -g mysql mysqlこれらのコマンドは
mysql
グループと mysql
ユーザを追加します。
useradd
と groupadd
構文は、別のバージョンの UNIX 上では少し異なるでしょ
う。adduser
と addgroup
と呼ばれることもあります。ユーザとグ
ループは mysql
の代わりに他の何かにすることもできます。
shell> gunzip < /path/to/mysql-VERSION.tar.gz | tar xvf -このコマンドは `mysql-VERSION' という名前のディレクトリを作成します。
shell> cd mysql-VERSION注意: 現在のこのトップレベルディレクトリで MySQL の configure と build を行なう必要があります。別のディレクトリでは build できません。
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 コンパイル時の問題 を参照してください。
shell> make installこのコマンドは
root
として実行する必要があります。
shell> scripts/mysql_install_db注意: 3.22.10 より古い MySQL バージョンでは、
mysql_install_db
実行時に MySQL サーバが開始されましたが、
これはもはや真ではありません!
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番目のコマンドは owner
を mysql
ユーザに変更し、
3番目のコマンドは group
属性を mysql
グループに変更します。
DBI
/DBD
インタフェースのサポートをインストールしたい
場合、section Perl Installation Comments を見てください。
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
オプションのいくつかを以下に説明します:
--without-server
オプションを使用してください:
shell> ./configure --without-serverC++ コンパイラがなければ、
mysql
はコンパイルできません(これは C++
を要求するクライアントプログラムの一つです)。この場合、configure
から C++ コンパイラをテストするコードを削除でます。それから
./configure
を --without-server
オプションつきで実行してく
ださい。コンパイルステップは mysql
の作成を試みますが、
`mysql.cc' についての警告は無視できます。(make
が止まる場合、
エラーが発生しても残りの作成を継続するように make -k
を試してくだ
さい。)
libmysqld.a
)を得たい場合は、
--with-embedded-server
オプションを使用してください。(version 4.0以
上)
configure
コマンドのうちのどれかを使用してく
ださい:
shell> ./configure --prefix=/usr/local/mysql shell> ./configure --prefix=/usr/local \ --localstatedir=/usr/local/mysql/data最初のコマンドはインストールプレフィックスを変更し、デフォルトの `/usr/local' ではなく `/usr/local/mysql' 配下にインストールし ます。次のコマンドはデフォルトのインストールプレフィックスを保存しますが、 データベースディレクトリのデフォルト位置(通常は `/usr/local/var')を 上書きし、
/usr/local/mysql/data
に変更します。
MySQL をコンパイルした後でも、これらのオプションはオプションファイルで変更
できます See section `my.cnf' オプションファイル.
configure
コマン
ドを次のように使用します:
shell> ./configure --with-unix-socket-path=/usr/local/mysql/tmp/mysql.sockファイル名は絶対パスでなければなりません! MySQL オプションファイルを使用することで、`mysql.sock' の場所をあとで 変更することもできます。 See section MySQL ソケットファイル `/tmp/mysql.sock' を変更する方法、削除から守る方法.
configure
を実行します:
shell> ./configure --with-client-ldflags=-all-static \ --with-mysqld-ldflags=-all-static
gcc
を使用していて、libg++
や libstdc++
がインストー
ルされていない場合、configure
に gcc
を C++ コンパイラとし
て使用することを伝えてください:
shell> CC=gcc CXX=gcc ./configure
gcc
を C++ コンパイラとして使用する時、libg++
または
libstdc++
のリンクは試みません。
This may be a good idea to do even if you
have the above libraries installed, as some versions of these libraries have
caused strange problems for MySQL users in the past.
あなたが使用しているコンパイラによって、設定するいくつかの標準的な環境変数
があります:
Compiler | Recommended options |
gcc 2.7.2.1 | CC=gcc CXX=gcc CXXFLAGS="-O3 -felide-constructors" |
egcs 1.0.3a | CC=gcc CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" |
gcc 2.95.2 | CFLAGS="-O3 -mpentiumpro" CXX=gcc CXXFLAGS="-O3 -mpentiumpro \ -felide-constructors -fno-exceptions -fno-rtti" |
pgcc 2.90.29 or newer | CFLAGS="-O3 -mpentiumpro -mstack-align-double" CXX=gcc \ CXXFLAGS="-O3 -mpentiumpro -mstack-align-double -felide-constructors \ -fno-exceptions -fno-rtti" |
--prefix=/usr/local/mysql --enable-assembler \ --with-mysqld-ldflags=-all-static言い換えれば、すべての最近の gcc バージョン用には、完全な configure 行は次 のようなものになります:
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我々が MySQL Web サイト http://www.mysql.com/ 上で提供して いるバイナリは、完全に最適化されてコンパイルされ、多くのユーザに完全です。 See section MySQL Binaries Compiled by MySQL AB。さらに速いバイナリを作成するために調整できることが いくつかありますが、これは上級ユーザ向けです。 See section MySQL の速度に影響するコンパイルとリンク方法. コンパイラやリンカが共有ライブラリ `libmysqlclient.so.#' を生成でき ないというエラーになる場合、
--disable-shared
オプションを
configure
に与えることで、この問題を回避できます。この場合、
configure
は共有ライブラリ `libmysqlclient.so.#' を作成しま
せん。
NULL
項目(すなわち、NULL
が許されていない項目)に
DEFAULT
項目値を使用しないように MySQL をコンフィグでき
ます。これは、非 NULL
値を要求する全ての項目に値を明示的に指定し
なければ、INSERT
ステートメントはエラーを生成します。デフォルト値
の使用を抑えるには、次のように configure
を実行します:
shell> CXXFLAGS=-DDONT_USE_DEFAULT_FIELDS ./configure
--with-charset
オプションを
使用します:
shell> ./configure --with-charset=CHARSET
CHARSET
は次のうちの一つです: big5
, cp1251
, cp1257
,
czech
, danish
, dec8
, dos
, euc_kr
,
gb2312
, gbk
, german1
, hebrew
, hp8
,
hungarian
, koi8_ru
, koi8_ukr
, latin1
,
latin2
, sjis
, swe7
, tis620
, ujis
,
usa7
, or win1251ukr
.
See section データとソートに使用されるキャラクター・セット.
サーバとクライアント間で文字を変換したい場合は、
SET CHARACTER SET
コマンドを調べるべきです。
See section SET
構文.
警告: テーブルを生成した後に文字セットを変更する場合、
myisamchk -r -q --set-character-set=charset
を全てのテーブルに実行する必要があります。
そうでないと、インデックスは正しくソートされません。(これは、MySQL のイ
ンストール時、いくつかのテーブルの生成時、異なる文字セットを使用して
MySQL の再コンフィグ時、そして再インストール時に発生します。)
オプション --with-extra-charsets=LIST
で、サーバ内に組み込むべき追加
文字セットを指定することができます。
ここで、LIST
は空白で区切られた文字セットのリストです。
complex
は動的にロードできないすべての文字を含み、all
はバイ
ナリにすべての文字セットを含みます。
--with-debug
オプションを使用します:
shell> ./configure --with-debugこれにより、いくつかのエラーを見つけられる安全なメモリ割り当てが含まれ、 何が発生しているかについての出力を提供します。 See section MySQL server のデバッグ.
--enable-thread-safe-client
configure オプションでスレッド安全用に
コンパイルする必要があります。これは、スレッドアプリケーションがリンクす
べき libmysqlclient_r
ライブラリを生成します。
See section スレッドクライアントを作る方法.
警告: 我々の新しいテストコードについて我々を手助けすることに興味 がある場合にだけ、この節を読むべきです。MySQL を得て、あなたのシ ステム上で実行したいだけの場合は、標準リリースディストリビューションを使 用すべきです(ソースまたはバイナリディストリビューション)。
我々のもっとも新しい開発ソースツリーを得るには、次の手順に従ってください:
BitKeeper
from
http://www.bitmover.com/cgi-bin/download.cgi. You will need
Bitkeeper
3.0 or newer to access our repository.
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.23To clone the 4.0 branch, use this command:
shell> bk clone bk://mysql.bkbits.net/mysql-4.0 mysql-4.0To clone the 4.1 branch, use this command:
shell> bk clone bk://mysql.bkbits.net/mysql-4.1 mysql-4.1In 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.1The initial download of the source tree may take a while, depending on the speed of your connection - please be patient.
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 makeIf 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.
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.
make test
. See section MySQL Test Suite.
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.
bk clone
operation to get the source tree, you
should run bk pull
periodically to get the updates.
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.
BitKeeper
has a nice help utility that you can access via
bk helptool
.
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
Solaris や Linux 上で gcc
を使用した場合、一切警告無く
全ての MySQL プログラムがきれいに作れます。
他のシステムではインクルードファイルの違いから警告が出るかもしれません。
MIT-pthreads を使用した際の警告は section MIT-pthreads に関して を参照してください。
他の問題は、以下をチェックしてください。
多くの問題の解決のために、再 configure が必要です。 あなたが再構成する必要があるならば、以下に気をつけてください:
configure
を一度実行した後に実行するならば、 configure
は
前に作った情報を利用します。この情報は `config.cache' に保存されます。
configure
は起動時にこのファイルを探し、もし存在するならば、
その中の情報が正しい物として読み込みます。
これはあなたが再コンフィグするならば無効になります。
configure
を実行するごとに、 make
を実行してコンパイルしなければなりません。
しかし、最初に、前のビルドでできたオブジェクトを、消しておいてください。
なぜなら、違うコンフィグオプションにより生成されたからです。
古いコンフィグやオブジェクトファイルの使用を防ぐため、
configure
前に以下のコマンドを実行してください:
shell> rm config.cache shell> make clean
こうするかわりに、make distclean
としても構いません。
以下に、 MySQL をコンパイルする際に起こりやすい問題をあげておきます:
Internal compiler error: program cc1plus got fatal signal 11 or Out of virtual memory or Virtual memory exhaustedこの問題は、
gcc
がインライン展開で `sql_yacc.cc' をコンパイルするのに、
とても多くのメモリーを必要とするからです。
この場合、 configure
を --with-low-memory
オプション指定で実行します:
shell> ./configure --with-low-memoryこのオプションは、
gcc
を使用しているなら -fno-inline
オプションを
コマンドラインに加え、gcc
以外ならば -O0
を加えます。
多くのメモリーとスワップを持っていない限りは、--with-low-memory
オプションを使用すべきです。
この問題はけっこうなハードウェア構成でも起こることが知られています。
通常、 --with-low-memory
オプションでこの問題は解決できます。
configure
は c++
という名前でコンパイラーを使用し、
GNU c++
は -lg++
を使ってリンクします。
もし gcc
を使用しているならば、コンフィグ時に以下のような問題が出るかもしれません:
configure: error: installation or configuration problem: C++ compiler cannot create executables.この問題は、
g++
, libg++
あるいは libstdc++
に関連したものです。
原因の一つとして考えられることは、 g++
を持っていないか、あるいは、
g++
はあっても libg++
か libstdc++
がないという事です。
`config.log' ファイルは c++ コンパイラが動作しなかった理由を記録しています!
この問題を解決するに当たり、あなたが持っている C++ コンパイラーの代わりに
gcc
を使用しても構いません。CXX
環境変数に "gcc -O3"
としてみてください。
例えば:
shell> CXX="gcc -O3" ./configureこれは
gcc
が g++
と同様に C++ ソースをコンパイルするので動きますが、
libg++
か libstdc++
が標準ではリンクされません。
他の解決方法は、もちろん、g++
, libg++
, libstdc++
をインストールすることです。
We would however like to recommend
you to not use libg++
or libstdc++
with MySQL as this will
only increase the binary size of mysqld without giving you any benefits.
Some versions of these libraries have also caused strange problems for
MySQL users in the past.
make
のバージョンを上げてください:
making all in mit-pthreads make: Fatal error in reader: Makefile, line 18: Badly formed macro assignment or make: file `Makefile' line 18: Must be a separator (: or pthread.h: No such file or directorySolaris と FreeBSD の
make
プログラムには問題があることが知られています。
GNU make
Version 3.75 は動作確認されています。
CFLAGS
と CXXFLAGS
環境変数に
フラグを追加してください。同様に、 CC
と CXX
にコンパイラー名を
与えることもできます。
例えば:
shell> CC=gcc shell> CFLAGS=-O3 shell> CXX=gcc shell> CXXFLAGS=-O3 shell> export CC CFLAGS CXX CXXFLAGSsection MySQL Binaries Compiled by MySQL AB にはフラグの定義がリストされています。 色々なシステム上で役に立つと思います。
gcc
コンパイラーをアップグレードしてください:
client/libmysql.c:273: parse error before `__attribute__'
gcc
2.8.1 は動作することが確認されていますが、
gcc
2.95.2 以上をお勧めします。
mysqld
コンパイル時に以下のようなエラーが出た場合、
configure
が accept()
, getsockname()
, getpeername()
の最後の引数を正しく検出していません:
cxx: Error: mysqld.cc, line 645: In this statement, the referenced type of the pointer value "&length" is "unsigned long", which is not compatible with "int". new_sock = accept(sock, (struct sockaddr *)&cAddr, &length);これを修正するには、`config.h' ファイル(
configure
により作られる) を修正します。
いかのように:
/* Define as the base type of the last arg to accept */ #define SOCKET_SIZE_TYPE XXX
XXX
を size_t
か int
(あなたのオペレーティングシステムが依存している型)に変えます。
(configure
すると毎回 `config.h' は作り直されるので、
この修正は configure
する度に行わなければならないことに注意)
"sql_yacc.yy", line xxx fatal: default action causes potential...これはあなたの
yacc
のバージョンが不十分であることを示しています。
bison
(GNU 版 yacc
) を代わりにインストールして使用する必要があります。
mysqld
か MySQL クライアントをデバッグしたいなら、
configure
を --with-debug
オプション付きで実行します。
そしてコンパイルし、新しいクライアントライブラリーでクライアントをリンクします。
See section Debugging a MySQL client.
このセクションでは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
.
--with-mit-threads
オプションで
configure
実行することによって、
MIT-pthreadsが使われることを強制することができます。
shell> ./configure --with-mit-threadsMIT-pthreadsを使う時、非ソースディレクトリで構築することはサポートされていませ ん。なぜなら、私たちはこのコードへ私たちの変更を最小にしたいからです。
--without-server
を使ってクライアントコードのみを
ビルドすることを設定したならば、クライアントは MIT-othreads が使われているかいないか、
UNIXソケット接続がデフォルトで使われているのかわかりません。なぜなら UNIX ソケットは
MIT-pthreads 下では動作しないからです。また、あなたはそのようなインスタンスでは
-h
または --host
を使う必要があります。
--external-locking
オプション
を指定してサーバーに伝えることで、システムロックは使えるようになります。
This is only
needed if you want to be able to run two MySQL servers against the same
data files (not recommended).
bind()
コマンドは何のエラーメッセージ
なしにソケットへの bind に失敗することがあります。これは結果としてサーバーへの接続
失敗となります。たとえば、
shell> mysqladmin version mysqladmin: connect to server at '' failed; error: 'Can't connect to mysql server on localhost (146)'これを解決するために
mysqld
サーバーを終了して、再起動してください。こ
れは私たちがサーバーダウンを強制して、すぐにリスタートさせようとしたときだけ起こ
りました。
sleep()
システムコールは SIGINT
(break)
では割り込みできません。 これは mysqladmin --sleep
を走らせているときにだけ
起こることがわかっています。
割り込みが発生してプロセスが停止する前に、あなたは終了させるための sleep()
コールを待たなく
てはなりません。
ld: warning: symbol `_iob' has differing sizes: (file /my/local/pthreads/lib/libpthread.a(findfp.o) value=0x4; file /usr/lib/libc.so value=0x140); /my/local/pthreads/lib/libpthread.a(findfp.o) definition taken ld: warning: symbol `__iob' has differing sizes: (file /my/local/pthreads/lib/libpthread.a(findfp.o) value=0x4; file /usr/lib/libc.so value=0x140); /my/local/pthreads/lib/libpthread.a(findfp.o) definition taken
implicit declaration of function `int strtoll(...)' implicit declaration of function `int strtoul(...)'
readline
を手に入れていません(これは必要では
ないのですが、おそらく誰かには興味があるでしょう)。
You will need the following:
Building MySQL
File
menu, select Open Workspace
.
Build
menu,
select the Set Active Configuration
menu.
mysqld - Win32 Debug
and click OK.
F7
to begin the build of the debug server, libs, and
some client applications.
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 のソースディレクトリです。
コマンドは本節といかに続く節で説明しますが、BINDIR
は
mysqladmin
や safe_mysqld
がインストールされたディレクトリを示します。
バイナリ配布を使用している場合、BINDIR
はバイナリ配布の `bin' ディレクトリになります。
ソースからインストールした場合、BINDIR
は、configure
で特別指定しない限り、
`/usr/local/bin' です。
EXECDIR
は mysqld
サーバーのインストール先です。
バイナリ配布を使用している場合、これは BINDIR
ディレクトリと同一になります。
ソースからインストールした場合、`/usr/local/libexec' です。
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
.
root
で mysql_install_db
を実行する必要があるとあなたは思うかもしれません。
しかし、 MySQL は root
以外のユーザーで起動できます。
データベースディレクトリがサーバーを起動したユーザに対して読み書きが許可されていれば良いのです。
MySQL を一般ユーザーで走らせる方法は
section 一般ユーザで MySQL を動かす方法.
もし mysql_install_db
で問題が出たら、
section mysql_install_db
実行時の問題. を参照のこと。
mysql_install_db
スクリプトを走らせるにはいくつか選択があります:
mysql_install_db
を走らせる前に編集して、許可の初期状態を変更してもいいでしょう。
これは多くのマシンに同じ権限設定をして MySQL をインストールする際に
役立ちます。 この場合、いくつかの INSERT
構文を mysql.user
と
mysql.db
テーブルにたいして追加するようにするだけですみます!
mysql -u root mysql
で MySQL root
ユーザーで接続して直接許可テーブルを変更する SQL 文を実行します。
mysql_install_db
を編集した後にそう思うかもしれません。mysql_install_db
.
shell> cd mysql_installation_directory shell> bin/safe_mysqld &サーバの起動に問題があれば、section MySQL サーバー起動時の問題 を見てください。
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
オプションで起動することにより得られます。
shell> BINDIR/mysqladmin -u root shutdown
safe_mysqld
か mysqld
を直接実行します。
例えば:
shell> BINDIR/safe_mysqld --log &
safe_mysqld
が失敗するなら、 MySQL のインストールディレクトリーから実行してみてください。
もしそれでも起動しないなら、section MySQL サーバー起動時の問題 を参照のこと。
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-testsRPM バイナリ配布には `sql-bench' ディレクトリがありません。 (RPM のソース配布には含まれます) この場合、ベンチマークをインストールしなくてはなりません。 MySQL バージョン 3.22 のバイナリ配布から、 `mysql-bench-VERSION-i386.rpm' という名前で RPM パッケージを作っており、 これにはベンチマークのデータとコードが含まれます。 `tests' サブディレクトリでテストすることも可能です。 例えば、`auto_increment.tst' の実行は以下のようにします:
shell> BINDIR/mysql -vvf test < ./tests/auto_increment.tstThe 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 バグや問題を報告する方法.
mysqld
daemon running
mysql_install_db
を実行する必要はありません。
mysql_install_db
を実行するのは MySQL を初めてインストールした後、
たった一回だけです。
mysqld
daemon doesn't work when one daemon is running
Can't start server: Bind on TCP/IP port: Address already in use
エラーメッセージか
Can't start server : Bind on unix socket...
エラーメッセージが出ます。
See section 同じマシンに多くのサーバをインストールする.
mysql_install_db
の実行時、あるいは mysqld
の起動/使用時に
エラーとなるでしょう。
違うディレクトリーにソケットファイルや一時ファイルを指定するには:
shell> TMPDIR=/some_tmp_dir/ shell> MYSQL_UNIX_PORT=/some_tmp_dir/mysqld.sock shell> export TMPDIR MYSQL_UNIX_PORTSee 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
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-privileges
か mysqladmin reload
を実行します。
トランザクションをサポートするテーブル(BDB, InnoDB)を使用しようとする場合、 最初に `my.cnf' ファイルを生成して、使用しようとするテーブル型の起動オプショ ンを設定すべきです。 See section MySQL テーブル型.
通常 mysqld
サーバーの起動は、以下の三つの方法のうち一つで行います:
mysql.server
による起動。このスクリプトはシステムの起動時、停止時に使われます。
詳細は section MySQL の自動起動と自動停止.
safe_mysqld
による起動。これは mysqld
への適切なオプションを決定し、
それらのオプションでサーバーの起動を試みます。 See section safe_mysqld
, The Wrapper Around mysqld
.
mysqld
directly.
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.server
と safe_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 が同じベースバージョ
ンである限り、同じアーキテクチャ上の異なるバージョン間でいつでも移動でき
ます。現在のベースバージョンは 3 です。MySQL の実行時に
キャラクタ・セットが変更された場合(これはソート順も変更します)、全てのテーブル
に myisamchk -r -q --set-character-set=charset
を行なう必要があります。
そうしなければ、インデックスが正しい順になりません。
もしあなたが神経質だったり新しいバージョンを恐れている場合、いつでもあな
たの古い mysqld
を mysqld-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 の
アップグレード後にコアダンプする兆候に気づいた場合は、特に
そうしてください。
In general what you have to do when upgrading to 4.1 from an earlier MySQL version:
mysql_fix_privilege_tables
to generate the new
password field that is needed for secure handling of passwords.
The following is a more complete lists tell what you have to watch out for when upgrading to version 4.1;
mysql> SELECT cast("2001-1-1" as DATE) -> '2001-01-01'
SHOW CREATE TABLE
and mysqldump
.
(MySQL 4.0.6 and above can read the new dump files, but not previous
MySQL versions).
'YYYY-MM-DD HH:MM:DD'
.
If you want to have this as a number you should add +0 to the timestamp
column. Different timestamp lengths are not supported.
--shared_memory_base_name
option on all machines.
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
, データベースとテーブルから、構造とデータをダンプ.
In general what you have to do when upgrading to 4.0 from an earlier MySQL version:
mysql_fix_privilege_tables
to add new
privileges and features
to the MySQL privilege tables.
mysql_convert_table_format database
. Note that this should only
be run if all tables in the given database is ISAM or MyISAM tables. If
this is not the case you should run ALTER TABLE table_name TYPE=MyISAM
on all ISAM tables.
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 にアップグレードする際に気をつけなければなら ないことです;
mysql.user
table.
See section GRANT
と REVOKE
構文.
To get these new privileges to work, one must run the
mysql_fix_privilege_tables
script. Until this script is run all
users have the SHOW DATABASES
, CREATE TEMPORARY TABLES
,
and LOCK TABLES
privileges. SUPER
and EXECUTE
privileges take their value from PROCESS
.
REPLICATION SLAVE
and REPLICATION CLIENT
take their
values from FILE
.
If you have any scripts that creates new users, you may want to change
them to use the new privileges. If you are not using GRANT
commands in the scripts, this is a good time to change your scripts.
In version 4.0.2 the option --safe-show-database
is deprecated
(and no longer does anything). See section セキュリティに関する mysqld
の起動オプション.
If you get access denied errors for new users in version 4.0.2, you
should check if you need some of the new grants that you didn't need
before. In particular, you will need REPLICATION SLAVE
(instead of FILE
) for new slaves.
myisam_max_extra_sort_file_size
and
myisam_max_extra_sort_file_size
are now given in bytes
(was megabytes before 4.0.3).
External system locking of MyISAM/ISAM files is now turned off by default.
One can turn this on by doing --external-locking
. (For most users
this is never needed).
From | to. |
myisam_bulk_insert_tree_size | bulk_insert_buffer_size
|
query_cache_startup_type | query_cache_type
|
record_buffer | read_buffer_size
|
record_rnd_buffer | read_rnd_buffer_size
|
sort_buffer | sort_buffer_size
|
warnings | log-warnings
|
err-log | --log-error (for mysqld_safe )
|
record_buffer
, sort_buffer
and
warnings
will still work in MySQL 4.0 but are deprecated.
From | To. |
SQL_BIG_TABLES | BIG_TABLES
|
SQL_LOW_PRIORITY_UPDATES | LOW_PRIORITY_UPDATES
|
SQL_MAX_JOIN_SIZE | MAX_JOIN_SIZE
|
SQL_QUERY_CACHE_TYPE | QUERY_CACHE_TYPE
|
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=#
instead of
SET SQL_SLAVE_SKIP_COUNTER=#
.
--skip-locking
to
--skip-external-locking
and --enable-locking
to
--external-locking
.
SHOW MASTER STATUS
now returns an empty set if binary log is not
enabled.
SHOW SLAVE STATUS
now returns an empty set if slave is not initialised.
--temp-pool
enabled by default as this
gives better performance with some OS (Most notable Linux).
DOUBLE
and FLOAT
columns now honour the
UNSIGNED
flag on storage (before, UNSIGNED
was ignored for
these columns).
ORDER BY column DESC
now always sorts NULL
values
first; in 3.23 this was not always consistent. Note: MySQL 4.0.11 restored
the original behaviour.
SHOW INDEX
has 2 columns more (Null
and Index_type
)
than it had in 3.23.
CHECK
, SIGNED
, LOCALTIME
and LOCALTIMESTAMP
are now reserved words.
|
, &
, <<
,
>>
, and ~
is now unsigned. This may cause problems if you
are using them in a context where you want a signed result.
See section Cast Functions.
UNSIGNED
, the result will be unsigned! In other
words, before upgrading to MySQL 4.0, you should check your application
for cases where you are subtracting a value from an unsigned entity and
want a negative answer or subtracting an unsigned value from an
integer column. You can disable this behaviour by using the
--sql-mode=NO_UNSIGNED_SUBTRACTION
option when starting
mysqld
. See section Cast Functions.
MATCH ... AGAINST (... IN BOOLEAN MODE)
を使用するためには、
REPAIR TABLE table_name USE_FRM
を実行してテーブルをリビルド
する必要があります。
たとえ テーブルの型が MyISAM
であったとしても。
LOCATE()
と INSTR()
はケース依存です。
もしいずれかの引数がバイナリ文字列ならば。Otherwise they are case-insensitive.
STRCMP()
now uses the current character set when doing comparisons,
which means that the default comparison behaviour now is case-insensitive.
HEX(string)
は、与えられた `文字列' を、
16進数で表記しなおした `文字列' を返すようになりました。
もし、`数値'の16進表記を得たい場合は、 HEX()
の引数は
数値にしなくてはなりません。
(訳注: 4.0ではこうなります. (EUC-JP)
mysql> select HEX("xyz"),HEX("あ"),HEX("16"),HEX(16); +------------+-----------+-----------+---------+ | HEX("xyz") | HEX("あ") | HEX("16") | HEX(16) | +------------+-----------+-----------+---------+ | 78797A | A4A2 | 3136 | 10 | +------------+-----------+-----------+---------+これが、3.23ではこうなっていました.
mysql> select HEX("xyz"),HEX("あ"),HEX("16"),HEX(16); +------------+-----------+-----------+---------+ | HEX("xyz") | HEX("あ") | HEX("16") | HEX(16) | +------------+-----------+-----------+---------+ | 0 | 0 | 10 | 10 | +------------+-----------+-----------+---------+)
INSERT INTO ... SELECT
は常に IGNORE
が有効になっ
ていました。4.0.1 では、IGNORE
を記述しない場合、MySQL はエラーの場
合に停止します(そして、おそらくロールバックします)。
safe_mysqld
as a symlink to
mysqld_safe
.
mysql_drop_db
, mysql_create_db
,
mysql_connect
は、もう、サポートされなくなりました。
ただし、MySQL を CFLAGS=-DUSE_OLD_FUNCTIONS
フラグでコンパイルすれば、まだ使うことはできます。
しかし、このフラグを使用する代わりに
クライアントを新しい 4.0 API に変更する方が良いです。
MYSQL_FIELD
構造体では、
length
と max_length
が
unsigned int
から unsigned long
に変更されました。
これを printf()
形式関数に使用する場合にいくつかの警告が出ること以
外は、問題は発生しません。
TRUNCATE TABLE
を使用すべきです。(なぜなら TRUNCATE
TABLE
は DELETE FROM table_name
よりも速いからです)。
TRUNCATE TABLE
や DROP DATABASE
の実行時に、有効な
LOCK TABLES
やトランザクションがある場合、エラーになります。
SHOW OPEN TABLE
のフォーマットが変更されました。
mysql_thread_init()
と
mysql_thread_end()
を使用せねばなりません。 See section スレッドクライアントを作る方法.
drop_db()
呼び出しを使用している
ためです。
RAND(seed)
は、3.23 に比べて、より違ったランダムを返すようになりました。
これは RAND(seed)
と RAND(seed+1)
により違いがでるという事です。
IFNULL(A,B)
is now set to be the
more 'general' of the types of A
and B
. (The order is
STRING
, REAL
or INTEGER
).
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 にアップグレードするときに、注目する必要があるものを列挙します:
tis620
文字セットを使用しているすべてのテーブルを myisamchk
-r
または REPAIR TABLE
で fix する必要があります。
DROP DATABASE
を行なう場
合は、リンクとオリジナルデータベースが削除されます。(3.22 では configure
が readlink
システムコールを検出しないため、これは起りません。)
OPTIMIZE TABLE
は現在、MyISAM
テーブルだけに動作します。他
のテーブル型については、ALTER TABLE
を使用して、テーブルを最適化で
きます。OPTIMIZE TABLE
の間は、テーブルは他のスレッドからロックされ
ます。
mysql
は現在、デフォルトで
--no-named-commands (-g)
オプションで起動されます。このオプションは
--enable-named-commands (-G)
で無効にできます。これは、非互換問題を
引き起こす場合があります。たとえば、セミコロン無しの named command を使用
する SQL スクリプトです! 長い形式のコマンドは行頭でまだ動作します。
MONTH()
) will now
return 0 for 0000-00-00
dates. (MySQL 3.22 returned NULL
.)
german
文字ソート順を使用する場合、ソート順についていくつか変更され
ているので、isamchk -r
ですべてのテーブルを修復する必要があります!
IF
のデフォルトの戻り値型は現在両方の引数に依存します。最初の引数だけではありません。
AUTO_INCREMENT
は負数では働きません。
この理由は、負数は -1 から 0 へのラッピング時に問題を引き起こすためです。
MyISAM の AUTO_INCREMENT
は現在、低レベルの部分で処理され、以
前よりとても速いです。MyISAM テーブルでは、テーブルからいくつかのレコード
を削除したとしても、古い数値は再利用されません。
CASE
, DELAYED
, ELSE
, END
, FULLTEXT
,
INNER
, RIGHT
, WHEN
は
予約語になりました。
FLOAT(X)
は本当の浮動小数点型になりました。桁数固定の値ではありません。
DECIMAL(length,dec)
宣言時、length 引数はもはや符号や小数点の場所を含みません。
TIME
文字列は以下のフォーマットのいずれかでなければなりません:
[[[DAYS] [H]H:]MM:]SS[.fraction]
か
[[[[[H]H]H]H]MM]SS[.fraction]
.
LIKE
は、同一文字の比較 '='
ルールを使用して、
比較を行うようになりました。
もし古い比較方法にするならば、 MySQL を CXXFLAGS=-DLIKE_CMP_TOUPPER
フラグでコンパイルします。
REGEXP
は、通常の文字列(非 binary) では、ケース非依存になりました。
MyISAM
テーブル(.MYI
) の検査・修復には、CHECK TABLE
を使用するか、myisamchk
を使用します。
isamchk
は ISAM(.ISM
) テーブル用に使用します。
mysqldump
を行いたいならば、
--opt
や --all
オプションを mysqldump
に指定してはいけません。
DATE_FORMAT()
をチェックしてください。
各フォーマット文字の前には `%' 文字が必要になりました。
(MySQL 3.22 バージョン以降ではこの文法が許されます。)
mysql_fetch_fields_direct
が関数になり (今まではマクロだったのが)、
MYSQL_FIELD
型ではなく MYSQL_FIELD
ポインター型を返します。
mysql_num_fields()
は、 MYSQL*
object をもはや使うことができません。
(これは今、 MYSQL_RES*
を引数に取る関数になりました)。
代わりに、 mysql_field_count()
を使用すべきです。
MySQL
バージョン 3.22 では, SELECT DISTINCT ...
の出力は
ほとんどいつもソートされました。 3.23 では, ソートを行った結果を得るには
GROUP BY
か ORDER BY
を使用しなくてはなりません。
SUM()
は 0 の代わりに NULL
を返すようになりました。
これは ANSI SQL 準拠です。
NULL
値での AND
や OR
は現在 0 ではなく
NULL
を返します。
これは主に、NOT NULL
= NULL
として、AND/OR
式上で
NOT
を使用するクエリに影響します。LPAD()
と RPAD()
は
長さ引数よりも長い場合、結果文字列は短くなります。
バージョン 3.21 と バージョン 3.22 の間には互換性に影響する変更はありません。
DATE
型のフィールドを持たせて作成した新しいテーブルは、
日付の格納に新しい方法を使用することだけが、唯一の落とし穴です。
これらの新しいフィールドに古いバージョンの
mysqld
からアクセスすることはできません。
MySQL
バージョン 3.22 インストール後、新しいサーバを開始して、
mysql_fix_privilege_tables
スクリプトを実行すべきです。これは
GRANT
コマンドを使用するために必要な権限を追加します。これを忘れ
ると、ALTER TABLE
、CREATE INDEX
、DROP 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_buffer
は key_buffer_size
に名前が
変わりました。しかし、まだ前の名前もスターとアップファイル中で使用できま
す。
既に バージョン 3.20.28 より前のバージョンが稼働していて、バージョン 3.21.x に変更したい場合は、 次を行なう必要があります:
safe_mysqld --old-protocol
で mysqld
3.21 サーバを起動すれ
ば、バージョン 3.20 配布からのクライアントでそれを使用できます。この場合、新しいク
ライアント関数 mysql_errno()
はサーバのエラーは何も返さず、
CR_UNKNOWN_ERROR
だけを返します (ただしクライアントのエラーについ
ては働きます)。そして サーバは古い password()
チェックを新しいものの代わ
りに使用します。
mysqld
に --old-protocol
オプションを使わない場合、
次の変更をする必要があります:
mysql.user
テーブル内の password
フィールドを
CHAR(16)
に変換するために、スクリプト
scripts/add_long_password
を実行する必要があります。
mysql.user
テーブル内に再配置する必要がありま
す(31ビットパスワードの代わりに、62ビットを得るために)。
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
(user
と password
引数の順番が変更されました)。
See section The DBI
Interface.
次の変更は古いアプリケーションでのクエリに影響します:
HAVING
は現在 ORDER BY
節より前になければいけません。
LOCATE()
へのパラメータは交換されました。
DATE
,
TIME
そして TIMESTAMP
です。
もし、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
データベース転送を実行するために、mysqldump
と mysqlimport
も使用できます。大きなテーブルでは、これは単純な mysqldump
の使用
よりもとても速いです。次に示すコマンドでは、DUMPDIR
は
mysqldump
からの出力を格納するために使用するディレクトリの完全な
パス名を表わしています。
まず、出力ファイルのためのディレクトリを作成して、データベースをダンプし ます:
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
を実行してください。
以下の注意は、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 1000000
を safe_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
実行時には、以下のうちの一つの方法で問題を解決できます:
-Lpath
のかわりに)リンクします:
-Wl,r/path-libmysqlclient.so
.
libmysqclient.so
を `/usr/lib' にコピーします
LD_RUN_PATH
環境変数を `libmysqlclient.so' が存在する場所に設定します。
(クライアントを実行する前に設定します)
富士通コンパイラ (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
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
この問題は、以下のうちのどれかの方法で解決できます:
tar.gz
)、代わりに
インストールします。
mysql_install_db --force
を実行します; これは mysql_install_db
に
かかれている resolveip
テストを実行しません。
また許可テーブル内でホスト名が使えなくなっています;
ホスト名でなく IP アドレスで登録します (localhost
は除).
もし --force
を持っていないような古い MySQL を使用しているなら、
エディターで、resolveip
テストを mysql_install
から削除します。
mysqld
を --user
の代わりに su
で起動。
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
カーネ
ルでこの問題が解決されることを希望します。
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
いくつかの埋め込み関数, 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 かそれ以上にしなくてはなりません。
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:
gdb 4.18
. You should download and use gdb 5.1 instead!
mysqld
statically when using gcc
, the
resulting image will core dump at start. In other words, don't
use --with-mysqld-ldflags=-all-static
with gcc
.
MySQL は最新の glibc
を使用した MkLinux で動作します。
(glibc
2.0.7 でテストしました).
Qube2 (Linux Mips) 上で MySQL を動作させるには、
最新の glibc
ライブラリでなくてはなりません
(glibc-2.0.7-29C2
は動作することが分かっています)。
そして、 egcs
C++ compiler (egcs-1.0.2-9
, gcc 2.95.2
以上) を
使用しなくてはなりません。
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.
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 のインストール.
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!
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.
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 バージョンでは、GRANT
と REVOKE
コ
マンドで、簡単に新しいユーザを追加でき、権限を変更することができます。
See section GRANT
と REVOKE
構文.
以下は SSH を用いてリモートの MySQL サーバに安全に接続するための 方法について述べたものです。 (by David Carlson dcarlson@mplcomm.com):
SecureCRT
from http://www.vandyke.com/.
Another option is f-secure
from http://www.f-secure.com/. You
can also find some free ones on Google
at
http://directory.google.com/Top/Computers/Security/Products_and_Tools/Cryptography/SSH/Clients/Windows/.
Host_Name = yourmysqlserver_URL_or_IP
.
Set userid=your_userid
to log in to your server (probably not the same
as your MySQL login/password.
local_port: 3306
, remote_host: yourmysqlservername_or_ip
, remote_port: 3306
)
or a local forward (Set port: 3306
, host: localhost
, remote port: 3306
).
localhost
for the MySQL host server@-not yourmysqlservername
.
You should now have an ODBC connection to MySQL, encrypted using SSH.
Windows 上では、3.23.16 以上のバージョンの MySQL ディストリビュー
ション中の mysqld-max
と mysql-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.
ソースファイル中で `mysql.h' をインクルードする前に `windows.h' を インクルードするべきです:
#if defined(_WIN32) || defined(_WIN64) #include <windows.h> #endif #include <mysql.h>
あなたのコードを、必要に応じて `libmysql.dll' 中でロードするための ラッパーである `libmysql.lib' ライブラリに動的にリンクすることも できますし、また `mysqlclient.lib' ライブラリを静的にリンクすることも できます。
mysqlclient ライブラリはスレッド対応ライブラリとしてコンパイル されていますので、あなたのコードもマルチスレッド対応になるように コンパイルするべきことに注意してください。
MySQL-Windows バージョンは現在それ自体とても安定した(stableな)状態で供給されています。 MySQL-win32 バージョンは すべての機能が UNIX バージョンの MySQL と対応しています。 ただし、下記のような例外があります。
mysqld
を実行させるべきではあり
ません!
WindowsNT と Windows98 はこのバグを持ちません。
INSERT
と SELECT
を混ぜることを可能にするために pread()
及び pwrite()
関数コールに依存します。現時点では pread()
/pwrite()
をエミュレートするために Mutex を用いています。長期的な計画では、
ファイルレベルのインターフェースを仮想インターフェースで置き換えて
いくつもりなので、さらに速度を上げるために Windows NT/2000/XP 上で
readfile()
/writefile()
インターフェースを使うことができます。
現在の実装は、しかし MySQL が利用可能なファイル数の上限が 1024 に
なっています。これは Unix では可能な数の並行スレッドを NT/2000/XP 上では
動作させることができないことを意味しています。
mysqladmin kill
は、スリープしている接続上では働かないはずです。
mysqladmin shutdown
は中断することができません。
DROP DATABASE
mysqladmin shutdown
で終了しなければなりません。
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
エラー
error 2017: can't open named pipe to host: . pipe...これは、MySQL のリリースバージョンがデフォルトで NT の 名前つきパイプを 使っているために起こっています。 新しい MySQL クライアントで
--host=localhost
オプションを用いるか、
以下の情報を含むオプションファイル `C:\my.cnf' を作成することで、このエラーを
回避することができます。
[client] host = localhostStarting from 3.23.50, named pipes are only enabled if
mysqld
is started
with --enable-named-pipe
.
Access denied for user
error
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
VIEW
s.
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:
MYSQL.DLL
server. This should include everything in
a standard MySQL server, except thread creation. This will make
MySQL much easier to use in applications that don't need a true
client/server and don't need to access the server from other hosts.
mysqld
をサービスとして --install
フラグで登録するとき、
コマンドラインにデフォルトオプションも一緒に追加できると素敵です。
差し当たって、 回避策は代わりに `C:\my.cnf' ファイル内のパラメータをリストすることです。
mysqld
を終了させることができればほんとうに親切でしょう。
今のところ、あなたは mysqladmin shutdown
を使わなければなりません。
mysql
のコマンドライン・ツールで使うために readline
をWindowsに移植しませんか?
mysql
、mysqlshow
、mysqladmin
、および、mysqldump
)のGUI
バージョンがあればいいでしょうねぇ。
mysqladmin kill
を用いて、オープンなスレッドを
kill することができるでしょう。
mysqld
はデフォルトロケールではなく、常に「C」ロケールで起動します。私たちは、
ソート順に関して mysqld
が現在のロケールを使用するようにしたいです。
他の Windows 特有の事柄は MySQL-Windows ディストリビューションに同梱されている `README' ファイルで説明されています。
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
-mt
を CFLAGS
と CXXFLAGS
に加えます。
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
これは以下のどれかで回避できます:
-Lpath
の代わりに):
-Wl,r/full-path-to-libmysqlclient.so
.
LD_RUN_PATH
environment variable before running your client.
configure や MySQL が -lz
のリンクを試み、あなたがそれを
インストールしていないという問題がある場合は、2つの選択肢があります:
--with-named-z-libs=no
をつけて configure を行ないます。
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.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 `;'
これを解決するには、以下のうち一つを行います:
CFLAGS=-DHAVE_CURSES_H CXXFLAGS=-DHAVE_CURSES_H ./configure
.
#define HAVE_TERM
行を `config.h' ファイルから消し、
make
を再実行します。
クライアントプログラムのリンク時に、リンカが -lz
を見つけられない
という問題が発生した場合、問題はおそらく `libz.so' ファイルが
`/usr/local/lib' にインストールされたことです。次の方法の一つでこれ
を修正できます:
LD_LIBRARY_PATH
に `/usr/local/lib' を追加
/lib
から libz.so
へのリンクを追加
--with-named-z-libs=no
オプション付きで MySQL を
configure する。
On Solaris 2.8 on x86, mysqld
will core dump if you run
'strip' in.
(訳注: GNU binutils を Sun 上で使用すると、CPU, version にかかわらず、
この現象に遭遇します。その場合は、/usr/ccs/bin/ の方を使います。)
gcc
か egcs
を 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.
This section provides information for the various BSD flavours, as well as specific versions within those.
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
.
To compile on NetBSD you need GNU make
. Otherwise, the compile will
crash when make
tries to run lint
on C++ files.
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
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
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.
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
.
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).
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.
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
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:
shell> /usr/sbin/swinstall -s /path/to/depot mysql.full
shell> /usr/sbin/swinstall -s /path/to/depot mysql.server
shell> /usr/sbin/swinstall -s /path/to/depot mysql.client
shell> /usr/sbin/swinstall -s /path/to/depot mysql.developer
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
.
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
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.
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.
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.
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
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.
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
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)
./configure
in the `threads/src' directory and select
the SCO OpenServer option. This command copies `Makefile.SCO5' to
`Makefile'.
make
.
cd
to the `thread/src' directory, and run make
install
.
make
when making MySQL.
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.
configure
command should work:
shell> ./configure --prefix=/usr/local/mysql --disable-shared
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:
mysqld
with -lgthreads -lsocket -lgthreads
.
malloc
. If you encounter problems with memory usage,
make sure that `gmalloc.o' is included in `libgthreads.a' and
`libgthreads.so'.
read()
,
write()
, getmsg()
, connect()
, accept()
,
select()
, and wait()
.
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
.
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.
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";
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.
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.
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-Dumper
、DBI
、及び、Msql-Mysql-modules
を入手してインストールしてください。
インストール手順は以下に示す通りです。なお、ここではData-Dumper
のみの手順が示されていますが、
他のモジュールについても同様な手順でインストールできます。
shell> gunzip < Data-Dumper-VERSION.tar.gz | tar xvf -This command creates a directory named `Data-Dumper-VERSION'.
shell> cd Data-Dumper-VERSION
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
.
という見出しの文書をご覧下さい。
DBD
モジュールとActiveState Perlをインストールするには以下の手順で行います。
set HTTP_proxy=my.proxy.com:3128
C:\> c:\perl\bin\ppm.pl
DBI
がインストールされていなければインストールします。
ppm> install DBI
install \ ftp://ftp.de.uu.net/pub/CPAN/authors/id/JWIED/DBD-mysql-1.2212.x86.ppd
以上で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";
MySQL Perlの配布パッケージにはDBI
、DBD:MySQL
、そして、DBD:ODBC
が含まれています。
C:
で配布パッケージを解凍してください。`C:\PERL'に必要なファイルが現れます。
perl -v
と入力してperl
の起動をチェックしてみましょう。
DBI
/DBD
InterfacePerl が "`../mysql/mysql.so'を見つけられない" というメッセージを出した場合、 それは多分 Perl のシェアードライブラリ `libmysqlclient.so' を見つけることが出来ないのでしょう。
これは以下のような方法で解決できます。
Msql-Mysql-modules
は通常、perl Makefile.PL
とコンパイルされますが、
perl Makefile.PL -static -config
とコンパイルしてください。
LD_RUN_PATH
に追加することによって
そこへのパスが追加されます。
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 モジュールを使用する際は
DBI
やDBD-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
で必要なコマンドを再確認することができます。
この章では、 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: ********
********
とかかれている部分にはあなたのパスワードを入れます;
mysql
が Enter 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>
プロンプトによって、それを示しています。
前のセクションで述べたように、あなたがサーバーとつながっていることを確かめて下さい。
この状態ではまだどんなデータベースも選択していない状態です。しかしそれはかまいません。
ここでは、テーブルの作成やデータの入力、取り出しよりも、
いかにクエリを発行するかに重点を置きます。
このセクションでは、あなた自身を 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
のいくつかの事を説明しています:
QUIT
はそのうちの一つです。後で他も出てきます。)
mysql
はそれをサーバーに送り、結果を表示します。
その後、 mysql>
プロンプトを出し、他のコマンドが受け付けれる状態であると
示します。
mysql
はクエリの結果を表にして出します。 最初の行は項目のラベル名です。
その下の行に、クエリの結果が続きます。 通常、項目のラベル名はデータベースのテーブルから
あなたが取り出したフィールド名になります。 テーブルのフィールド名以外の式を
あなたが検索したのなら(ちょうど例のように)、mysql
は与えられた式自身を
項目のラベル名として表示します。
mysql
は何レコード(rows)返ってきたかを示し、実行にどれくらいの時間が
かかったかも示します。 これはおおざっぱなサーバーのパフォーマンスを示します。
これらの値は wall clock time (CPU や マシンタイムではなく) を使用しており、さらに、
サーバーの負荷、およびネットワーク待ち時間といった要因にも影響されるので、
不正確です。
(この章の他の例題においては ``rows in set'' の行は省きます。)
キーワードは、いかなる大文字小文字でも記述できます。 以下に示すクエリは同じです:
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.
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 GRANT
と REVOKE
構文.
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.
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"
で表すことにしましょう。
birth
と death
のフィールドには、明らかに 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
文を用いるよりも相当多くのタイピングを要してしまうことがわかると思います。
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.
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:
DELETE
and LOAD DATA
:
mysql> SET AUTOCOMMIT=1; # Used for quick re-create of the table mysql> DELETE FROM pet; mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;However, if you do this, you must also re-enter the record for Puffball.
UPDATE
statement:
mysql> UPDATE pet SET birth = "1989-08-31" WHERE name = "Bowser";
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.
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 | +-------+--------+---------+------+------------+-------+
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 | +--------+---------+------------+
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
ならば、 death
と birth
の差の計算を行います:
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()
がいいでしょう。 これがどのように動くか確かめるには、
birth
と MONTH(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パターンを使用する場合、 =
や
!=
を使用しないように注意してください。 LIKE
か NOT 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 では他のパターン・マッチの形も提供されます。正規表現の拡張を使用して。
これらのパターン・マッチをテストする際には、REGEXP
と NOT 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 | +-------+--------+---------+------+------------+-------+
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 | +---------+------+----------+
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:
FROM
clause lists two tables because the query needs to pull
information from both of them.
name
column. The query uses
WHERE
clause to match up records in the two tables based on the
name
values.
name
column occurs in both tables, you must be specific
about which table you mean when referring to the column. This is done
by prepending the table name to the column name.
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
がそれらの情報を示します。
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 | +---------+--------+-------+
``What's the highest item number?''
SELECT MAX(article) AS article FROM shop +---------+ | article | +---------+ | 4 | +---------+
``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:
SELECT
statement.
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!
``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 | +---------+-------+
``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:
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.
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 | +---------+--------+-------+
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 | +----+-------+--------+-------+
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.
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.
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
に実行させます。
shell> mysql < batch-file | more
shell> mysql < batch-file > mysql.out
cron
ジョブとして実行する場合。 この場合、バッチモードでなければなりません。
mysql
コマンドに渡す場合。
たとえば、EUC-JP, Shift_JIS の漢字文字などは、端末や環境によっては直接入力できない場合もあるでしょう。
あるいは、文字コードの違う MySQL サーバーにデータを転送するときなども。
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;
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.
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
id
and tvab
in
numerical order. Adding 0
to the result causes MySQL to
treat the result as a number.
id
tvab
1
or 2
.
ptvab
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 |
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;
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 '\\'
mysqld
コマンド行オプション多くの場合、オプションファイルを通じて mysqld オプションを管理すべきです。 See section `my.cnf' オプションファイル.
mysqld
と mysqld.server
は mysqld
と server
グループからオプションを読み込みます。mysqld_safe
は
mysqld
, server
, mysqld_safe
, safe_mysqld
グ
ループからオプションを読み込みます。組み込み MySQL サーバは通常
server
, embedded
, xxxxx_SERVER
からオプションを読み
込みます。xxxxx
はアプリケーション名です。
mysqld
は次のコマンド行オプションを受け付けます。
完全なリストについては mysqld --help
を実行してください。
--ansi
-b, --basedir=path
--big-tables
--bind-address=IP
--console
--log-error
が指定されていても、エラーログメッセージを
stderr/stdout に書き出します。Windows mysqld はこのオプションが使用され
た場合はコンソールスクリーンをクローズしません。
--character-sets-dir=path
--chroot=path
mysqld
デーモンを chroot 下に置きます。
MySQL 4.0 からの推奨されるセキュリティ手法です。
(MySQL 3.23 は 100% クローズな chroot jail を提供できません)。
これは LOAD DATA INFILE
と SELECT ... INTO OUTFILE
を制限します。
--core-file
mysqld
が死んだ場合 core ファイルを書き出します。いくつかのシステム
では、--core-file-size
も safe_mysqld
に記述する必要がありま
す。
See section safe_mysqld
, The Wrapper Around mysqld
.
注意: Solaris のようないくつかのシステムでは、--user
オプションも
使用すると core ファイルを得られません。
-h, --datadir=path
--debug[...]=
--with-debug
つきで configure された場合、このオ
プション使用して、mysqld
が何を行なっているかのトレースファイルを得
ることができます
See section Creating Trace Files.
--default-character-set=charset
--default-table-type=type
--delay-key-write[= OFF | ON | ALL]
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)
--enable-named-pipe
-T, --exit-info
--flush
-?, --help
--init-file=file
-L, --language=...
-l, --log[=file]
--log-bin=[file]
--log-bin-index[=file]
--log-error[=file]
--log-isam[=file]
--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...]]]
DEFAULT
か BACKUP
か FORCE
か QUICK
の組み合わせ.
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 | 削除ブロックがない場合にテーブル内のレコードをチェック しません。 |
BACKUP,FORCE
を使用すべきです。いくつかのレコードが削除され
る場合でも、テーブルを強制的に修復しますが、古いデータファイルをバックアッ
プとして保存するため、あとで何が起こったか検証できます。
--pid-file=path
safe_mysqld
によって使用される pid ファイルのパス。
-P, --port=...
-o, --old-protocol
--one-thread
-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 GRANT
と REVOKE
構文。
--safe-user-create
mysql.user
テーブルやこのテーブル内の
任意のフィールドについて INSERT
権限を持っていない場合、そのユー
ザは GRANT コマンドで新しいユーザを作成できません。
--skip-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-privileges
や mysqladmin reload
を実行する
ことで、権限テーブルを使用して起動するように実行中のサーバに伝えることがで
きます。)
--skip-host-cache
--skip-innodb
--skip-external-locking (4.0.3から. 4.0.3より前では --skip-locking)
isamchk
または myisamchk
を使
用するためには、サーバをシャットダウンする必要があります。
See section MySQL はどれくらい安定か?。注意: MySQL バージョン 3.23 では、
REPAIR
と CHECK
を MyISAM
テーブルの修復/チェックに
使用できます。
--skip-name-resolve
Host
フィールド値は
IP 番号か localhost
でなければなりません。 See section How MySQL uses DNS.
--skip-networking
mysqld
との接続には
Unix ソケット経由で行なう必要があります。このオプションはローカル要求だけ
を許可するシステムでは、高く推奨されます。 See section How MySQL uses DNS.
--skip-new
--skip-symlink
--skip-safemalloc
--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
--transaction-isolation= { READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE }
SET TRANSACTION
構文。
-t, --tmpdir=path
/tmp
ディレクトリが一時テーブル
を保持するのに小さすぎるパーティション上にある場合に有用です。
MySQL 4.1 からは、このオプションはコロン :
(Windows ではセミコロン
;
)で区切られたいくつかのパスを受け付けます。これらはラウンドロビ
ン方法で使用されます。
-u, --user= [user_name | userid]
user_name
か userid
(数値) で 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
構文。
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時に決定されており、 --datadir
を
mysqld
起動時に指定しても変更されません。
(サーバーはコマンドラインの引数を処理する前にオプションファイルを探します。
よって、--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
への socket
と port
引
数だけです。
See section 同一マシン上に複数の 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_number
と file_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 サーバーに、 これまた違うポートを使用するように作られたクライアントから接続したい場合、 以下のようにします:
--host 'hostname' --port=port_numer
か
Unix ソケット経由での接続 [--host localhost] --socket=file_name
オプションで起動します。
--protocol=tcp
to connect with TCP/IP and
--protocol=socket
to connect via a Unix socket.
DBD::mysql
module you can read the options
from the MySQL option files. See section `my.cnf' オプションファイル.
$dsn = "DBI:mysql:test;mysql_read_default_group=client; mysql_read_default_file=/usr/local/mysql/data/my.cnf" $dbh = DBI->connect($dsn, $user, $password);
MYSQL_UNIX_PORT
と MYSQL_TCP_PORT
環境変数に Unix ソケットファイルと
TCP/IP のポート番号とセットし、クライアントを立ちあげます。
もし、このポート番号やソケットファイルを常に使用するのであれば、
`.login' ファイルかなにかに環境変数をセットするように書いておけばよいでしょう。
See section Environment Variables.
MySQL has an advanced but non-standard security/privilege system. This section describes how it works.
よくあるセキュリティの間違いを避けるために、インターネットに接続されたコン ピュータ上で 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
データベース内の
user
テーブルへのアクセスを与えないでください! 暗号化されたパスワー
ドは MySQL の本当のパスワードです。もしあなたが与えられたユーザに
ついて user
テーブルにリストされたパスワードを知ることができれば、
そのアカウントについてリストされたホストへアクセスすれば、あなたは簡単にそ
のユーザとしてログインできます。
GRANT
と REVOKE
コマンドは MySQL へのアクセスを制限するための物です。
必要以上の権限を誰にも与えないでください。
全てのホストに対して、何か出来るような許可を与えてはいけません。
Checklist:
mysql -u root
を行ってみます。
パスワードを尋ねられること無しにサーバへの接続ができる場合、問題があります。
どのユーザでも(root でなくても)、MySQL サーバに完全な権限で接続で
きます! root
パスワードの設定についての項目に特別な注意を払って
MySQL インストール説明を見直してください。
SHOW GRANTS
を使用し、だれがなんのアクセスを持つかチェックします。
必要ない権限を、REVOKE
コマンドを使用して削除してください。
MD5()
, SHA1()
や
他の one-way hashing 関数を使用してください。
(SHA1()
はバージョン4.0.2から。MD5()
はバージョン3.23.2から。)
nmap
のようなツールを使用して、
あなたのマシンのポートをスキャンしてみます。
MySQL はデフォルトで 3306 番を使用しています。
このポートには信用できないホストからはアクセスできないようにすべきです。
MySQL ポートがオープンしているかどうかをチェックする他の簡単な方
法は、次のコマンドをいくつかのリモートマシンから試すことです。ここで
server_host
はあなたの MySQL サーバのホスト名です:
shell> telnet server_host 3306接続し、いくつかのゴミ文字が得られた場合、ポートはオープンして います。それをオープンしておく正当な理由が本当にない限り、ファイアーウォー ルやルータでクローズすべきです。
telnet
がハングしたり拒否されたり
する場合、すべて OK です。ポートはブロックされています。
; DROP ALL DATABASES ;
のような文字を入力しても、
あなたのアプリケーションは安全ですか?
これは極端な例ですが、それらに対して準備しない場合、似たようなテクニックを
使用するハッカーの結果として、大きなセキュリティリークとデータ喪失が発生し
得ます。
数値データのチェックも忘れないでください。よくある間違いは文字列しか保護し
ないことです。時々、人はデータベースが保護される必要のない公に有効なデータ
だけを含んでいるかどうかを考えます。これは間違いです。少なくとも、
denial-of-service タイプのアタックはそのようなデータベースでも実行されます。
このタイプのアタックから保護するもっとも簡単な方法は、数値定数の回りにアポ
ストロフィを使用することです: SELECT * FROM table WHERE ID=234
の代
わりに SELECT * FROM table WHERE ID='234'
。 MySQL は自動的
にこの文字列を数値に変換し、そこからすべての非数値シンボルを取り除きます。
Checklist:
%22
(`"'), %23
(`#') , %27
(`'') をつけてみて、動的URLを
いろいろ変更して試してみてください。
addslashes()
function.
As of PHP 4.0.3, a mysql_escape_string()
function is available
that is based on the function of the same name in the MySQL C API.
mysql_real_escape_string()
API call.
escape
and quote
modifiers for query streams.
quote()
method or use placeholders.
PreparedStatement
object and placeholders.
tcpdump
と strings
ユーティリティを使うことを学んで下さい.
以下のコマンドで、ほとんどの場合、暗号化されていない
MySQL のデータが見えるでしょう:
shell> tcpdump -l -i eth0 -w - src or dst port 3306 | strings(この例は Linux のものです。他のシステムでは少し違うでしょう). 警告: データが見えなくても、実際に常に暗号化されているわけではありません。 高いセキュリティが必要なら、セキュリティエキスパートに相談すべきです。
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 システムを安全にするためには、次のことを考えるべきです:
other_user
にパスワードが設定されていない場合、
誰でも mysql -u other_user db_name
として簡単に他の人としてログインでき
ることを覚えてください。これは全てのクライアント/サーバアプリケーション
で一般的な振る舞いです。全てのユーザのパスワードは、
mysql_install_db
スクリプトを実行前に編集することで、または
MySQL root
ユーザだけは次のようにして変更することができます。
shell> mysql -u root mysql mysql> UPDATE user SET Password=PASSWORD('new_password') -> WHERE user='root'; mysql> FLUSH PRIVILEGES;
root
ユーザーで実行しないでください。
FILE
権限を持つ任意のユーザが root
としてファイル(例えば、
~root/.bashrc
)を生成できるためとても危険です。これを防ぐために、
mysqld
は、--user=root
オプションで直接指定されない限り、
root
としての実行を拒否します。
代わりに mysqld
は権限を持たない一般ユーザとして実行できます。
より安全にするため、新しく Unix ユーザ mysql
を追加することもできます。
mysqld
を 他の Unix ユーザーで起動したとしても、
MySQL の user
テーブルの root
ユーザーの名前を変更する必要はありません。
なぜなら、 MySQL ユーザーの名前は Unix のユーザー名とはなんの関係もないからです。
root ユーザ名を変更する必要はありません。
mysqld
を他の Unix ユーザで起動するためには、`/etc/my.cnf' オ
プションファイルまたはサーバのデータディレクトリの `my.cnf' オプショ
ンファイルの、[mysqld]
グループにユーザ名を記述した user
行
を追加してください。たとえば:
[mysqld] user=mysqlこれは、あなたが手動で起動したり
safe_mysqld
または
mysql.server
を使用して起動しても、指定されたユーザでサーバを起動さ
せます。詳細は、section 一般ユーザで MySQL を動かす方法. を見てください。
--skip-symlink
option). This is especially important if you run
mysqld
as root as anyone that has write access to the mysqld data
directories could then delete any file in the system!
See section Using Symbolic Links for Tables.
mysqld
を実行している Unix ユーザだけが
読み込み/書き込み可能なことをチェックしてください。
PROCESS
権限を全てのユーザに与えないでください。この許可がある人は誰でも
mysqladmin processlist
コマンドで実行されているクエリーの中身を見ることができます。
もし誰かが、UPDATE user SET password=PASSWORD('not_secure')
クエリーを
実行していたとして、それが見えてしまいます。
mysqld
は PROCESS
権限を持つユーザに対する特別な接続をリザーブします。
そのため、たとえ全ての通常接続が使われたとしても、MySQL root
ユーザだけは、
ログインでき、いろいろチェックできます。
FILE
権限を全てのユーザに与えないでください。ユーザがこの権限を持つ場合、
mysqld
デーモンを実行している Unix ユーザーの権限で
ファイルシステム内のどこにでもファイルを書き込むことができます!
これを少し安全にするため、SELECT ... INTO OUTFILE
で作成される全てのファイルは
全員が書き込み可能な状態で生成されますが、
既存のファイルを上書きすることができないようになっています。
FILE
権限はサーバーを走らせている Unix ユーザーがアクセスできる
全てのファイルを読むために使用されかもしれません。
いかなるファイルもカレントのデータベースに取りこめます。
例えば、 LOAD DATA
を使用して `/etc/passwd' をテーブルに
取り込むと、SELECT
でその内容が読めることになります。
mysqld
への --secure
オプションは原理上はホスト名を安
全にします。どんな場合でも、ワイルドカードを含んだホスト名を、許可テーブルに登録する
事は本当に注意深くすべきです!
mysqld
の
max_user_connections
変数を設定することで、これを行なうことができま
す。
mysqld
の起動オプション
mysqld
の次のオプションはセキュリティに影響します:
--local-infile[=(0|1)]
--local-infile=0
then one can't use LOAD DATA LOCAL
INFILE
.
--safe-show-database
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 GRANT
と REVOKE
構文.
--safe-user-create
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-privileges
か mysqladmin reload
を実行することで、
起動しているサーバーは特権システムを使用するようになります。)
--skip-name-resolve
Host
フィールドは IP アドレスか
localhost
でなければなりません。
--skip-networking
mysqld
への全ての接続は、
Unix ソケットで行われます。MIT-pthreads は Unix ソケットをサポートしない
ため、このオプションは MIT-pthreads を使用するシステム上で MySQL
3.23.27 以前のバージョンを使用する場合は、うまく動きません。
--skip-show-database
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.
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 のアクセスコントロールは以下の二つからなります:
SELECT
権限があるのか、
データベースに対して DROP
する許可が与えられているのか、を確認します。
サーバーは 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_priv
と columns_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
テーブルの Host
と User
に
'thomas.loc.gov'
と 'bob'
が登録されている場合、
サーバーへの接続は ホスト thomas.loc.gov
から来た 'bob'
に許可されます。
同様に、db
テーブルの Host
, User
, Db
に
'thomas.loc.gov'
, 'bob'
, 'reports'
が登録されていると、
ホスト thomas.loc.gov
から来た bob
に対し reports
データベースへの接続が許されます。
tables_priv
と columns_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_priv
と columns_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'
|
サーバーは以下のように権限テーブルを使用します:
user
テーブルのスコープフィールドは、接続要求を受け入れるか拒否するかを決定します。
許可された接続について、user
テーブルで与えられたすべての権限は、ユー
ザのグローバル(スーパーユーザ)権限を示します。この権限はサーバ上の
すべての データベースに適用されます。
(訳注:
例えば、user
テーブル の権限を 'Y'
にした場合、
どんなに db
テーブルや host
テーブルで権限を 'N'
にしたとしても
権限は 'Y'
のままである。
つまり user
テーブルの権限許可 'Y'
が全てに反映されてしまうという事。
user
テーブルには最低限の許可を与えるようにし、
db
テーブルや host
テーブルで、それぞれの権限を許可する方が無難。
)
db
と host
テーブルは一緒に使用されます:
db
テーブルのスコープフィールドはどのホストからどのデータベースのアクセスできるかを決定します。
権限フィールドは、どういった操作ができるかを定義します。
host
テーブルは、db
テーブルの登録をいくつかのホストに与えたい時に、
db
テーブルの拡張として使用されます。
例えば、ネットワーク上の限定したマシンからデータベースを使用したい場合、
db
テーブルの Host
の値は空にしておきます。
そして host
テーブルにそれぞれのホストについての登録を行います。
この機構は、 section Access Control, Stage 2: Request Verification で詳細に述べられています。
tables_priv
と columns_priv
テーブルは db
テーブルに似ていますが、
それらはより細かく定義できます;
データベースレベルではなく、テーブルとフィールドのレベルで与えます。
管理者権限 (RELOAD
, SHUTDOWN
,など) は user
テーブルにだけ定義するように。
これは、管理者操作はデータベースではなくサーバーへの操作であり、
他の許可テーブルにある必要がないからです。
またこうしておくと、管理者操作の許可は、user
テーブルの定義だけを
見ればわかるようになります。
FILE
操作の権限は user
テーブルにだけ定義するように。
これは管理者操作ではありませんが、アクセスしているデータベースにかかわらず、
サーバー内のファイルを読み書きできるのです。
mysqld
サーバーは起動時にこれらのテーブルを読み込みます。
許可テーブルの変更を反映させる方法はこちらを参照のこと → section いつ権限の変更が反映されるか
これらのテーブルの登録を変更した場合、思ったとおりの権限状態になっている事を確認することはいいことです。
問題の解決には, section 何故 Access denied
エラーになるのか. セキュリティに関するアドバイスは
section MySQL をクラッカーに対して安全にする方法.
便利なツールとして mysqlaccess
スクリプト( Yves Carlier 作)が MySQL の配布に含まれています。
mysqlaccess
を --help
オプションで起動するとヘルプが表示されます。
mysqlaccess
は user
,db
and host
テーブルだけしか
検査しません。テーブルレベルの権限、フィールドレベルの権限は調べません。
権限の設定は 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
の実行を許可します。
CREATE
と DROP
権限は、新しいデータベースやテーブルの作成、
あるいは既に存在するデータベース、テーブルの破棄(削除)を許可します。
注意: mysql
データベースに登録されているユーザーに DROP
権限を与えると、
そのユーザーは MySQL のアクセス権限が格納されているデータベースを破棄できます!
GRANT
権限は、あなたが他のユーザーに対して自分の権限を持たせる事を許可します。
FILE
権限を与えると、LOAD DATA INFILE
と SELECT ... 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-privileges
は reload
と同義です。
その他の flush-*
コマンドは refresh
の動作とよく似ていますが、
適用範囲を絞っており、ちょっとした場合に有効です。
例えば、ログファイルだけをフラッシュしたい場合、
refresh
を行うよりも flush-logs
がいいです。
shutdown
コマンドは、サーバーをシャットダウンします。
processlist
コマンドはサーバーが実行しているスレッドの情報を表示します。
kill
コマンドはサーバーのスレッドをkillします。
自分のスレッドは常に表示、killできますが、他人のスレッドを見るには
PROCESS
権限が必要で、他人のスレッドをkillするには
SUPER
権限が必要です。See section KILL
構文.
(SUPER
権限は 4.0.2で追加されました)
ある権限を欲しがるユーザーだけにその権限を許可するのはよい考えですが、 権限を与えるときには、特定の事項を熟知していなければなりません:
GRANT
権限を許可されたユーザーは、他のユーザーの権限を変える事ができます。
二人のユーザー間で違っている権限と grant
権限を入れ換えることができます。
ALTER
権限は、テーブル名の変更を行うことにより特権システムを破るために
使用されるかもしれません。
FILE
権限は、サーバー上にある全ての読み込み可能なファイルと
カレントのデータベースのディレクトリにあるファイルを、
データベースのテーブルに取り込むことができ、
その内容は SELECT
文を使用することでアクセスできます。
SHUTDOWN
権限は、他のユーザーに対するサービスを、サーバーを
停止することによって、拒否するようにできます。
PROCESS
権限は実行されているクエリーをプレーンテキストで見ることに使えます。
パスワードの設定、変更のクエリーも含みます。
mysql
データベースに対しての権限は、パスワードの変更や他の権限の変更に、使用されます。
(パスワードは暗号化されて登録されており、悪意のあるユーザーでも
単純に読むことはできません).
mysql.user
のパスワードフィールドにアクセスできれば、それを使用して
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
コマンドはコマンドラインに引数がなければ接続にデフォルト値を用います。
localhost
.
-p
が指定されていなければパスワードは与えられません
Unix のログインユーザーが joe
の場合、以下のコマンドは等価です:
shell> mysql -h localhost -u joe shell> mysql -h localhost shell> mysql -u joe shell> mysql
他の MySQL クライアントも同じように動作します。
Unix システムでは、ある値をデフォルト値にして接続に使用することができます。 そうすることにより、毎回毎回コマンドラインに引数を与えなくてすむようになります:
[client]
セクションに接続用のパラメターを記述できます。
その記述は以下のようになります:
[client] host=host_name user=user_name password=your_passSee section `my.cnf' オプションファイル.
MYSQL_HOST
環境変数を使用します。
MySQL のユーザー名は USER
(これは Windows のみ) に設定された値を使用します。
パスワードは MYSQL_PWD
環境変数を見ますが、これは危険です。(次の節参照)
See section Environment Variables.
MySQL サーバーに接続すると、あなたがパスワード認証して接続していようがいまいが、 サーバーはあなたの身元により接続の許可拒否を行います。 もし身元が一致しない場合接続を拒否し、接続許可した場合、 サーバーは Stage 2 へと進み、要求を待ちます。
身元は二つのものに基づいて確認されます:
身元の確認は user
テーブルのスコープフィールド
(Host
, User
, Password
) を使用して行います。
サーバーは user
テーブルの登録に一致しているホスト名と
ユーザー名に限り接続を許可し、その後、パスワードを要求します。
user
テーブルのスコープフィールドの登録は以下のようになります:
Host
の値はホスト名か IP アドレスか 'localhost'
(ローカルホスト) です。
Host
、Db
フィールドにはワイルドカード文字 `%' と `_' を使用できます。
If you wish to use for instance a
`_' character as part of a database name, specify it as `\_' in
the GRANT
command.
Host
に '%'
を設定すると、全てのホストにマッチします。
Host
値は、権限が host
テーブル内の与えられたホスト名に
適合するエントリと AND されることを意味します。次の章にこれについての詳し
い情報を見つけられます。
Host
値には、何
ビットがネットワークアドレスに使用されるかを示すネットマスクを記述すること
ができます。例えば:
mysql> GRANT ALL PRIVILEGES ON db.* -> TO david@'192.58.197.0/255.255.255.0';これは、次が真になる IP からの接続をすべて許可します:
user_ip & netmask = host_ip.上記の例では、192.58.197.0〜192.58.197.255 のすべての IP が MySQL サーバに接続できます。
User
フィールドには設定できませんが、
User
フィールドをブランク(空)にすることはできます。ブランクは全ての名前にマッチします。
これはユーザー名がない状態で接続してきたものに適用され、
クライアントがユーザー名を明記しない限り、匿名ユーザー(名前がブランク)として扱われます。
全てのアクセスのチェックにブランクのユーザー名が使用される事を意味します。
(that is, during Stage 2).
Password
フィールドは空にできます。
これは、いかなるパスワードにもマッチするという意味ではなくて、
パスワードなして接続できるということになります。
非ブランクの 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
テーブルの Host
と User
の設定例です:
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.gov
の fred
からの接続は、上に示された
登録のうちのいくつかにマッチするでしょう。
サーバーは、複数の登録にマッチした場合、どのようにしてその中から
使用する登録を選ぶのでしょう?
サーバーは起動後に user
テーブルをソートし、並び換えられた順に
登録を検索することにより、この問題を解決します。
最初にマッチした登録が使用されます。
user
テーブルが以下のようにソートされていた場合:
+-----------+----------+- | Host | User | ... +-----------+----------+- | % | root | ... | % | jeffrey | ... | localhost | root | ... | localhost | | ... +-----------+----------+-
サーバーがこのテーブルを読むと、Host
に値が最も確実に特定できる
ホストを指定しているエントリを、最初に参照します。
(Host
項の '%'
は ``すべてのホスト'' を意味し、
ホスト名をはっきりと特定しているものではありません)
Host
の値が同じエントリがあった場合、もっとも明確に User
の値が
ユーザーを指定しているエントリを最初に参照します。
(User
の値が空の場合、``だれでも'' を意味します)
この結果、user
テーブルは以下のようにソートされます:
+-----------+----------+- | Host | User | ... +-----------+----------+- | localhost | root | ... | localhost | | ... | % | jeffrey | ... | % | root | ... +-----------+----------+-
接続が試みられた場合、サーバーは並び換えられた登録を探し、最初に見つけたものを
使用します。
'localhost'
の jeffrey
からの接続は、まず最初に Host
に
localhost
を設定しているエントリにマッチします。
ユーザー名が空のエントリは、ホスト名とユーザー名の両方を指定した接続にもマッチします。
( '%'/'jeffrey'
エントリもマッチします。が、これは最初にはマッチしません。)
もう一例。user
が以下の設定と仮定します:
+----------------+----------+- | Host | User | ... +----------------+----------+- | % | jeffrey | ... | thomas.loc.gov | | ... +----------------+----------+-
これは次のようにソートされます:
+----------------+----------+- | Host | User | ... +----------------+----------+- | thomas.loc.gov | | ... | % | jeffrey | ... +----------------+----------+-
thomas.loc.gov
の jeffrey
からの接続は、最初のエントリにマッチし、
whitehouse.gov
の jeffrey
からの接続は、二つ目のエントリにマッチします。
よくある考え違いは、ユーザー名を与えて接続した場合、
サーバーが接続にマッチするものを探す際に、
そのユーザー名が指定されているルールが
最初に使用されるだろうと考えることです。これは正しくありません。
前の例でこれを示しましたが、thomas.loc.gov
の jeffrey
からの接続が
最初にマッチするのは、 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 その他の関数.
一度接続か確立されると、サーバーはステージ2に移ります。
このステージでは、サーバーはこの接続から来るそれぞれの要求が許可されて
いるかどうかをチェックします。
チェックは実行しようとしている操作のタイプにより行います。
その操作が許可テーブルのどの権限フィールドに当てはまるかを見ます。
これら権限は user
, db
,host
, tables_priv
か
columns_priv
テーブルより導出されます。
権限テーブルは GRANT
, REVOKE
コマンドで操作します。
See section GRANT
と REVOKE
構文. (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
フィールドだけに使用できます。
'%'
Host
値は ``あらゆるホスト'' を意味します。
db
テーブルの Host
に空を設定すると、``さらに host
テーブルに許可情報を探しにいく''
となります。
'%'
か 空値を Host
テーブルに設定すると、それは ``あらゆるホスト'' となります。
'%'
か 空値を host
テーブルの Db
フィールドに設定すると、
それは ``あらゆるデータベース'' となります。
User
を空値にすると、匿名ユーザーにマッチします。
サーバー起動時に、db
テーブルと host
テーブルはサーバーに読み込まれます。
(user
テーブルもこの時に同時に読まれます)
db
テーブルは Host
, Db
, User
のフィールドでソートされ、
host
テーブルは Host
, Db
フィールドでソートされます。
user
テーブルは、一番特定できるエントリを最初に、一番特定できないものを最後にソートします。
サーバーはソートされたものの中から、最初にマッチしたものを使用します。
tables_priv
と columns_priv
テーブルは、
特定のテーブルとフィールドに対する権限を許可します。
スコープフィールドの値は、いかにそって記述されます:
Host
フィールドに使用できます。
Host
値を '%'
かブランクにすると、
``any host.'' を意味します。
Db
, Table_name
, Column_name
フィールドはどのテーブルにも
ワイルドカードやブランクは使用できません。
tables_priv
と columns_priv
テーブルは
Host
, Db
, User
フィールドで並び換えられます。
これは db
テーブルのソートに似ていますが、 Host
フィールドだけが
ワイルドカードを含むので、ソートはより単純なものになります。
この要求の承認は次のようにして行います。 もしアクセス承認を決定する部分のソースコードを理解できるなら、 ちょっと変わったアルゴリズムで承認の決定を行っている事に気づくでしょう。
管理者の要求(SHUTDOWN
, RELOAD
, etc.)については、サーバーは
user
テーブルだけを参照します。(user
テーブルだけが管理者権限のフィールドを持つ)。
エントリに許可登録されている操作は受け入れられ、それ以外は拒否されます。
例えば、mysqladmin shutdown
を実行しようとしても、
user
テーブルの SHUTDOWN
権限が許されていなければ実行できません。
この時、db
と host
テーブルはチェックされません。
(これらのテーブルには Shutdown_priv
フィールドが無いからです)
データベースへの要求 (INSERT
, UPDATE
, etc.) において、
サーバーはまず最初に、ユーザーのグローバルな権限(スーパーユーザー)を
user
の中から探しだします。
もし許可が与えられていれば、アクセスは成功します。
user
テーブルのグローバルな権限の設定が不十分であるなら、
サーバーはユーザーのデータベースに対する権限を db
テーブルと
host
テーブルから決定します:
db
テーブルの Host
,Db
,User
フィールドを参照します。
Host
と User
フィールドはユーザーの接続時のホスト名と MySQL ユーザー名にマッチします。
Db
フィールドはユーザーがアクセスしたいデータベース名にマッチします。
Host
と User
にマッチするものが無かった場合、アクセスは拒否されます。
db
テーブル内の Host
フィールドが空でないエントリにマッチした場合、
ユーザーの指定されているデータベースに対する権限が定義されます。
Host
フィールドが空値の db
テーブルのエントリにマッチした場合、
どのホストがそのデータベースへアクセスできるかを host
テーブルから探し出します。
この場合、host
テーブル の Host
, Db
フィールドとマッチするものを探し出します。
host
テーブルにエントリがなかった場合、アクセスは拒否されます。
もしマッチすると、ユーザーの特定データベースに対する権限は、
host
テーブルと db
テーブル両方にまたがった権限から割り出されます。
いうならば両方とも 'Y'
である権限。
(この方法を使用すると、まず db
テーブルのエントリに大まかな権限を設定しておき、
それから host
テーブルのエントリを使用して、ホスト情報もとに権限を限定していくという事ができます)
特定データベースに対する権限が db
テーブルと host
テーブルのエントリから決定された後、
サーバーはその割り出された権限に対し、user
テーブルて設定されている権限を加えます。
この結果から得られた権限にマッチした要求は受け入れられます。
そうでなければ、サーバーはユーザーのテーブル、フィールドに対する許可を、
tables_priv
と columns_priv
内に探します。
アクセスはこの結果により、許可、拒否されます。
先のユーザーの権限が計算される方法の記述は、boolean 表記で示すならば、 以下のようになるでしょう:
global privileges OR (database privileges AND host privileges) OR table privileges OR column privileges
これは少し分かりにくいかもしれません。もしグローバルの user
エントリ
権限許可が、リクエストされたオペレーションには不十分だと最初に分かった際、
サーバーがこれらの権限を database-, table-, column-固有の権限の
後に、なぜ、追加してしまうのか。
その理由は、リクエストが1個以上の権限を要求するだろうということです。
例えば、もしあなたが INSERT ... SELECT
構文を実行するなら、
あなたには INSERT
と SELECT
権限が必要です。
あなたの権限が、 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_install_db
を実行して
許可テーブルを初期化しましたか?
していなければ実行してください。See section MySQL 権限許可の初期設定
権限許可のテーブルが初期化されているかを試すには以下のようにします:
shell> mysql -u root testThe server should let you connect without error. You should also make sure you have a file `user.MYD' in the MySQL database directory. Ordinarily, this is `PATH/var/mysql/user.MYD', where
PATH
is the
pathname to the MySQL installation root.
shell> mysql -u root mysql初期状態では、MySQL に
root
ユーザーをパスワードなしで登録しているので、
問題なく接続できるはずです。
しかしこれはセキュリティ上危険な状態なので、
他の MySQL ユーザーを登録している時に、
root
のパスワードを設定しておいてください。
もし root
で接続しようとして以下のエラーが出た場合:
Access denied for user: '@unknown' to database mysqlこれは
user
テーブルに、 User
フィールド = root
かつ
mysqld
がリゾルブできなかったホスト名で、クライアントが登録されていないからです。
この場合、 `/etc/hosts' ファイルあるいは `\windows\hosts' ファイルを編集して
ホスト名を追加し、--skip-grant-tables
オプションでサーバーをリスタートします。
shell> mysqladmin -u root -pxxxx ver Access denied for user: 'root@localhost' (Using password: YES)これは間違ったパスワードを使用したことを意味します。 See section パスワードの設定法. root のパスワードを忘れた場合、
mysqld
を
--skip-grant-tables
で再起動して、パスワードを変更することができま
す。See section 忘れたパスワードをリセットする.
パスワードを指定してないのに、上のエラーがでた場合は、my.ini
ファイ
ルに間違ったパスワードがあることを意味します。See section `my.cnf' オプションファイル. このオ
プションファイルは、次のように --no-defaults
オプションで回避できま
す:
shell> mysqladmin --no-defaults -u root ver
mysql_fix_privilege_tables
スクリプトを実行しましたか?
実行していないなら、このエラーになります。
許可テーブルの構造が MySQL バージョン 3.22.11 から変更され、
GRANT
構文が機能しています。
INSERT
, UPDATE
, SET PASSWORD
構文でパスワードを設定するとき
PASSWORD()
関数を使用しなければならないことを思い出してください。
しかし PASSWORD()
関数は、GRANT ... INDENTIFIED BY
構文や
mysqladmin password
コマンドでは不要です。
See section パスワードの設定法.
localhost
はローカルのホスト名です。
もしクライアントがホストを指定せずに接続してきた場合、localhost
がデフォルトで使用されます。
しかし、 MIT-pthreads を使用している場合、localhost
への接続は失敗します。
(localhost
への接続は、Unixソケットを使用しますが、 MySQL 3.23.27 未満では
MIT-pthreads が ソケット接続をサポートしていないためです。)
この問題が起きるシステムでは、サーバー名を指定するために --host
オプションを使用すべきです。
これは TCP/IP 接続を使用して mysqld
サーバーに接続します。
この場合、user
テーブルに、サーバーの実ホスト名を登録しておかなくてはなりません。
(これはクライアントプログラムをサーバーと同じホスト上で動かしている場合真となります)
例えば、Using password: NO
を含むエラーメッセージを得た場合、これは
パスワードなしでログインしようとしたことを意味します。
mysql -u user_name db_name
を使用してデータベースに接続しているときに
Access denied
エラーが発生した場合、user
テーブルの設定違いが考えられます。
mysql -u root mysql
を実行し、以下の SQL 文を試してください:
mysql> SELECT * FROM user;
Host
と User
にあなたのコンピュータ名と
MySQL ユーザー名にマッチする登録がなされていなければなりません。
Access denied
エラーは、どのユーザーで接続してきたか、
どのホストから接続しようとしているか、パスワードを使用しているのかをメッセージに出力します。
通常、エラーになっているホスト名とユーザー名がマッチするエントリが
user
テーブルに一つはなければなりません。
For example if you get an error
message that contains Using password: NO
, this means that you
tried to login without an password.
user
テーブルにあなたがアクセスしているホストにマッチする行がありません:
Host ... is not allowed to connect to this MySQL server
mysql
コマンドをサーバーのホスト上で使用して、
user
, db
, host
テーブルに接続しようとしている
ユーザー名/ホスト名 を加えて、mysqladmin flush-privileges
を
実行すれば解決できるでしょう。
もしサーバーが MySQL バージョン 3.22 ではなく、接続しようとしている
ホストの IP もホスト名もわからない場合、
user
テーブルの Host
フィールドに '%'
を設定し、
mysqld
を --log
オプションで再起動してください。
そしてクライアントホストから接続すれば、MySQL のログファイルに
そのホストの情報が記録されているはずです。
それがわかれば、先に設定した user
テーブルの Host
フィールドの '%'
を
ログに記録されたホスト名に置き換えます。(しかしこれはシステムを危険にさらします)
Linux 上でこのエラーの他の原因は、あなたの使用しているのと異なる glibc バー
ジョンでコンパイルされた、バイナリ MySQL バージョンを使用している
ことを意味します。この場合、あなたの OS/glibc をアップグレードするか、ソー
ス MySQL バージョンをダウンロードしてコンパイルすべきです。ソース
RPM は、通常コンパイルとインストールは簡単なので、これは大きな問題ではあり
ません。
shell> mysqladmin -u root -pxxxx -h some-hostname ver Access denied for user: 'root@' (Using password: YES)これは MySQL が IP をホスト名に解決しようとした時に何かエラーを得 たことを意味します。この場合、
mysqladmin flush-hosts
を実行して、内
部の DNS キャッシュをリセットできます。 See section How MySQL uses DNS.
いくつかの永久的な解決策は:
--skip-name-resolve
で mysqld
を起動する。
--skip-host-cache
で mysqld
を起動する。
localhost
に
接続する。
/etc/hosts
にクライアントマシン名を書く。
mysql -u root test
は動いたものの mysql -h your_hostname -u root test
が
Access denied
を返した場合、
user
テーブルに正しいホスト名が使用されていないと思われます。
user
テーブルの Host
フィールドにホスト名を確定できる形で指定していないか、
使用しているシステムのリゾルブが FQDN (or vice-versa) を返しているかだと思われます。
例えば、user
テーブルに 'tcx'
ホストの定義があったとして、
DNS が MySQL に 'tcx.subnet.se'
をホスト名として返した場合、
これは動きません。
user
テーブルの Host
フィールドの値に、あなたのホストの IP 番号を加えてください。
(user
テーブルの Host
の値にワイルドカードを使用することができます。'tcx.%'
のように。
しかしホスト名の値を `%' 文字で終わらせる設定は、安全ではなく、推奨されません)
mysql -u user_name test
が動作し mysql -u user_name other_db_name
が
動作しない場合は、db
テーブルに other_db_name
のエントリが
登録されていません。
mysql -u user_name db_name
はサーバー上では動作するが、
mysql -u host_name -u user_name db_name
がクライアントホスト上で動作しない場合、
user
テーブルか db
テーブルにクライアントホストの名前が登録されていません。
Access denied
の原因がもし上記に当てはまらない場合は、
user
テーブルから Host
にワイルドカードを使用しているエントリを
全て消去してみてください。(`%' や `_' を含む値です)
よくある間違いは、localhost
に対して localhost
と同じマシン上から
の接続を許可すると考えて
Host
='%'
と User
='some user'
を登録することです。
これは動きません。なぜなら、デフォルトの権限に
Host
='localhost'
と User
=''
が含まれているからです。
Host
の値が 'localhost'
の場合、これは '%'
よりも
具体的に指定されているので、localhost
からの接続にはこちらの方が
使用されるのです! 正しい指定の仕方は、二番目の登録として
Host
='localhost'
と User
='some_user'
を追加するか、
あるいは、Host
='localhost'
と User
=''
を削除することです。
db
か host
テーブルに問題があるのかもしれません。:
Access to database deniedもし
db
テーブルに Host
フィールドが空の登録がある場合には、
host
テーブル中に、db
テーブルに登録されている
ホストを明記した物が一つ以上あるかどうかを確認してください。
もし SELECT ... INTO OUTFILE
や LOAD DATA INFILE
SQL 文を
使用している時にこのエラーが出る場合、
user
テーブルのあなたの登録に FILE
権限が
許可されていないと思われます。
Access denied
がでるなら、
オプションファイルに古いパスワードが書かれているか確認してください。
See section `my.cnf' オプションファイル.
INSERT
または UPDATE
ステートメントを使用して
)直接変更する場合、あなたの変更は無視されたように見えます。サーバに権限テー
ブルを再読み込みさせるために、FLUSH PRIVILEGES
ステートメントの発行
か、mysqladmin flush-privileges
コマンドの実行の必要があることを忘
れないでください。そうでないと、あなたの変更は次回のサーバ再起動まで効果が
ありません。UPDATE
コマンドで root
パスワードを設定後、権限
をフラッシュするまでそれを指定する必要がありません。サーバはまだパスワード
を変更したことを知らないからです!
mysql -u user_name db_name
または mysql -u user_name
-pyour_pass db_name
でサーバへの接続を試してください。mysql
クライ
アントを使用して接続できれば、アクセス権でなく、あなたのプログラムに問題が
あります。(-p
とパスワードの間に空白がないことに注意してください;
パスワードを指定するのに、--password=your_pass
構文も使用できます。
単に -p
オプションを使用すると、MySQL はパスワードの入力を
求めます。)
mysqld
デーモンを --skip-grant-tables
オプショ
ン付きで開始してください。MySQL 権限テーブルを変更し、あなたの変
更が望む効果があるかどうかのチェックに、mysqlaccess
スクリプトを使
用できます。あなたの変更が満足できた時に、mysqladmin
flush-privileges
を実行し、mysqld
サーバに新しい権限テーブルを使用
して開始するように伝えてください。注意: 権限テーブルのリロードは
--skip-grant-tables
オプションを上書きします。これは、サーバを落と
して再起動することなしに、権限テーブルの使用を始めるようにサーバに伝えるこ
とができます。
mysqld
デーモンをデバッグオプションで起動してください。
例えば、--debug=d,general,query
。これはコネクションに試みたホストやユーザーの情報、
また実行したコマンドを表示します。 See section Creating Trace Files.
mysqldump mysql
コマンドでダンプできます。
いつものように、 mysqlbug
スクリプトでポストしてください。See section バグや問題を報告する方法.
ときには、 mysqldump
を実行するために、
mysqld
を --skip-grant-tables
オプションで実行しないと
いけないかもしれません。
GRANT
と REVOKE
構文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
ステートメントは何も行ないません。
GRANT
と REVOKE
コマンドセットの主な目的は、システム管理者
がユーザを生成すること、MySQL ユーザに次の4つの権限レベルの権
利を与えたり取り消すことをできるようにすることです:
mysql.user
テーブル内に格納されます。
mysql.db
テーブルと mysql.host
テーブル内に格納されます。
mysql.tables_priv
テーブル内に格納されます。
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 へ追加.
GRANT
と REVOKE
ステートメントにおいて 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
コマンドで削除されるまでそこに残ります。
いうならば GRANT
は user
テーブルの登録を作りますが、
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
開始時、全ての権限はメモリに読み込まれます。データベース、
テーブル、フィールド権限は一度効果を得ます。ユーザレベル権限はユーザ再接続時に
効果を得ます。
これらの許可テーブルを GRANT
や REVOKE
を使って変更しても
サーバーにはすぐに反映されません。
もしこれらの許可テーブルを手動で変更した場合(INSERT
, UPDATE
, 等で変更した場合)、
FLUSH PRIVILEGES
構文を実行するか、mysqladmin flush-privileges
を実行して
サーバーに許可テーブルの再読み込みを行わせなくてはなりません。
See section いつ権限の変更が反映されるか.
The biggest differences between the ANSI SQL and MySQL versions of
GRANT
are:
TRIGGER
or UNDER
privileges.
INSERT
privilege on only some of the
columns in a table, you can execute INSERT
statements on the
table; the columns for which you don't have the INSERT
privilege
will be set to their default values. ANSI SQL requires you to have the
INSERT
privilege on all columns.
ANSI SQL
で権限を取り消す場合、この権限に基づいて承認され
た全ての権限も取り消されます。MySQL
では、全ての権限は明示的な
REVOKE
コマンドまたは MySQL 権限テーブルの操作によっての
み破棄されます。
For a description of using REQUIRE
, see section Using Secure Connections.
MySQL によって使用されるユーザー名とパスワードの使用のされ方と、 Unix, Windows で使用される方法とは、いくつか異なる点があります。
-u
か --user
スイッチで変更できます。
これは、全てのユーザに対しパスワードを設定しておかないと、
全くデータベースを安全にできないことを意味します。
もしパスワードを全ユーザーに設定しておかないと、そのユーザー名で認証なしにサーバーに接続できます。
PASSWORD()
と ENCRYPT()
関数の説明を参照 → section その他の関数.
注意: パスワードが '暗号化' されて格納されていても、あなたの '暗号化' され
たパスワードを知ることで、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.
MySQL ユーザーと彼らの権限は通常 GRANT
コマンドで作成されます。
See section GRANT
と REVOKE
構文.
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
コマンドを実行して、
サーバーに許可テーブルの読み込みを指示しなければなりません。
そうしなければ、サーバーを再起動させるまで、変更は反映されません。
権限テーブルを手で変更して、権限のリロードを忘れた場合、変更が何も行なわれ
ないように見えるのがなぜかと不思議に思うでしょう!
サーバーが許可テーブルの変更を通知した場合、既に接続している クライアントは、以下のような影響を受けます:
USE db_name
コマンド以降から
有効になります。
MySQL インストール後、scripts/mysql_install_db
を
実行して権限のアクセス許可を初期化します。
See section 素早いインストールの概要.
mysql_install_db
スクリプトは mysqld
サーバーを起動し、
以下のように権限を初期化してテーブルに登録します:
root
ユーザーはスーパーユーザーとして登録され、
全ての操作ができます。
localhostからしか接続できません。
注意:
root
のパスワードの初期値は空です。
全ての人が パスワードなしで root
になれ、全ての権限許可を得ることができます。
'test'
あるいは 'test_'
で名前がはじまっているデータベースに対して、
匿名ユーザーでもなんでもできるように許可が与えられます。
これは ローカルホストからの全てのユーザーは パスワード無しで接続ができ、
匿名ユーザーとして扱われるということです。
mysqladmin shutdown
や
mysqladmin processlist
を実行できません。
注意: デフォルトの権限は 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 配布からコピーしなおさ
なくてはなりません。
ユーザーは2つの違った方法で追加できます:
GRANT
構文を使用して行う方法と、
MySQL の許可テーブルを直接操作する方法とです。
The
preferred method is to use GRANT
statements, because they are
more concise and less error-prone. See section GRANT
と REVOKE
構文.
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
'some_pass'
を
使用する必要があります。
monty@localhost
と monty@"%"
の両方に GRANT
構文を
発行しなくてはならない事に注意してください。
もし localhost
からの許可をした登録がないと、localhost
から接続した時、
mysql_install_db
が自動で作成した localhost
への匿名ユーザーが優先されます。
なぜなら、 Host
フィールドの値が(ブランクやワールドカード以外に)明記されており、
許可登録が MySQL 内部でソートされる時に順番が上にソートされるからです。
admin
localhost
からパスワードなしで接続できますが、reload
, process
の使用だけが許されます。
これは、mysqladmin reload
, mysqladmin refresh
, mysqladmin flush-*
そして
mysqladmin processlist
コマンドの実行がこのユーザーに許可されます。
データベースへのアクセスは許可されていません。
しかしこれは後でテーブル GRANT
構文を発行すれば、
個々のデータベースへのアクセス権限が設定できます。
dummy
'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'
にするだけでかまいません。
db
や host
テーブルに登録は必要無いのです。
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;
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 GRANT
と REVOKE
構文.
前節の例で述べた、とても重要な基本原則:
INSERT
か UPDATE
で空ではないパスワードを設定する場合、
暗号化するために 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 ユーザ名とパスワード.
自分のパスワードを他人にさらけ出すのは勧められることではありません。 それぞれの方法に於ける危険度に応じ、以下に示す方法でクライアントプログラムに あなたのパスワードをあたえて走らせることができます:
mysql.user
テーブルへのアクセスを与えてはいけません。
ユーザの暗号化されたパスワード知ることで、そのユーザとしてログインが可能に
なります。パスワードは、使用される本当のパスワードを見ることができないよう
に、スクランブルされているだけです(同じようなパスワードを他のアプリケーショ
ンでたまたま使用する場合のため)。
-pyour_pass
か --password=your_pass
オプションをコマンドラインで使用します。
これは便利ですが安全ではありません。あなたのパスワードは (ps
コマンドのような)
システムの状態を見るコマンドにて見ることができます。
(MySQL クライアントは初期化過程においてコマンドラインの引数をゼロで上書きして
見せないようにしているのですが、瞬間ですが値が見えてしまうのです)
-p
あるいは --password
オプションを your_pass
を与えないで使用します。
この場合、クライアントプログラムはターミナルを通じてパスワードの入力を促してきます:
shell> mysql -u user_name -p Enter password: ********`*' 文字はパスワードを表しています。 これはコマンドラインにパスワードを指定するより安全です。他のユーザーには見えませんから。 しかしこのパスワードを毎回入れる方法は対話式のプログラムを実行する場合だけに使用できる手です。 もし非対話式のスクリプトからクライアントプログラムを起動したい場合、 パスワードを端末から入れる機会がありません。 On some systems, you may even find that the first line of your script is read and interpreted (incorrectly) as your password!
[client]
セクションに、以下のような形で書きます:
[client] password=your_passもし `.my.cnf' ファイルにパスワードを書いているなら、ファイルはグループや その他のユーザーが読み書きできないようにすべきです。ファイルのモードは
400
か 600
にします。
See section `my.cnf' オプションファイル.
MYSQL_PWD
環境変数にパスワードを設定することもできます。しかしこの方法は
きわめて危険であるので、使用すべきではありません。
ps
のあるバージョンでは、実行中のプロセスの環境変数を表示するオプションがあります;
もし MYSQL_PWD
環境変数にパスワードを設定していると全てべたで見れます。
このバージョンの ps
を持っていないシステムだとしても、プロセスの環境変数を調べる
方法がないとはいえないので、この方法はあまりいい方法ではありません。
See section Environment Variables.
まとめると、より安全な方法は、 パスワードプロンプトを返すクライアントプログラムを実行するか、 適切なパーミッションをかけた `.my.cnf' ファイルにパスワードを書くか です。
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.
To get secure connections to work with MySQL you must do the following:
--with-vio --with-openssl
で MySQL をコンフィギャ.
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
か
他の方法でバックアップしておきましょう。
)
mysqld
が OpenSSL をサポートしている場合は、
SHOW VARIABLES LIKE 'have_openssl'
が YES
を返します。
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:
REQUIRE SSL
オプションは、サーバーに対して、
SSL 接続のみを許可します。
もし、非SSL接続を許可する ACL (アクセス・コントロール・リスト)の
レコードが存在する場合、このオプションは除かれることに注意してください。
mysql> GRANT ALL PRIVILEGES ON test.* TO root@localhost -> IDENTIFIED BY "goodsecret" REQUIRE SSL;
REQUIRE X509
は、クライアントが有効な証明書を持っていることを
意味しますが、しかし、
正確(的確,厳密)な certificate、issuer、subject を持っているかについては、
留意していません。
唯一の制限は、CA 証明書のシグネチャが正しいかを確かめることです。
mysql> GRANT ALL PRIVILEGES ON test.* TO root@localhost -> IDENTIFIED BY "goodsecret" REQUIRE X509;
REQUIRE ISSUER issuer
はコネクションをより制限します:
クライアントは CA 局から発行される有効な X509 証明書を
持っていなければなりません。
X509 証明書を使う事は、常に 暗号化を暗に意味します。
そのため、SSL
オプションはこの場合は必要ではありません。
mysql> GRANT ALL PRIVILEGES ON test.* TO root@localhost -> IDENTIFIED BY "goodsecret" -> REQUIRE ISSUER "C=FI, ST=Some-State, L=Helsinki, "> O=MySQL Finland AB, CN=Tonu Samuel/Email=tonu@mysql.com";
REQUIRE SUBJECT "subject"
はクライアントにたいして、
"subject"
をサブジェクトに持つ、有効な X509 証明書を要求します。
もしクライアントが正当な certificate を持っていても
"subject"
が違うものであれば、コネクションは許可されません。
mysql> GRANT ALL PRIVILEGES ON test.* TO root@localhost -> IDENTIFIED BY "goodsecret" -> REQUIRE SUBJECT "C=EE, ST=Some-State, L=Tallinn, "> O=MySQL demo client certificate, "> CN=Tonu Samuel/Email=tonu@mysql.com";
REQUIRE CIPHER "cipher"
is needed to assure enough strong ciphers
and keylengths will be used. SSL itself can be weak if old algorithms
with short encryption keys are used. Using this option, we can ask for
some exact cipher method to allow a connection.
mysql> GRANT ALL PRIVILEGES ON test.* TO root@localhost -> IDENTIFIED BY "goodsecret" -> REQUIRE CIPHER "EDH-RSA-DES-CBC3-SHA";以下のようにして、これらのオプションは組み合わせることが可能です: The
SUBJECT
, ISSUER
, and CIPHER
options can be
combined in the REQUIRE
clause like this:
mysql> GRANT ALL PRIVILEGES ON test.* TO root@localhost -> IDENTIFIED BY "goodsecret" -> REQUIRE SUBJECT "C=EE, ST=Some-State, L=Tallinn, "> O=MySQL demo client certificate, "> CN=Tonu Samuel/Email=tonu@mysql.com" -> AND ISSUER "C=FI, ST=Some-State, L=Helsinki, "> O=MySQL Finland AB, CN=Tonu Samuel/Email=tonu@mysql.com" -> AND CIPHER "EDH-RSA-DES-CBC3-SHA";Starting from MySQL 4.0.4 the
AND
keyword is optional between
REQUIRE
options.
オプションの指定順序はといません。
しかし同じオプションを二重に使用できません。
違うオプションのみが、組み合わせ可能です。
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 OUTFILE
か
BACKUP TABLE
を使用できます。
See section BACKUP TABLE
構文 (3.23.25以上).
他の方法は mysqldump
プログラムか
mysqlhotcopy スクリプト
を使用することです。
See section mysqldump
, データベースとテーブルから、構造とデータをダンプ.
See section mysqlhotcopy
, Copying MySQL Databases and Tables.
shell> mysqldump --tab=/path/to/some/dir --opt --all or shell> mysqlhotcopy database /path/to/some/dirYou 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.
mysqld
を止め、そして --log-update[=file_name]
オプションをつけて起動します。
See section 更新ログ. ログファイルは、 mysqldump
実行後に行われたデータベースの変更を
複製するための情報を与えてくれます。
もしリストアをしなければならない場合、まず最初に REPAIR TABLE
か
myisamchk -r
を実行してテーブルの修復を試みてください。
ほとんどの場合、99.9% 修復はできるはずです。
もし myisamchk
が失敗した場合、以下のようにします:
(this will only work if you have started MySQL with
--log-update
, see section 更新ログ):
mysqldump
バックアップデータをリストアします。
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 KEY
か UNIQUE
が必要です。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:
FLUSH TABLES WITH READ LOCK
.
mount vxfs snapshot
.
UNLOCK TABLES
.
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 TABLE
は MyISAM
テーブル と 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
で
あるべきです。OK
や Table 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
チェックを行ないます。清適サイズレコードでは、レコードはめっ
たに壊れないので、QUICK
と FAST
ではレコードスキャンをスキッ
プします。
チェックオプションは次のように組み合わせられます:
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:
Found row where the auto_increment column has the value 0
.
This means that you have in the table a row where the
AUTO_INCREMENT
index column contains the value 0.
(It's possible to create a row where the AUTO_INCREMENT
column is 0 by
explicitly setting the column to 0 with an UPDATE
statement)
This isn't an error in itself, but could cause trouble if you decide to
dump the table and restore it or do an ALTER TABLE
on the
table. In this case the AUTO_INCREMENT
column will change value,
according to the rules of AUTO_INCREMENT
columns, which could cause
problems like a duplicate key error.
To get rid of the warning, just execute an UPDATE
statement
to set the column to some other value than 0.
REPAIR TABLE
構文 (3.23.14以上)REPAIR TABLE tbl_name[,tbl_name...] [QUICK] [EXTENDED] [USE_FRM]
REPAIR TABLE
は MyISAM
テーブルだけで動作します。テーブルに
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
--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:
--safe-recover
.
CHAR
, VARCHAR
or TEXT
keys as the
sort needs to store the whole keys during sorting. If you have lots
of temporary space and you can force myisamchk
to repair by sorting
you can use the --sort-recover
option.
-s or --silent
-s
を指定すると(-ss
)、myisamchk
は
ほとんど出力をしなくなります。
-v or --verbose
-d
と -e
オプションと共に使用できます。
-v
を複数指定すると(-vv
, -vvv
)、もっと出力が多くなります!
-V or --version
myisamchk
バージョンを表示して終了。
-w or, --wait
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
myisamchk
や myisamchk --medium-check
は、
このオプションなしで全てのエラーを見つけるはずです。
多くのメモリがマシンにあるなら、--extended-check
を使用する際には
key_buffer_size
の値を多く増やします。
-F or --fast
-C or --check-only-changed
-f or --force
myisamchk
with -r
(repair) on the table, if
myisamchk
finds any errors in the table.
-i or --information
-m or --medium-check
-U or --update-state
--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
myisamchk
to check a table that is in use by some other application that doesn't
use locking (like mysqld --skip-external-locking
).
以下のオプションは myisamchk
を -r
か -o
オプションで
実行した場合に使用できます:
-D # or --data-file-length=#
-e or --extend-check
-f or --force
table_name.TMD
) instead of aborting.
-k # or keys-used=#
#
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
-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
-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
myisamchk
to use sorting to resolve the keys even if the
temporary files should be very big.
--character-sets-dir=...
--set-character-set=name
-t or --tmpdir=path
myisamchk
は
TMPDIR
環境変数の値をこのパスとします。
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
-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
myisamchk --describe --verbose table_name'
or using SHOW KEYS
in
MySQL.
-d or --description
-A or --set-auto-increment[=value]
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
-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
の使用は多くの場合おそらく十分でしょう。
しかし、myisamchk
は TMPDIR
内に一時ファイルを使用します。
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:
--quick
, as in this
case only the index file will be re-created. This space is needed on the
same disk as the original record file!
--recover
or --sort-recover
(but not when using --safe-recover
), you will need space for a
sort buffer for:
(largest_key + row_pointer_length)*number_of_rows * 2
.
You can check the length of the keys and the row_pointer_length with
myisamchk -dv table
.
This space is allocated on the temporary disk (specified by TMPDIR
or
--tmpdir=#
).
If you have a problem with disk space during repair, you can try to use
--safe-recover
instead of --recover
.
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
.
To check a MyISAM table, use the following commands:
myisamchk tbl_name
myisamchk
without options or
with either the -s
or --silent
option.
myisamchk -m tbl_name
myisamchk -e tbl_name
-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
-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以上).
テーブル破壊の兆しとして、クエリが予期せず中断したり、以下のようなエラーが出たり します:
perror ###
. Here
is the most common errors that indicates a problem with the table:
shell> perror 126 127 132 134 135 136 141 144 145 126 = Index file is crashed / Wrong file format 127 = Record-file is crashed 132 = Old database file 134 = Record was already deleted (or record file crashed) 135 = No more room in record file 136 = No more room in index file 141 = Duplicate unique key or constraint on write or update 144 = Table is crashed and last repair failed 145 = Table was marked as crashed and should be repairedNote that error 135, no more room in record file, is not an error that can be fixed by a simple repair. In this case you have to do:
ALTER TABLE table MAX_ROWS=xxx AVG_ROW_LENGTH=yyy;
この他の場合、あなたは自分のテーブルを修理しなければなりません。
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''の意)。
これはデータファイルに触れないでインデックスファイルの修理を試みます。
もしデータファイルが全てとデータファイル中の正しい場所での削除リンクポイントを
含んでいるなら、これは動作してテーブルを修復します。
成功後、次のテーブルの修復に進んでください。
失敗した場合は、以下の手順で試みてください:
myisamchk -r tbl_name
を使用します(-r
は ``recovery mode''の意)。
これは不正なレコードと削除されたレコードをデータファイルから消去し、
インデックスファイル(.MYI)を再構築します。
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 ブロックが破壊された場合、 または不正な情報を含む場合、またはインデックスファイルがない場合にだけ、 本修復段階を経ます。 この場合、新しいインデックスファイルファイルを作成する必要があります。 次のようにしてください:
shell> mysql db_name mysql> SET AUTOCOMMIT=1; mysql> TRUNCATE TABLE table_name; mysql> quitIf your SQL version doesn't have
TRUNCATE TABLE
, use DELETE FROM
table_name
instead.
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)もクラッシュした場合にだけ発生します。 これは発生することはありません。なぜならディスクリプタファイルは テーブルが生成された後に書かれることはないからです。
myisamchk -r
で開始すべきです。
断片化されたレコードの結合と、
レコードの削除と更新から生じる無駄なスペースの排除、
これら行うには、修復モード(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
には、あなたがテーブルの性能を向上させるのに使用することができる
他の多くのオプションがあります:
-S
, --sort-index
-R index_num
, --sort-records=index_num
-a
, --analyze
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
を ``describe mode'' で実行し、テーブルの説明記述を作ります。
--skip-external-locking
(ver.4.0.3未満では--skip-locking
) を指定して
MySQL サーバーを起動した場合、
myisamchk
は myisamchk 実行中に更新されたテーブルについてエラーを報告します.
しかし myisamchk
は describe mode ではテーブルを変えないので、
データを破壊する危険性はありません。
myisamchk
がしていることに関する、より多くの情報を作り出すには、
-v
をつけて冗長モードで走らせるようにします。
-eis
と似ているが、何を行っているかを表示します。
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'' は同義です。
Data records
と同じです。
.MYD
ファイル) が獲得できる長さ (バイト数)。
.MYI
ファイル) が獲得できる長さ (バイト数)。
Fixed length
を使用します。
他の値で可能な物は圧縮
、パック
します。
unique
or multip.
(multiple). このインデックス内では1つの値が複数
回存在し得ます。
packed
, stripped
か empty
オプションを持ちます。
myisamchk -a
で更新されます。これ
が全く更新されない場合はデフォルト値の 30 が与えられます。
myisamchk
で再配置
されるため、値はとても高くなります (理論的な最大にとても近くなります)。
CHAR
/VARCHAR
/DECIMAL
キーでだけ使用できます。名前の
ような長い文字列では、これは使用領域を顕著に減らします。上の三番目の例では4番目
のキーが10文字長で、領域の60%の減少を得ます。
Packed
は示します。
myisamchk
でテーブルを再配置
できます。
See section テーブルの最適化.
Linkdata
は
そのポインタの全ての合計です。
テーブルが pack_isam
で圧縮されているなら、myisamchk -d
は
それぞれのテーブルコラムに関する追加情報を出力します。
section myisampack
, MySQL の圧縮された読み込み専用テーブルジェネレータ. を参照してください。
この情報例と説明記述の意味があります。
OPTIMIZE TABLE
構文OPTIMIZE TABLE tbl_name[,tbl_name]...
OPTIMIZE TABLE
は、テーブルの大部分を削除したり、可変長となっているテーブ
ル(VARCHAR
、BLOB
もしくはTEXT
フィールドを持つテーブル)に多く
の変更を加えた場合に使用すべきです。
削除されたレコードはリンクリストで維持され、次のINSERT
操作は、古いレコー
ド位置を再利用します。
未使用領域を再生するためにOPTIMIZE TABLE
を使用することができます。
今のところ、OPTIMIZE TABLE
は MyISAM
と BDB
テーブ
ル上でだけ動作します。BDB
テーブルでは、OPTIMIZE TABLE
が現
在 ANALYZE TABLE
にマップされます。
See section ANALYZE TABLE
Syntax.
--skip-new
または --safe-mode
で mysqld
を起動するこ
とで、他のテーブル型で OPTIMIZE TABLE
を動作するようにできます。しかし、こ
の場合 OPTIMIZE TABLE
は ALTER TABLE
にマップされるだけです。
OPTIMIZE TABLE
は次の方法で動作します:
MyISAM
テーブルの OPTIMIZE TABLE
はテーブル上で
myisamchk --quick --check-changed-tables --sort-index --analyze
を
実行することと同等です。
注意: テーブルは OPTIMIZE TABLE
実行中はロックされます!
ANALYZE TABLE
SyntaxANALYZE 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 processlist
と mysqladmin 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.
SELECT
, ORDER BY
and GROUP BY
loops, the flag is
checked after reading a block of rows. If the kill flag is set, the
statement is aborted.
ALTER TABLE
the kill flag is checked before each block of
rows are read from the original table. If the kill flag was set the command
is aborted and the temporary table is deleted.
UPDATE
or DELETE
, the kill flag
is checked after each block read and after each updated or deleted
row. If the kill flag is set, the statement is aborted. Note that if you
are not using transactions, the changes will not be rolled back!
GET_LOCK()
will abort with NULL
.
INSERT DELAYED
thread will quickly flush all rows it has in
memory and die.
Locked
),
the table lock will be quickly aborted.
write
call, the
write is aborted with an disk full error message.
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 ワイルドカード
(`%' と `_') です。
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 TABLES
や mysqlshow db_name
の要求で
表示されません。
SHOW OPEN TABLES
はテーブルキャッシュに現在オープン去れているテーブ
ルを一覧表示します。See section MySQL はどのようにテーブルのオープン & クローズを行なうか?. Comment
フィールドはテーブ
ルが何回 cached
と in_use
になったかを知らせます。
SHOW COLUMNS
は与えられたテーブルのフィールドを表示します。
FULL
オプションを指定した場合、各フィールドに持つ権限も得られます。
もしそのフィールドの型が、あなたが CREATE TABLE
構文実行時に与えたものと
違う場合は、 MySQL は、フィールドの型をときおり変更することが
あることに注意してください。 See section 暗黙のフィールド定義変更.
DESCRIBE
文は SHOW COLUMNS
と似たような情報を提供します。
See section DESCRIBE
構文 (フィールドについての情報を得る).
SHOW FIELDS
は SHOW COLUMNS
の別名として使用され、
SHOW KEYS
は SHOW INDEX
の別名として使用されます。
テーブルのフィールドやインデックスは mysqlshow db_name tbl_name
か mysqlshow -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 STATUS
は mysqladmin 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 | サーバーが走っている秒数 |
上についてのいくつかコメント:
Opened_tables
が大きければ、 table_cache
変数が小さすぎる
のでしょう。
Key_reads
が大きければ、 key_buffer_size
が少なすぎるでしょう。
キャッシュ ミス レート は
Key_reads
/Key_read_requests
で計算できます。
Handler_read_rnd
is big, then you probably have a lot of
queries that require MySQL to scan whole tables or you have
joins that don't use keys properly.
Threads_created
is big, you may want to increase the
thread_cache_size
variable. The cache hit rate can be calculated
with Threads_created
/Connections
.
Created_tmp_disk_tables
is big, you may want to increase the
tmp_table_size
variable to get the temporary tables memory-based
instead of disk based.
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メガバイトを示します。大文字小文字の区別はなく、
16M
と 16m
は同じ意味になります。
ansi_mode
.
もし mysqld
が --ansi
オプションで起動されているなら、ON
.
See section Running MySQL in ANSI Mode.
back_log
MySQL が持てる未解決の接続要求の数です。これは MySQL
スレッドがものすごく多くの接続要求をとても短い時間に得た時に、働き
ます。接続のチェックと新しいスレッドの開始はメインスレッドにすこし時間
(しかしほんのわずか)がかかります。back_log は、MySQL が瞬間的に新
しい要求への回答を停止する前に、この短い時間の間にスタックできる接続数です。
短い期間に多くの接続を期待する場合にだけ、これを増加する必要があります。
いいかえるなら、これは TCP/IP 接続の入力 listen キューのサイズです。
オペレーティングシステムはこのキューの大きさを制限しています。
UNIX システムコール listen(2)
のマニュアルページに、さらに詳細があります。
この値を最大限にしたい場合、お使いのOSのドキュメントを見てください。
back_log
をこのOSの制限値より多く取ってもは全く効果ありません。
basedir
The value of the --basedir
option.
bdb_cache_size
The buffer that is allocated to cache index and rows for BDB
tables. If you don't use BDB
tables, you should start
mysqld
with --skip-bdb
to not waste memory for this
cache.
bdb_log_buffer_size
The buffer that is allocated to cache index and rows for BDB
tables. If you don't use BDB
tables, you should set this to 0 or
start mysqld
with --skip-bdb
to not waste memory for this
cache.
bdb_home
The value of the --bdb-home
option.
bdb_max_lock
The maximum number of locks (10,000 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.
bdb_logdir
The value of the --bdb-logdir
option.
bdb_shared_data
Is ON
if you are using --bdb-shared-data
.
bdb_tmpdir
The value of the --bdb-tmpdir
option.
binlog_cache_size
. The size of the cache to hold the SQL
statements for the binary log during a transaction. If you often use
big, multi-statement transactions you can increase this to get more
performance. See section BEGIN/COMMIT/ROLLBACK
構文.
bulk_insert_buffer_size
(was myisam_bulk_insert_tree_size
)
MyISAM uses special tree-like cache to make bulk inserts (that is,
INSERT ... SELECT
, INSERT ... VALUES (...), (...), ...
, and
LOAD DATA INFILE
) faster. This variable limits
the size of the cache tree in bytes per thread. Setting it to 0
will disable this optimisation.
Note: this cache is only used when adding data to non-empty table.
Default value is 8 MB.
character_set
The default character set.
character_sets
The supported character sets.
concurrent_inserts
もし ON
(これはデフォルトです) なら、MySQL は、
SELECT
クエリが実行されている MyISAM
テーブルに対して、
同時に INSERT
が使用できるようにします。
このオプションは mysqld
のオプションに --safe
か --skip-new
を
指定することで OFF
にできます。
connect_timeout
mysqld
サーバーが接続パケットを待つ秒数。 (Bad handshake
を返すま
での秒数)
datadir
The value of the --datadir
option.
delay_key_write
Option for MyISAM tables. Can have one of the following values:
OFF | All CREATE TABLE ... DELAYED_KEY_WRITES are ignored. |
ON | (デフォルト) MySQL は CREATE TABLE 文の
DELAY_KEY_WRITE オプションを尊重します。
|
ALL | 開かれている全てのテーブルが DELAY_KEY_WRITE オプション指定されて
作成されたものとして扱われる
|
DELAY_KEY_WRITE
オプションが有効な場合、テーブルのキーバッファは、
毎回のインデックスの更新にはフラッシュされず、ただテーブルが閉じられたときにだけ
フラッシュされます。 これはキーの書き出しを速くしますが、もしこれを使用するなら、
全てのテーブルを myisamchk --fast --force
で自動的に検査するようにすべき
です。
delayed_insert_limit
delayed_insert_limit
個のレコードを挿入した後、 INSERT DELAYED
ハンドラーは待たされている SELECT
文がないかチェックします。 もしあるなら、
挿入を続ける前にそれらの実行を許します。
delayed_insert_timeout
どれぐらい INSERT DELAYED
スレッドが INSERT
文を待つべきか。
delayed_queue_size
What size queue (in rows) should be allocated for handling INSERT
DELAYED
. If the queue becomes full, any client that does INSERT
DELAYED
will wait until there is room in the queue again.
flush
This is ON
if you have started MySQL with the --flush
option.
flush_time
これがもし、非ゼロにセットされたなら、毎 flush_time
秒ごとに
全てのテーブルが閉じられます。 (リソースの解放とDiskへのsyncのために)
We
only recommend this option on Windows 9x/Me, or on systems where you have
very little resources.
ft_boolean_syntax
List of operators supported by MATCH ... AGAINST(... IN BOOLEAN MODE)
.
See section MySQL Full-text Search.
ft_min_word_len
The minimum length of the word to be included in a FULLTEXT
index.
Note: FULLTEXT
indexes must be rebuilt after changing
this variable. (This option is new for MySQL 4.0.)
ft_max_word_len
The maximum length of the word to be included in a FULLTEXT
index.
Note: FULLTEXT
indexes must be rebuilt after changing
this variable. (This option is new for MySQL 4.0.)
ft_max_word_len_for_sort
The maximum length of the word in a FULLTEXT
index
to be used in fast index recreation method in REPAIR
,
CREATE INDEX
, or ALTER TABLE
. Longer words are inserted the
slow way. The rule of the thumb is as follows: with
ft_max_word_len_for_sort
increasing, MySQL will create bigger
temporary files (thus slowing the process down, due to disk I/O), and will put
fewer keys in one sort block (again, decreasing the efficiency). When
ft_max_word_len_for_sort
is too small, instead, MySQL will insert a
lot of words into index the slow way, but short words will be inserted very
quickly.
ft_stopword_file
The file to read the list of stopwords for fulltext search from.
All the words from the file will be used, comments are not honored.
By default, built-in list of stopwords is used
(as defined in `myisam/ft_static.c').
Setting this parameter to an empty string (""
) will disable
stopword filtering.
Note: FULLTEXT
indexes must be rebuilt after changing
this variable. (This option is new for MySQL 4.0.10)
have_innodb
YES
if mysqld
supports InnoDB tables. DISABLED
if --skip-innodb
is used.
have_bdb
YES
if mysqld
supports Berkeley DB tables. DISABLED
if --skip-bdb
is used.
have_raid
YES
if mysqld
supports the RAID
option.
have_openssl
YES
if mysqld
supports SSL (encryption) on the client/server
protocol.
init_file
サーバー起動時に、--init-file
オプションに与えたファイルの名前です。
このファイルには、サーバー起動時に実行したい SQL 文を書いておきます。
interactive_timeout
The number of seconds the server waits for activity on an interactive
connection before closing it. An interactive client is defined as a
client that uses the CLIENT_INTERACTIVE
option to
mysql_real_connect()
. See also wait_timeout
.
join_buffer_size
このバッファは(インデックス無しの)完全な結合に使用されます。それは2つの
テーブル間の完全な結合ごとに1回割り当てられます。インデックスの追加がで
きない時、より速い完全な結合を得るために、これを増加してください。通常、
速い結合を得る一番良い方法は、インデックスを追加することです。
key_buffer_size
インデックス・ブロックはバッファされ、そして全てのスレッドに共有されます。
key_buffer_size
はインデックス・ブロックのためのバッファ・サイズです。
Increase this to get better index handling (for all reads and multiple
writes) to as much as you can afford; 64M on a 256M machine that mainly
runs MySQL is quite common. If you, however, make this too big
(for instance more than 50% of your total memory) your system may start
to page and become extremely slow. Remember that because MySQL does not
cache data reads, you will have to leave some room for the OS
filesystem cache.
You can check the performance of the key buffer by doing SHOW
STATUS
and examine the variables Key_read_requests
,
Key_reads
, Key_write_requests
, and Key_writes
. The
Key_reads/Key_read_request
ratio should normally be < 0.01.
The Key_write/Key_write_requests
is usually near 1 if you are
using mostly updates/deletes but may be much smaller if you tend to
do updates that affect many at the same time or if you are
using DELAY_KEY_WRITE
. See section SHOW
構文.
To get even more speed when writing many rows at the same time, use
LOCK TABLES
. See section LOCK TABLES/UNLOCK TABLES
構文.
language
The language used for error messages.
large_file_support
If mysqld
was compiled with options for big file support.
locked_in_memory
If mysqld
was locked in memory with --memlock
log
If logging of all queries is enabled.
log_update
If the update log is enabled.
log_bin
If the binary log is enabled.
log_slave_updates
If the updates from the slave should be logged.
long_query_time
もしあるクエリがこの値(秒)より時間がかかれば、Slow_queries
カウンター
が増やされます。
If you are using --log-slow-queries
, the query
will be logged to the slow query logfile. This value is measured in real
time, not CPU time, so a query that may be under the threshold on a lightly
loaded system may be above the threshold on a heavily loaded one.
See section The Slow Query Log (3.23.28以上).
lower_case_table_names
If set to 1 table names are stored in lowercase on disk and table
name comparisons will be case-insensitive.
From version 4.0.2, this option also applies to database names.
See section 名前のケース依存性.
max_allowed_packet
一つのパケットの最大サイズ。メッセージバッファは net_buffer_length
バイト
に初期化されますが、
max_allowed_packet
まで大きくすることができます。このデフォルト値は、
大きなパケット、間違ったパケットをを受けるには小さい値です。
大きな BLOB
を使用している場合は、これを増加する必要があります。使用した
い最大の BLOB
と同じくらい大きくするべきです。
The protocol limits for max_allowed_packet
is 16M in MySQL
3.23 and 1G in MySQL 4.0.
max_binlog_cache_size
If a multi-statement transaction requires more than this amount of memory,
one will get the error "Multi-statement transaction required more than
'max_binlog_cache_size' bytes of storage".
max_binlog_size
バージョン 3.23.33 以降より有効.
もしバイナリ(レプリケーション)ログファイルの大きさが、これに指定された数を
超えて書かれてしまった場合、ログファイルが自動でローテートされます。
1024<=max_binlog_size
<=1GB までの
範囲の値しか与えれません。デフォルトは 1GB です。
max_connections
許される同時クライアントの数。これを増加する場合は、mysqld
が持つファイ
ルディスクリプタの数を増やす必要があるでしょう。
後述のファイルデスクリプターの制限の説明を参照のこと。 See section Too many connections
エラー.
max_connect_errors
もしあるホストからの接続中断がこの値を以上になった場合、これ以後、
そのホストからの接続を拒絶します。FLUSH HOSTS
コマンドで
ホストの拒否を解除できます。
max_delayed_threads
この値を超えて INSERT DELAYED
を扱うスレッドを起動できません。
もし全ての INSERT DELAYED
スレッドが使用されていて、さらに新しいテーブルに
データを挿入しようとすると、そのレコードは DELAYED
が与えられていない
場合と同様に挿入されます。
max_heap_table_size
Don't allow creation of heap tables bigger than this.
max_join_size
max_join_size
より多いレコードを触るとエラーが返ります。長い時間をかけて
百万行を返すような WHERE
なしの結合を作成するようなユーザを持って
いる場合にこれを設定してください。
max_sort_length
BLOB
または TEXT
項目上でソートする時に使用するバイト数。
(最初の max_sort_length
バイトだけがそれぞれの値で使用でき、残りは無視さ
れます)
max_user_connections
The maximum number of active connections for a single user (0 = no limit).
max_tmp_tables
(このオプションはまだなにも行いません).
クライアントが同時にオープンできるテーブル数の最大値。
max_write_lock_count
After this many write locks, allow some read locks to run in between.
myisam_recover_options
The value of the --myisam-recover
option.
myisam_sort_buffer_size
The buffer that is allocated when sorting the index when doing a
REPAIR
or when creating indexes with CREATE INDEX
or
ALTER TABLE
.
myisam_max_extra_sort_file_size
.
If the temporary file used for fast index creation would be bigger than
using the key cache by the amount specified here, then prefer the key
cache method. This is mainly used to force long character keys in large
tables to use the slower key cache method to create the index.
Note that this parameter is given in megabytes before 4.0.3 and
in bytes starting from this version.
myisam_max_sort_file_size
The maximum size of the temporary file MySQL is allowed to use
while recreating the index (during REPAIR
, ALTER TABLE
or LOAD DATA INFILE
. If the file-size would be bigger than this,
the index will be created through the key cache (which is slower).
Note that this parameter is given in megabytes before 4.0.3 and
in bytes starting from this version.
net_buffer_length
通信バッファがクエリ間でこのサイズにリセットされます。これは通常は変更す
べきではありませんが、とても小さなメモリしかない場合は、これを期待される
クエリのサイズに設定してください。
( これは、クライアントから送られてくるSQL文の長さ分あればいいでしょう。
もし構文がこの値をこえた場合、バッファは自動的に大きくなります。
ただし max_allowed_packet
バイトまでです)
net_read_timeout
Number of seconds to wait for more data from a connection before aborting
the read. Note that when we don't expect data from a connection, the timeout
is defined by write_timeout
. See also slave_net_timeout
.
net_retry_count
If a read on a communication port is interrupted, retry this many times
before giving up. This value should be quite high on FreeBSD
as
internal interrupts are sent to all threads.
net_write_timeout
Number of seconds to wait for a block to be written to a connection before
aborting the write.
open_files_limit
If this is not 0, then mysqld
will use this value to reserve file
descriptors to use with setrlimit()
. If this value is 0 then
mysqld
will reserve max_connections*5
or
max_connections + table_cache*2
(whichever is larger) number of
files. You should try increasing this if mysqld
gives you the
error 'Too many open files'.
pid_file
The value of the --pid-file
option.
port
The value of the --port
option.
protocol_version
The protocol version used by the MySQL server.
read_buffer_size
(ver. 4.0.3 未満では record_buffer
)
順序スキャンを行う各スレッドが、スキャンするテーブル毎に、このサイズのバッ
ファを割り当てます。多くの順序スキャンを行う場合は、これを増加させてくだ
さい。
record_rnd_buffer_size
When reading rows in sorted order after a sort, the rows are read
through this buffer to avoid a disk seeks. Can improve ORDER BY
by a lot if set to a high value. As this is a thread-specific variable,
one should not set this big globally, but just change this when running
some specific big queries.
query_cache_limit
Don't cache results that are bigger than this. (Default 1M).
query_cache_size
The memory allocated to store results from old queries.
If this is 0, the query cache is disabled (default).
query_cache_type
This may be set (only numeric) to
Value | Alias | Comment |
0 | OFF | Don't cache or retrieve results. |
1 | ON | Cache all results except SELECT SQL_NO_CACHE ... queries.
|
2 | DEMAND | Cache only SELECT SQL_CACHE ... queries.
|
safe_show_database
Don't show databases for which the user doesn't have any database or
table privileges. This can improve security if you're concerned about
people being able to see what databases other users have. See also
skip_show_database
.
server_id
The value of the --server-id
option.
skip_locking
Is OFF if mysqld
uses external locking.
skip_networking
Is ON if we only allow local (socket) connections.
skip_show_database
This prevents people from doing SHOW DATABASES
if they don't have
the PROCESS
privilege. This can improve security if you're
concerned about people being able to see what databases other users
have. See also safe_show_database
.
slave_net_timeout
Number of seconds to wait for more data from a master/slave connection
before aborting the read.
slow_launch_time
If creating the thread takes longer than this value (in seconds), the
Slow_launch_threads
counter will be incremented.
socket
The Unix socket used by the server.
sort_buffer_size
ソートを行う必要がある各スレッドがこのサイズのバッファを割り当てます。よ
り速い ORDER BY
または GROUP BY
のためにはこれを増やしてく
ださい。
See section MySQL が一時ファイルを格納する場所.
table_cache
全てのスレッドについてのオープンテーブルの数。これを増加する場合は、
mysqld
が要求するオープンファイルディスクリプタの数も
増加することに注意しないといけません。
You can check if you need to increase the table cache by checking the
Opened_tables
variable.
See section SHOW STATUS
.
If this variable
is big and you don't do FLUSH TABLES
a lot (which just forces all
tables to be closed and reopenend), then you should increase the value of this
variable.
For more information about the table cache, see section MySQL はどのようにテーブルのオープン & クローズを行なうか?.
table_type
The default table type.
thread_cache_size
How many threads we should keep in a cache for reuse. When a
client disconnects, the client's threads are put in the cache if there
aren't more than thread_cache_size
threads from before. All new
threads are first taken from the cache, and only when the cache is empty
is a new thread created. This variable can be increased to improve
performance if you have a lot of new connections. (Normally this doesn't
give a notable performance improvement if you have a good
thread implementation.) By examing the difference between
the Connections
and Threads_created
status variables
(see section SHOW STATUS
for details) you can see how efficient
thread cache is.
thread_concurrency
On Solaris, mysqld
will call thr_setconcurrency()
with
this value. thr_setconcurrency()
permits the application to give
the threads system a hint for the desired number of threads that should
be run at the same time.
thread_stack
各スレッドのスタックの大きさ。crash-me
によって検出される多く
の制限がこれに依存します。デフォルトでは、通常のオペレーションに対して
十分とってあります。 See section The MySQL Benchmark Suite.
timezone
The timezone for the server.
tmp_table_size
メモリー内の 一時テーブルがこの値を超えようとした場合、MySQL は
自動的に、これを、disk ベースの MyISAM
テーブルに変換します。
多くの先進的な GROUP BY
クエリを行う場合は、
この tmp_table_size
を増加してください。
tmpdir
The directory used for temporary files and temporary tables.
Starting from MySQL 4.1, it 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.
version
The version number for the server.
wait_timeout
インタラクティブではないアクティブなコネクションを
閉じるのに、にサーバーが待つ秒数。
On thread startup SESSION.WAIT_TIMEOUT
is initialised from
GLOBAL.WAIT_TIMEOUT
or GLOBAL.INTERACTIVE_TIMEOUT
depending
on the type of client (as defined by the CLIENT_INTERACTIVE
connect
option). See also interactive_timeout
.
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.
File
shows the full path to the log file
Type
shows the type of the log file (BDB
for Berkeley
DB log files)
Status
shows the status of the log file (FREE
if the
file can be removed, or IN USE
if the file is needed by the transaction
subsystem)
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
Checking table
The thread is performing [automatic] checking of the table.
Closing tables
Means that the thread is flushing the changed table data to disk and
closing the used tables. This should be a fast operation. If not, then
you should check that you don't have a full disk or that the disk is not
in very heavy use.
Connect Out
Slave connecting to master.
Copying to tmp table on disk
The temporary result set was larger than tmp_table_size
and the
thread is now changing the in memory-based temporary table to a disk
based one to save memory.
Creating tmp table
The thread is creating a temporary table to hold a part of the result for
the query.
deleting from main table
When executing the first part of a multi-table delete and we are only
deleting from the first table.
deleting from reference tables
When executing the second part of a multi-table delete and we are deleting
the matched rows from the other tables.
Flushing tables
The thread is executing FLUSH TABLES
and is waiting for all
threads to close their tables.
Killed
Someone has sent a kill to the thread and it should abort next time it
checks the kill flag. The flag is checked in each major loop in MySQL,
but in some cases it may still take a short time for the thread to die.
If the thread is locked by some other thread, the kill will take affect
as soon as the other thread releases it's lock.
Sending data
The thread is processing rows for a SELECT
statement and is
also sending data to the client.
Sorting for group
The thread is doing a sort to satsify a GROUP BY
.
Sorting for order
The thread is doing a sort to satsify a ORDER BY
.
Opening tables
This simply means that the thread is trying to open a table. This is
should be very fast procedure, unless something prevents opening. For
example an ALTER TABLE
or a LOCK TABLE
can prevent opening
a table until the command is finished.
Removing duplicates
The query was using SELECT DISTINCT
in such a way that MySQL
couldn't optimise that distinct away at an early stage. Because of this
MySQL has to do an extra stage to remove all duplicated rows before
sending the result to the client.
Reopen table
The thread got a lock for the table, but noticed after getting the lock
that the underlying table structure changed. It has freed the lock,
closed the table and is now trying to reopen it.
Repair by sorting
The repair code is using sorting to create indexes.
Repair with keycache
The repair code is using creating keys one by one through the key cache.
This is much slower than Repair by sorting
.
Searching rows for update
The thread is doing a first phase to find all matching rows before
updating them. This has to be done if the UPDATE
is changing
the index that is used to find the involved rows.
Sleeping
The thread is wating for the client to send a new command to it.
System lock
The thread is waiting for getting to get a external system lock for the
table. If you are not using multiple mysqld servers that are accessing
the same tables, you can disable system locks with the
--skip-external-locking
option.
Upgrading lock
The INSERT DELAYED
handler is trying to get a lock for the table
to insert rows.
Updating
The thread is searching for rows to update and updating them.
User Lock
The thread is waiting on a GET_LOCK()
.
Waiting for tables
The thread got a notification that the underlying structure for a table
has changed and it needs to reopen the table to get the new structure.
To be able to reopen the table it must however wait until all other
threads have closed the table in question.
This notification happens if another thread has used FLUSH TABLES
or one of the following commands on the table in question: FLUSH
TABLES table_name
, ALTER TABLE
, RENAME TABLE
,
REPAIR TABLE
, ANALYZE TABLE
or OPTIMIZE TABLE
.
waiting for handler insert
The INSERT DELAYED
handler has processed all inserts and are
waiting to get new ones.
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 は スウェーデン語/フィンランド語に一致する 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 BY
と GROUP BY
コマンドによってソートされる方法を決定します。
キャラクターセットは、名前として使用してもよい文字と SELECT
構文中の
ORDER BY
と GROUP 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
しかし通常はこれは不要です。
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
.
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 です。
例えば、latin1
と danish
は simple キャラクター・セットで、
big5
や czech
は complex キャラクター・セットです。
以下のセクションでは、あなたがキャラクター・セットに MYSET
という名前を
つけていると仮定します。
For a simple character set do the following:
ctype
array takes up the first 257 words. The
to_lower[]
, to_upper[]
and sort_order[]
arrays take up
256 words each after that.
CHARSETS_AVAILABLE
and
COMPILED_CHARSETS
lists in configure.in
.
For a complex character set do the following:
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
/* * 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.
my_strncoll_MYSET()
my_strcoll_MYSET()
my_strxfrm_MYSET()
my_like_range_MYSET()
configure.in
中の CHARSETS_AVAILABLE
と
COMPILED_CHARSETS
に追加します。
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.
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
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.
If you try to use a character set that is not compiled into your binary, you can run into a couple of different problems:
--character-sets-dir
option to the program in question.
ERROR 1105: File '/usr/local/share/mysql/charsets/?.conf' not found (Errcode: 2)In this case you should either get a new
Index
file or add
by hand the name of any missing character sets.
For MyISAM
tables, you can check the character set name and number for a
table with myisamchk -dvv table_name
.
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
myisamchk
has many functions, it is described in its own
chapter. See section データベース管理.
make_binary_distribution
support.mysql.com
for the
convenience of other MySQL users.
mysqlbug
mysqld
mysql_install_db
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=#
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
--ledir=path
mysqld
--log=path
--mysqld=mysqld-version
mysqld
version in the ledir
directory you want to start.
--mysqld-version=version
--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=#
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=#
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:
safe_mysqld
is invoked. safe_mysqld
looks under its working
directory for `bin' and `data' directories (for binary
distributions) or for `libexec' and `var' directories (for source
distributions). This condition should be met if you execute
safe_mysqld
from your MySQL installation directory (for
example, `/usr/local/mysql' for a binary distribution).
safe_mysqld
attempts to locate them by absolute pathnames. Typical
locations are `/usr/local/libexec' and `/usr/local/var'.
The actual locations are determined when the distribution was built from which
safe_mysqld
comes. They should be correct if
MySQL was installed in a standard location.
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=...
[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
--user=...
mysqladmin
で使用する MySQL ユーザー.
--version
Some notes about mysqld_multi
:
mysqld
services (e.g using the mysqladmin
program) have the same
password and username for all the data directories accessed (to the
mysql
database) And make sure that the user has the SHUTDOWN
privilege! If you have many data directories and many different mysql
databases with different passwords for the MySQL root
user,
you may want to create a common multi_admin
user for each using the
same password (see below). Example how to do it:
shell> mysql -u root -S /tmp/mysql.sock -proot_password -e "GRANT SHUTDOWN ON *.* TO multi_admin@localhost IDENTIFIED BY 'multipass'"See section 特権システムはどのように動くか?. You will have to do the above for each
mysqld
running in each
data directory, that you have (just change the socket, -S=...
).
pid-file
is very important, if you are using safe_mysqld
to start mysqld
(e.g., --mysqld=safe_mysqld
) Every
mysqld
should have its own pid-file
. The advantage
using safe_mysqld
instead of mysqld
directly here is,
that safe_mysqld
``guards'' every mysqld
process and will
restart it, if a mysqld
process terminates due to a signal
sent using kill -9
, or for other reasons such as a segmentation
fault (which MySQL should never do, of course ;). Please note that the
safe_mysqld
script may require that you start it from a certain
place. This means that you may have to cd
to a certain directory,
before you start the mysqld_multi
. If you have problems starting,
please see the safe_mysqld
script. Check especially the lines:
-------------------------------------------------------------------------- MY_PWD=`pwd` Check if we are starting this relative (for the binary release) if test -d /data/mysql -a -f ./share/mysql/english/errmsg.sys -a -x ./bin/mysqld --------------------------------------------------------------------------See section
safe_mysqld
, The Wrapper Around mysqld
.
The above test should be successful, or you may encounter problems.
mysqld
s in the same data
directory. Use separate data directories, unless you know what
you are doing!
mysqld
.
mysqld
group were intentionally left out from
the example. You may have 'gaps' in the config file. This gives you
more flexibility. The order in which the mysqlds
are started or
stopped depends on the order in which they appear in the config file.
[mysqld17]
is 17.
--user
for mysqld
, but in order to
do this you need to run the mysqld_multi
script as the Unix root
user. Having the option in the config file doesn't matter; you will
just get a warning, if you are not the superuser and the mysqlds
are started under your Unix account. Important: Make
sure that the pid-file
and the data directory are
read+write(+execute for the latter one) accessible for that
Unix user, who the specific mysqld
process is started
as. Do not use the Unix root account for this, unless you
know what you are doing!
mysqld
s and why one
would want to have separate mysqld
processes. Starting multiple
mysqld
s in one data directory will not give you extra
performance in a threaded system!
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
can also pack BLOB
or TEXT
columns.
The older pack_isam
(for ISAM
tables) can not do this.
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=#
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
-t, --test
-T dir_name, --tmp_dir=dir_name
-v, --verbose
-V, --version
-w, --wait
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
empty-space
empty-zero
empty-fill
INTEGER
column may be changed to MEDIUMINT
).
pre-space
end-space
table-lookup
ENUM
before Huffman compression.
zero
Original trees
After join
After a table has been compressed, myisamchk -dvv
prints additional
information about each field:
Type
constant
no endspace
no endspace, not_always
no endspace, no empty
table-lookup
ENUM
.
zerofill(n)
n
bytes in the value are always 0 and are not
stored.
no zeros
always zero
Huff tree
Bits
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 |
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
mSQL
programs to MySQL. It doesn't
handle all cases, but it gives a good start when converting.
mysqlaccess
mysqladmin
mysqladmin
can also be used to retrieve version,
process, and status information from the server.
See section mysqladmin
, MySQL サーバーの管理.
mysqldump
mysqldump
, データベースとテーブルから、構造とデータをダンプ.
mysqlimport
LOAD DATA
INFILE
. See section mysqlimport
, テキストファイルからデータを取り込む.
mysqlshow
replace
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 database
や mysql --user=user_name --password=your_password d
atabase
のようにしてはじめます。
SQL 文を入力し、一文を `;', `\g' or `\G' で終え、
RETURN/ENTER を押します。
-?, --help
-A, --no-auto-rehash
mysql
の起動を速くします。
--prompt=...
-b, --no-beep
-B, --batch
--character-sets-dir=...
-C, --compress
-#, --debug[=...]
-D, --database=...
my.cnf
ファイルが便利です
--default-character-set=...
-e, --execute=...
-E, --vertical
\G
で終了した場合、同じように垂直に出力します。
-f, --force
-g, --no-named-commands
-G, --enable-named-commands
-i, --ignore-space
-h, --host=...
-H, --html
-X, --xml
-L, --skip-line-numbers
--no-pager
--no-tee
-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
--pager[=...]
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[=...]
-p
を使用する場合、このオプションとパスワードの間には
スペースが不要だということに注意してください。
-P port_num, --port=port_num
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
-r, --raw
--batch
とともに使用されます
--reconnect
-s, --silent
-S --socket=...
-t --table
-T, --debug-info
--tee=...
-u, --user=#
-U, --safe-updates[=#], --i-am-a-dummy[=#]
UPDATE
and DELETE
のみを行います。
これは後述します。 このオプションをもし my.cnf
に書いている場合は、
--safe-updates=0
でこのオプションをリセットできます。
-v, --verbose
-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_name
を WHERE
節を忘れて
実行しようとした場合のためにあります。)
このオプションが使用されると、 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
構文.
この効果は:
WHERE
節でキーを使用していなければ、UPDATE
や DELETE
は許可されません。 しかし、 LIMIT
を使用すれば UPDATE/DELETE
を
強制実行できます:
UPDATE table_name SET not_key_column=# WHERE not_key_column=# LIMIT 1;
#select_limit#
レコードまでに抑えられます。
#max_join_size
以上の行を必要とするであろう SELECT
は
中断されます。
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
:
mysql> pager cat > /tmp/log.txtand the results will only go to a file. You can also pass any options for the programs that you want to use with the
pager
:
mysql> pager less -n -i -S
mysql> pager cat | tee /dr1/tmp/res.txt | \ tee /dr2/tmp/res2.txt | less -n -i -S
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:
MYSQL_PS1
environment variable to a prompt string. For
example:
shell> export MYSQL_PS1="(\u@\h) [\d]> "
prompt
option in any MySQL configuration file, in the
mysql
group. For example:
[mysql] prompt=(\u@\h) [\d]>\_
--prompt
option on the command line to mysql
.
For example:
shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]>
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
kill id,id,...
password
ping
mysqld
が生きているかチェック
processlist
reload
refresh
shutdown
slave-start
slave-stop
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.
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
-1, --all-in-1
-a, --analyze
--auto-repair
-#, --debug=...
--character-sets-dir=...
-c, --check
-C, --check-only-changed
--compress
-?, --help
-B, --databases
--default-character-set=...
-F, --fast
-f, --force
-e, --extended
-h, --host=...
-m, --medium-check
-o, --optimize
-p, --password[=...]
-P port_num, --port=port_num
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
-r, --repair
-s, --silent
-S, --socket=...
--tables
-u, --user=#
-v, --verbose
-V, --version
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
LOCK TABLES
before and UNLOCK TABLE
after each table dump.
(To get faster inserts into MySQL.)
--add-drop-table
drop table
before each create statement.
-A, --all-databases
--databases
with all
databases selected.
-a, --all
--allow-keywords
-c, --complete-insert
-C, --compress
-B, --databases
USE db_name;
will be included in the output before each new database.
--delayed
INSERT DELAYED
command.
-e, --extended-insert
INSERT
syntax. (Gives more compact and
faster inserts statements.)
-#, --debug[=option_string]
--help
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
-T
option and have the same
meaning as the corresponding clauses for LOAD DATA INFILE
.
See section LOAD DATA INFILE
構文.
-F, --flush-logs
-f, --force,
-h, --host=..
localhost
.
-l, --lock-tables.
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
CREATE TABLE
statement).
-d, --no-data
--opt
--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]
mysqldump
you will be prompted for a password.
-P port_num, --port=port_num
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
mysql_use_result()
to do this.
-Q, --quote-names
-r, --result-file=...
--single-transaction
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
localhost
(which is the
default host).
--tables
-T, --tab=path-to-some-directory
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
-O var=option, --set-variable var=option
--set-variable
is deprecated since MySQL 4.0, just use --var=option
on its own.
-v, --verbose
-V, --version
-w, --where='where-condition'
-X, --xml
-x, --first-slave
"--where=user='jimf'" "-wuserid>1" "-wuserid<1"
-O net_buffer_length=#, where # < 16M
--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
-u, --user=#
-p, --password=#
-P, --port=#
-S, --socket=#
--allowold
--keepold
--noindices
myisamchk -rq.
.
--method=#
cp
or scp
).
-q, --quiet
--debug
-n, --dryrun
--regexp=#
--suffix=#
--checkpoint=#
--flushlog
--tmpdir=#
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=...
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
localhost
.
-i, --ignore
--replace
オプションの説明を見てください。
-l, --lock-tables
-L, --local
localhost
に接続した場合、テキストファイルは
サーバー上にあると仮定されます。(localhost
はデフォルト値)
-pyour_pass, --password[=your_pass]
mysqlimport
はパスワードのためのプロンプトをだします。
-P port_num, --port=port_num
localhost
を除くホストへの接続に使用します。
localhost
へは、Unix ソケットを使用します。)
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-r, --replace
--replace
と --ignore
オプションは、
入力されているレコードのユニークキーの値が、
既に存在しているレコードのユニークキーの値と同じ場合、
その入力されているデータの取り扱いを決定します。
もし --replace
が指定されているなら、
既にあるレコードは新しく読まれたレコードに置き換えられます。
もし --ignore
が指定されているなら、
入力された物は無視されます。
どちらのオプションも指定していない場合、
キーの値が重なっているとエラーを発し、
テキストファイルの残りの部分は無視されます。
-s, --silent
-S /path/to/socket, --socket=/path/to/socket
localhost
への接続時に使用するソケットファイルを指定します。
-u user_name, --user=user_name
-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
--libs
--socket
--port
--version
--libmysqld-libs
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!
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
のバッチモードでの使用.
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 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.
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 が拡張を持たなかったなら、mysqld
は
file_name.###
という形でログファイルを作成します。
このログファイルはデータディレクトリにかかれ、
その名前は file_name.###
という形式の名前になっています。
###
は mysqladmin refresh
か mysqladmin 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
を使用した UPDATE
か DELETE
で結果が得られなかった場合、
ログは書き出されません。
すでにセットされている値に、もう一度項目を更新するような 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 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.
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
コマンド行オプション.
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
を使用しなくてはなりません。
上記のコマンドは、以下のように動作します:
--log
) or slow query logging
(--log-slow-queries
) is used, closes and reopens the log file
(`mysql.log' and ``hostname`-slow.log' as default).
--log-update
) を使用しているなら、
更新ログを閉じ、新しいログファイルを開きます。そのさい、
ログファイルについている番号は増えます。
もし更新ログだけを使用しているなら、あなたは、ログを flush するだけでよくて、 その時、バックアップのため古い更新ログファイルを移動します。 もし普通のログを使っていれば、あなたは以下のようにすることができます:
shell> cd mysql-data-directory shell> mv mysql.log mysql.old shell> mysqladmin flush-logs
こうしておいて、`mysql.old' をバックアップし削除します。
この章は MySQL の様々なレプリケーション機能を説明します。レプリケーション で有効なオプションのリファレンスとしても役立ちます。レプリケーションの紹介 と、その実装方法を学べます。終りの方には、いくつかの FAQ と問題の説明とそ の解決方法もあります。
我々のウェブサイト http://www.mysql.com/ によく訪れ、この節の最新 版を読むようるように提案します。レプリケーションは絶えず改良されていて、 最新の情報でマニュアルを頻繁に更新します。
一方通行レプリケーションは、堅牢さと速度の両方を増加させるために使用できま す。堅牢さについて、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
内のレプリケーション
開始オプションにも精通すべきです。
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.2If 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.
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-dirWindows ユーザは
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 shutdownIf 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.
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
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
の省略はバイナリログのバックアップのためにだけ良
いことです。
mysql> RESET SLAVE;
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.
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.
以下はサポートされていることとサポートされていないことの説明です:
AUTO_INCREMENT
,
LAST_INSERT_ID
, TIMESTAMP
値を正しく扱います。
RAND()
はうまく複製できません。
RAND()
での更新を複製する場合は、RAND(some_non_rand_expr)
を
使用してください。
例えば、UNIX_TIMESTAMP()
を RAND()
の引数に使用するとか。
--default-character-set
) を使
用しなくてはなりません。
もし違った場合、スレーブ上で duplicate key errors が出るかもしれません。
これは、マスター上で一意のキーであったとしても、
違う キャラクター・セット ではそうとはみなされない事があるからです。
LOAD DATA INFILE
will be handled properly as long as the file
still resides on the master server at the time of update
propagation. LOAD LOCAL DATA INFILE
will be skipped. In 4.0, this
limitation is not present - all forms of LOAD DATA INFILE
are properly
replicated.
FLUSH
コマンドはバイナリログに記録されません。
もちろん、スレーブに複製されません。
これは FLUSH
が通常は何もデータを変更しないからです。
しかし、仮に MySQL の権限データベースを複製していて、
GRANT
文ではなくて直接 MySQL 権限テーブルを変更した場合には、
権限を反映させるために、スレーブ上で FLUSH PRIVILEGES
を行なわなくては
なりません。
SLAVE STOP
を行ない、それから
Slave_open_temp_tables
変数が 0 かどうかをチェックし、そして、
mysqladmin shutdown
を発行してください。数値が 0 でない場合は、スレー
ブスレッドを SLAVE START
で再起動して、次回に幸運かどうかを見てくだ
さい。 もっときれいな解決方法は、バージョン 4.0 まで待つ必要があります。それ以前
のバージョンの一時テーブルは正しく複製されません - アップグレードするか 一
時テーブルでのすべてのクエリの前にクライアント上で SET
SQL_LOG_BIN=0
の実行をお勧めします。
log-slave-updates
を有効にすることで、
マスターとスレーブの関係を輪っか状にすることが可能です。
しかし、多くのクエリは、この種のセットアップでは正しく動作しません。
違うシーケンス、違うサーバーで行なわれる更新によって引き起こる
潜在的な問題に対応するように、クライアントコードを注意して書かない限りは。
これは以下のようなセットアップを意味します:
A -> B -> C -> Aこのセットアップはテーブル間での更新に何も衝突が無い場合にのみ、動作します。 仮に A と C でデータを insert するとき、C にinsertするレコードのキーと 競合するようなレコードを A に insert してはいけません。 同じレコードを、2つのサーバーで更新すべきではありません。 もしそこで更新が適用される順番が重要なら。 ログのフォーマットは バージョン 3.23.36 で変更になりました。 3.23.36 以前のスレーブは、3.23.36 以上のログファイルを読むことができません。
.err
ファイルにメッセージが現われます。
この場合、スレーブを手動で接続し、エラーの原因を修正し(例えば、テーブルが無いとか)、
その後、 SLAVE START
SQLコマンドを実行します
(このコマンドはバージョン 3.23.16 以上から)。
バージョン 3.23.15 までは、サーバーを再起動しなくてはなりません。
master-connect-retry
秒毎(デフォルトでは 60秒)に
リトライを繰り返します。
このため、マスターをシャットダウンして、しばらくあとに再起動することは安全
です。スレーブはネットワーク接続性の停止も処理できます。
However, the slave will notice the
network outage only after receiving no data from the master for
slave_net_timeout
seconds. So if your outages are short, you may want
to decrease slave_net_timeout
; see section SHOW VARIABLES
.
my.cnf
ファイルに master-port
パラメターを書くことにより、
ポート番号を指定できます。
my.cnf
内の replicate-do-db
命令でデー
タベースのセットに、または replicate-ignore-db
でデータベースのセッ
トを除外して、複製を制限できます。注意: バージョン 3.23.23 になるまでは、
複製から除外されたデータベースで LOAD DATA INFILE
を行なうと、正し
く扱えないというバグがありました。
SET SQL_LOG_BIN = 0
でレプリケーシ
ョン(バイナリ) ログを止めることができます。
SET SQL_LOG_BIN = 1
で再びログを採取することができます。
これを行なう場合には、SUPER
権限(in MySQL 4.0.2 and above)か
PROCESS
権限(in older MySQL versions) が必要です。
FLUSH MASTER
と FLUSH SLAVE
コマンドが用意されました。
バージョン 3.23.26 から、これらの名前を
RESET MASTER
と RESET SLAVE
に変更しました。
互換性のために、古い FLUSH
もまだ動作します。
(訳注: このコマンドは、bin log を 001 からに強制してしまうため、
場合によっては複製をおかしくすることも有る。使用には注意。)
CHANGE MASTER TO
を使用して、
マスターを変更したりポジションを変更したりできるようになりました。
binlog-ignore-db
を使用して、
バイナリログを取らないデータベースを指定できるようになりました。
replicate-rewrite-db
を使用して、
マスター上のデータベースの名前を、スレーブ上では違う名前にするように、
スレーブに指示することができるようになりました。
PURGE MASTER LOGS TO 'log-name'
が使用できます。
This will remove all old
logs before, but not including 'log-name'
.
slave-skip-errors
option starting in Version 3.23.47.
replicate-do-table
/replicate-ignore-table
or
replicate-wild-do-table
/replicate-wild-ignore-table
, there
are currently some design deficiencies that in some rather rare cases
produce unexpected results. The replication protocol does not inform the
slave explicitly which tables are going to be modified by the query -- so
the slave has to parse the query to know this. To avoid redundant
parsing for queries that will end up actually being executed, table
exclusion is currently implemented by sending the query to the standard
MySQL parser, which will short-circuit the query and report success if
it detects that the table should be ignored. In addition to several
inefficiencies, this approach is also more bug prone, and there are two
known bugs as of Version 3.23.49 -- because the parser automatically opens
the table when parsing some queries the ignored table has to exist on
the slave. The other bug is that if the ignored table gets partially
updated, the slave thread will not notice that the table actually should
have been ignored and will suspend the replication process. While the
above bugs are conceptually very simple to fix, we have not yet found a way
to do this without a significant code change that would compromise the stability
status of 3.23 branch. There exists a workaround for both if in the rare case
it happens to affect your application -- use slave-skip-errors
.
レプリケーションを使用する場合は、我々は 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 MASTER と RESET 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 インタフェースを通じて制御できます。以下はコマンド のサマリです:
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_FILE と MASTER_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 でログのリストを行ない、すべてのスレーブに共通の最も古いログ
を見つけ(すべてのスレーブが最新の場合、リストの最後のログになります)、削除
しようとするすべてのログをバックアップし、目的のログをパージします。
|
Q: マスタが既に走っている状態で、マスタを止めないで、新しく スレーブを作るには、どのようにすればいいの?
A: いくつか方法があります。
もしマスタのどこかの時点でのバックアップを取っていて、そして
そのバックアップした時点に対応する
バイナリログの名前と位置を記録しているのであれば、
( SHOW MASTER STATUS
で知ることが出来ます)
以下のようにします:
CHANGE MASTER TO MASTER_HOST='master-host-name',
MASTER_USER='master-user-name', MASTER_PASSWORD='master-pass',
MASTER_LOG_FILE='recorded-log-name', MASTER_LOG_POS=recorded_log_pos
SLAVE START
実行
もし現在のマスタのバックアップを取っていないのであれば、以下が素早く セットアップする方法です:
FLUSH TABLES WITH READ LOCK
gtar zcf /tmp/backup.tar.gz /var/lib/mysql
(パスは環境にあわせて)
SHOW MASTER STATUS
- 確実にこの出力をメモしておくように - 後で必要になります
UNLOCK TABLES
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: 次のコマンドを実行してください:
FLUSH TABLES WITH READ LOCK
SHOW MASTER STATUS
- ログ名とオフセットを記録してください
SELECT MASTER_POS_WAIT('recorded_log_name', recorded_log_offset)
select が復帰した時、スレーブはマスタと同期されています
UNLOCK TABLES
- これでマスタは更新を続けられます。
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:
pthread_cond_wait()
,
from which we can be awakened either by an update or a kill.
Binlog_dump
loop.
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_writer_connect()
safe_reader_connect()
safe_reader_query()
safe_writer_query()
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: 現在有効な機能で、マスターとスレーブ(またはいくつかのスレーブ 達)をセットアップする必要があります。マスターが生きているかどうかを監視し、 アプリケーションとマスターのスレーブに失敗時に変更を指示するスクリプトを書 きます。以下はいくつかの提案です:
CHANGE MASTER TO
コマンドを使用して、スレーブにマスターを変更するよ
うに通知します。
nsupdate
を使って DNS を動的に更新できます。
log-bin
オプション付きで log-slave-updates
無しで
実行すべきです。この方法で、STOP SLAVE
; RESET MASTER
、他のス
レーブ上で CHANGE MASTER TO
を実行すると、すぐにスレーブがマスター
になるように準備ができます。
It will also help you catch
spurious updates that may happen because of misconfiguration of the
slave (ideally, you want to configure access rights so that no client
can update the slave, except for the slave thread) combined with the
bugs in your client programs (they should never update the slave
directly).
我々は現在自動マスター選択システムを 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 |
If you have followed the instructions, and your replication setup is not working, first eliminate the user error factor by checking the following:
SHOW MASTER STATUS
.
If it is, Position
will be non-zero. If not, verify that you have
given the master log-bin
option and have set server-id
.
SHOW SLAVE STATUS
. The answer is found
in Slave_running
column. If not, verify slave options and check the
error log for messages.
SHOW PROCESSLIST
, find the thread with system user
value in
User
column and none
in the Host
column, and check the
State
column. If it says connecting to master
, verify the
privileges for the replication user on the master, master host name, your
DNS setup, whether the master is actually running, whether it is reachable
from the slave, and if all that seems okay, read the error logs.
SLAVE START
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; SLAVE START;
to skip a query that
does not use AUTO_INCREMENT
or LAST_INSERT_ID()
, or
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2; SLAVE START;
otherwise. The reason
queries that use AUTO_INCREMENT
or LAST_INSERT_ID()
are different is that they take two events in the binary log of the master.
grep -i slave /path/to/your-log.err
on the slave. There is no
generic pattern to search for on the master, as the only errors it logs
are general system errors -- if it can, it will send the error to the slave
when things go wrong.
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":
log-slave-updates
and log-bin
-- this will keep
a log of all updates on the slave.
SHOW MASTER STATUS
on the master at the time
you have discovered the problem
SHOW SLAVE STATUS
on the master at the time
you have discovered the problem
mysqlbinlog
to examine the binary logs. The following should
be helpful
to find the trouble query, for example:
mysqlbinlog -j pos_from_slave_status /path/to/log_from_slave_status | head
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.
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.
主なボトルネックは:
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:
NULL
in a
NOT NULL
column or a too big numerical value in a numerical
column, MySQL will instead of giving an error instead set the column to
the 'best possible value'. For numerical values this is 0, the smallest
possible values or the largest possible value. For strings this is
either the empty string or the longest possible string that can be in
the column.
NULL
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.
全ての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.
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.
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:
VARCHAR
column can be
We can find the result from crash-me
on a lot of different databases at
http://www.mysql.com/information/crash-me.php.
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.
SELECT
s 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_name
や
SHOW 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 のために、EXPLAIN
は SELECT
文で使用されている
それぞれのテーブルの情報を返します。
テーブルは読まれる順に表示されます。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 UNION
s, 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
SELECT
clause, which can be any of the following:
SIMPLE
SELECT
(without UNION
s or subqueries).
PRIMARY
SELECT
.
UNION
UNION
SELECT
s.
DEPENDENT UNION
UNION
SELECTS
s, dependent on outer
subquery.
SUBSELECT
SELECT
in subquery.
DEPENDENT SUBSELECT
SELECT
, dependent on outer subquery.
DERIVED
SELECT
.
table
type
system
const
join type
の特別な場合です。
const
const
テーブルはとても速いです!
eq_ref
const
よりも良い形です。
インデックスの全てのパートが join で使用され、かつ、インデックスが
UNIQUE
か PRIMARY KEY
であるときに、これは使用されます。
ref
UNIQUE
や PRIMARY 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 が使用すると決めたキーの長さを示します。
もし key
が NULL
なら、長さは NULL
です。
注意: これはMySQL がマルチパートキーのいくつのパートを実際に使用
するかを示します。
ref
ref
項目は、テーブルからレコードを select するために、どのフィールドや
定数が key
と共に使用されたかを示します。
rows
rows
フィールドは、MySQL がクエリを実行するために検査する
必要があると考えているレコードの数を示します。
Extra
Distinct
Not exists
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: #)
Using filesort
join type
に一致する全てのレ
コードを通して行なわれ、WHERE
に適合する全てのレコードについて、
ソートキーとレコードへのポインタを格納します。それから、キーがソートされま
す。最後にレコードはソートされた順に取り出されます。
Using index
Using temporary
GROUP BY
が行なわれたも
のとは別のフィールド上で ORDER BY
を行なう場合に発生します。
Using where
WHERE
節が使用されます。この情報がなくて、
テーブルが型 ALL
か index
であれば、クエリ内に何か間違った
ものがあります(テーブルから全てのレコードを fetch/examine しようとしてい
るのでなければ)。
Using filesort
と Using
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;
この例では、以下のように仮定します:
Table | Column | Column type |
tt | ActualPC | CHAR(10)
|
tt | AssignedPC | CHAR(10)
|
tt | ClientID | CHAR(10)
|
et | EMPLOYID | CHAR(15)
|
do | CUSTNMBR | CHAR(15)
|
Table | Index |
tt | ActualPC
|
tt | AssignedPC
|
tt | ClientID
|
et | EMPLOYID (primary key)
|
do | CUSTNMBR (primary key)
|
tt.ActualPC
の値は、いちように分布して(配置されて)いません。
最初、いかなる最適化も行われていない状態では、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)
それぞれのテーブルで、type
が ALL
になっています。
これは MySQL が全てのテーブルを全結合することを示します!
それぞれのテーブル内の行数分から作った物が調べられるので、とても長い時間がかかり
ます!
この場合、74 * 2135 * 74 * 3872 = 45,268,558,720
行調べることになります。
テーブルが肥大化したときにかかる時間を考えてください....
一つ問題があります。(まだ) MySQL がフィールドのインデックスを効果的に
使用できていません。
この例の場合では、VARCHAR
と CHAR
は、それらが同じ長さで定義されて
いれば、変わりがありません。
tt.ActualPC
は CHAR(10)
と定義されており、
et.EMPLOYID
は CHAR(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
節に異なる順でテーブルを並べることで、良いパフォーマンスを
得られます。
ほとんどの場合、ディスク・シークを数えることでだいたいのパフォーマンスを予測でき
ます。
小さなテーブルでは、通常、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:
myisamchk
--analyze
on a table after it has been loaded with relevant data. This
updates a value for each index part that indicates the average number of
rows that have the same value. (For unique indexes, this is always 1,
of course.) MySQL will use this to decide which index to
choose when you connect two tables with 'a non-constant expression'.
You can check the result from the analyze
run by doing SHOW
INDEX FROM table_name
and examining the Cardinality
column.
myisamchk --sort-index --sort-records=1
を使用します
(もし 1番目のインデックス順にソートするなら)。
If you
have a unique index from which you want to read all records in order
according to that index, this is a good way to make that faster.
しかし、このソート方法は最適状態では書かれず、また大きなテーブルでは
多くの時間がかかることに注意してください!
WHERE
節を最適化するか?
WHERE
の最適化は、WHERE
がほとんど SELECT
で使用されるため、
SELECT
に置かれています。 しかし、同じ最適化は
DELETE
や UPDATE
文でも使用されます。
このセクションの最適化の説明はまだ不十分です。 なぜなら、 MySQL はとても多くの最適化を行っており、 それら全てについての説明を書ける時間が、我々はとれません。
MySQLによる最適化のいくつかを以下に示します:
((a AND b) AND c OR (((a AND b) AND (c AND d)))) -> (a AND b AND c) OR (a AND b AND c AND d)
(a<b AND b=c) AND a=5 -> b>5 AND b=c AND a=5
(B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6) -> B=5 OR B=6
WHERE
がない COCOUNT(*)
は、
MyISAM
and HEAP
の場合は テーブルの情報から
直接取り出されます。これはまた 1つのテーブルだけで NOT NULL
を
使用したときも同様です。
SELECT
構文を素早く見つけ、0 行を結果として返
します。
GROUP BY
または group 関数 (COUNT()
, MIN()
...) を使用しない
場合は、
HAVING
は WHERE
とマージされます。
WHERE
評価を得るために、また、可能な限り
早くレコードをスキップするために、各サブ結合についてより簡単な
WHERE
が構築されます。
WHERE
節で UNIQUE
インデックスや PRIMARY KEY
が使用されたテ
ーブルで、かつ、全てのインデックスが定数式で使用されていて、
かつ、インデックスのパートが NOT NULL
で定義されているテーブル。
mysql> SELECT * FROM t WHERE primary_key=1; mysql> SELECT * FROM t1,t2 -> WHERE t1.primary_key=1 AND t2.primary_key=t1.id;
ORDER BY
または GROUP
内の全てのフィールドが同じテーブルの場合は、
このテーブルは結合時に最初に優先されます。
ORDER BY
節と GROUP BY
節がある場合、または ORDER BY
か
GROUP BY
が結合キュー内の最初のテーブルではない他のテーブルからの項目を
含む場合、一時テーブルが生成されます。
SQL_SMALL_RESULT
を使用するなら, MySQL はメモリー内の一時
テーブルを使用します
HAVING
節に適合するものをスキップします。
以下はとても速いクエリの例です:
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,... ;
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.
LEFT JOIN
と RIGHT JOIN
を最適化するか?
MySQL の A LEFT JOIN B
は以下のように組みこまれています:
B
is set to be dependent on table A
and all tables
that A
is dependent on.
A
が LEFT JOIN
条件中に使用される全てのテーブル
(ただし B
は除く)に依存すると、セットされます。
LEFT JOIN
条件が WHERE
節に移動されます。
WHERE
節の最適化が行われます。
WHERE
節にマッチするレコードが A
にあり、
LEFT JOIN
条件にマッチするレコードが B
にない場合、
全てのフィールドが NULL
にセットされた B
のレコードが
作成されます。
LEFT JOIN
to find rows that don't exist in some
table and you have the following test: column_name IS NULL
in the
WHERE
part, where column_name is a column that is declared as
NOT NULL
, then MySQL will stop searching after more rows
(for a particular key combination) after it has found one row that
matches the LEFT JOIN
condition.
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
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):
ORDER BY
on different keys:
SELECT * FROM t1 ORDER BY key1,key2
ORDER BY
using non-consecutive key parts.
SELECT * FROM t1 WHERE key2=constant ORDER BY key_part2
ASC
and DESC
.
SELECT * FROM t1 ORDER BY key_part1 DESC,key_part2 ASC
ORDER BY
:
SELECT * FROM t1 WHERE key2=constant ORDER BY key1
ORDER
BY
on are not all from the first not-const
table that is used to
retrieve rows (This is the first table in the EXPLAIN
output which
doesn't use a const
row fetch method).
ORDER BY
and GROUP BY
expressions.
HASH
index in HEAP
tables).
In the cases where MySQL have to sort the result, it uses the following algorithm:
WHERE
clause are skipped.
sort_buffer
).
MERGEBUFF
(7) regions to one block in
another temporary file. Repeat until all blocks from the first file
are in the second file.
MERGEBUFF2
(15)
blocks left.
record_rnd_buffer
) .
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:
sort_buffer
variable.
record_rnd_buffer
variable.
tmpdir
to point to a dedicated disk with lots of empty space.
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 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;
LIMIT
を最適化するか?
In some cases MySQL will handle the query differently when you are
using LIMIT #
and not using HAVING
:
LIMIT
を使用して限定した数だけ select を行うなら、 MySQL は、
ある場合、テーブルを全て走査するよりも、インデックスを使用しようとします。
LIMIT #
を ORDER BY
と共に使用するなら, MySQL は
最初の #
行を見つけたらすぐに、全テーブルのソートは行わずに、
ソートを終わらせます。
LIMIT #
を DISTINCT
と共に使用するなら, MySQL は
#
個の一意なレコードを見つけた時点で終わります。
GROUP BY
can be resolved by reading the key in order
(or do a sort on the key) and then calculate summaries until the
key value changes. In this case LIMIT #
will not calculate any
unnecessary GROUP BY
s.
#
行をクライアントに送った後すぐに、
クエリを中断します。 (if you are not using SQL_CALC_FOUND_ROWS
).
LIMIT 0
は常に素早く空の結果を返します。
これはクエリのチェックや結果として得られるフィールドの型を得るために利用できます。
LIMIT #
を使用します。
INSERT
クエリの速度レコードを挿入する時間はおおよそ次からなります:
ここで (数字) は比例時間です。これは、テーブルのオープンにかかる初期オーバーヘッ ド(これは同時に動作する各クエリ毎に1回行なわれます)は考慮されていません。
テーブルのサイズはインデックスの挿入を log N で遅くします (B-tree)。
INSERT を速くするいくつかの方法:
INSERT
文を使用します。 これは個々に INSERT
文
を発行する場合に比べて、とても速くなります。
If you are adding
data to non-empty table, you may tune up bulk_insert_buffer_size
variable to make it even faster.
See section SHOW VARIABLES
.
INSERT DELAYED
文の使用で、より速くなるでしょう。 See section INSERT
構文.
MyISAM
では、複数の SELECT
が走っているテーブルに対して、
同時に、レコードを挿入できます。 ただしそのテーブルに対して
レコードの削除がない場合に。
LOAD DATA INFILE
を
使用します。 これはたくさんの INSERT
文の発行に比べて通常 20倍 程度
速くなります
See section LOAD DATA INFILE
構文.
LOAD DATA INFILE
の実行を速くすることが可能です。
以下の手順で行います:
CREATE TABLE
. For example, using
mysql
or Perl-DBI.
FLUSH TABLES
の実行。 あるいは mysqladmin flush-tables
コマンドの実行。
myisamchk --keys-used=0 -rq /path/to/db/tbl_name
の使用。
これは指定されたテーブルから全てのインデックスを削除します。
LOAD DATA INFILE
を使用してデータを入れます.
これはいかなるインデックスも更新しないでしょうし、そのため、速くもなるでしょう。
myisampack
on it to make it smaller. See section 圧縮テーブルの特徴.
myisamchk -r -q /path/to/db/tbl_name
でインデックスを再構築.
これは disk に書き込む前にインデックスをメモリに作成します。
これは多くのディスクシークを避けることが出来るのでとても速くなります。
でき上がったインデックスツリーは、バランスのよいものになります。
FLUSH TABLES
の実行。 あるいは mysqladmin flush-tables
コマンドの実行。
LOAD DATA INFILE
に組み込むかもしれません。
LOAD DATA INFILE
also does the above optimization if
you insert into an empty table; the main difference with the above
procedure is that you can let myisamchk
allocate much more temporary
memory for the index creation that you may want MySQL to allocate for
every index recreation.
Since MySQL 4.0 you can also use
ALTER TABLE tbl_name DISABLE KEYS
instead of
myisamchk --keys-used=0 -rq /path/to/db/tbl_name
and
ALTER TABLE tbl_name ENABLE KEYS
instead of
myisamchk -r -q /path/to/db/tbl_name
. This way you can also skip
FLUSH TABLES
steps.
mysql> LOCK TABLES a WRITE; mysql> INSERT INTO a VALUES (1,23),(2,34),(4,33); mysql> INSERT INTO a VALUES (8,26),(6,29); mysql> UNLOCK TABLES;主な速度差は、全ての
INSERT
構文でインデックスバッファが一度だけディスク
にフラッシュされることです。通常は INSERT
構文があるのと同じくらい多くの
インデックスバッファフラッシュがあります。単一構文の全てのレコードは、ロック
なしで挿入できます。
For transactional tables, you should use BEGIN/COMMIT
instead of
LOCK TABLES
to get a speedup.
ロックも複数接続テストの合計時間を低くしますが、いくつかのスレッドの最大
待ち時間は上がります(ロックを待っているから)。
例えば:
thread 1 does 1000 inserts thread 2, 3, and 4 does 1 insert thread 5 does 1000 insertsロックを使用しない場合、2, 3 そして 4 は 1 と 5 の前に終ります。ロックを 使用する場合、2,3,4 は 1 や 5 の前に終わることはおそらくありませんが、合 計時間は約 40 % 速くなります。
INSERT
, UPDATE
, DELETE
は、 MySQL ではとても速い
ので、
1 行で約 5 つ以上、値を 挿入・更新 をする操作に対して、
ロックを追加すれば、全般的により良い性能が得られます。
とても多い insert を行なう場合、
他のスレッドにそのロックしたテーブルへのアクセスを与えるために 、
だいたい 1000 レコードごとに一度、UNLOCK TABLES
した後に
LOCK TABLES
を行います。 これでもまだ良い性能が得られます。
もちろん LOAD DATA INFILE
はとても速いです。
LOAD DATA INFILE
と INSERT
を共に速くするためには、
キーバッファを増やします。 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:
thread_cache_size
variable. See section サーバーパラメーターのチューニング.
EXPLAIN
コマンドでこれが行えれます。
See section EXPLAIN
構文 (SELECT
についての情報を得る).
MyISAM
では、大量に変更されるようなテーブルに対して、
複雑な SELECT
クエリを避けるように試みます。
これはテーブル・ロックの問題を避けるためです。
MyISAM
テーブルでは、あるテーブルにレコードが挿入(削除は無しで)
されている最中に、同時に、同じテーブルからデータを読むことが可能です。
これがあなたにとって重要項目であるなら、
レコードの削除の必要のない方法や、多くのレコードを削除した後に
OPTIMIZE TABLE
を実行することを、考慮すべきです。
ALTER TABLE ... ORDER BY expr1,expr2...
if you mostly
retrieve rows in expr1,expr2...
order. By using this option after big
changes to the table, you may be able to get higher performance.
SELECT * FROM table_name WHERE hash=MD5(CONCAT(col1,col2))
AND col_1='constant' AND col_2='constant'
VARCHAR
や BLOB
フィールドを避けるように試みるべきです。
You will get dynamic row length as soon as you
are using a single VARCHAR
or BLOB
column. See section MySQL テーブル型.
UPDATE table SET count=count+1 WHERE index_column=constant
の更新は
とても速いです!
これは、MySQL MyISAM テーブルや ISAM テーブルのような
テーブル・ロッキング(multiple readers / single writers)をもつ
データベースを使う上で、本当に重要なことです。
This will
also give better performance with most databases, as the row locking
manager in this case will have less to do.
INSERT /*! DELAYED */
を使用します。
これは、一回のディスクへの書き込みで、多くのレコードがかかれるので、
速くなります。
INSERT /*! LOW_PRIORITY */
を使用します。
SELECT /*! HIGH_PRIORITY */
を使用します。
これは、たとえ誰かが書き込みを待っていたとしても、その SELECT は
実行されます。
INSERT
文の使用。 これは多くのレコードを一つの SQL コマンドで
挿入することが出来ます。
(多くの SQL サーバーがこれをサポートしています)
LOAD DATA INFILE
を使用します。
This is
faster than normal inserts and will be even faster when myisamchk
is integrated in mysqld
.
AUTO_INCREMENT
を使用します。
OPTIMIZE TABLE
を時々使用します。
See section OPTIMIZE TABLE
構文.
HEAP
テーブルをスピードアップのために使用します.
See section MySQL テーブル型.
customer_name
の
かわりに name
を使うとか)。 他の SQL サーバーへの移植を考慮するなら、
名前は 18 文字より短くすべきです。
MyISAM
を直接アクセスすることは、
SQL インターフェースを介してアクセスするよりも、2〜5倍速くなるでしょう。
これを可能にするには、そのデータは、アプリケーションと同じマシン上になくてはなら
ず、通常、一つのプロセスだけでアクセスされるべきです。
(なぜなら、外部ファイルロックは、とても遅いから)。
上の問題は、MySQL サーバー内の MyISAM
のローレベルのコマンドの
導入で解決できるでしょう。 (これはよりよいパフォーマンスを得ることの出来る、
簡単な方法の一つです)。
By carefully designing the database interface,
it should be quite easy to support this types of optimization.
DELAY_KEY_WRITE=1
が定義されたテーブルは、インデックスの更新が速くなります。
これはそのインデックス・ファイルが閉じられるまでディスクに記録されないからです。
したがって、なにかが途中で mysqld
をキルしてもテーブルが大丈夫なようにす
るため、mysqld
を起動する前には、myisamchk
をそれらのテーブルに
対して実行すべきです。
As the key information can always be generated
from the data, you should not lose anything by using DELAY_KEY_WRITE
.
付録に、異なるロックする方法に関する議論があります。 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
オプションと共に INSERT
、 UPDATE
、
DELETE
構文、または 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)
大きなテーブルには、 テーブルのロックはレコードのロックよりはるかに良いですが、
いくつかの落とし穴があります。
BDB
と InnoDB
のテーブルでは、 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
を発行するようにします。
テーブルロッキングは以下の場合にはあまり良くありません:
SELECT
を発行。
UPDATE
を発行;
このクライアントは先の SELECT
が完了するまで待ちます
SELECT
構文を発行;
UPDATE
は SELECT
よりも高い優先度を持つので、
この SELECT
は先の UPDATE
が完了するまで待ちます。
これは一番最初の SELECT
が 終了するまで待たされます!
full disk
のような待機状態になっている場合、
問題のテーブルにアクセスを行おうとした全てのスレッドもまた、
より多くのディスク・スペースが利用可能になるまで待機状態に入ります。
この問題のいくつかの可能な解決は以下の通りです:
SELECT
構文を速く実行できるように試みます; これを行うにあたり、
いくつかのサマリーテーブルを作成しなければならないかもしれません.
mysqld
を --low-priority-updates
オプションで起動。
これは全てのあるテーブルを更新する構文に対して、 SELECT
構文よりも
低い優先度を与えます。 この場合、前述のシナリオ中の最後の SELECT
構文は
INSERT
構文が完了する前に実行されます。
LOW_PRIORITY
属性指定を用いて、 INSERT
,UPDATE
,DELETE
構文に低い優先度を与えることも出来ます。
WRITE
ロックの後に READ
ロックを与えるために、
max_write_lock_count
を低い値にして mysqld
を開始します。
SET LOW_PRIORITY_UPDATES=1
(ver. 4.0.3 未満では SET SQL_LOW_PRIORITY_UPDATES=1
)
を使用して、
ある特定のスレッドからの全ての更新を、低い優先度に指定する事ができます。
See section SET
構文.
HIGH_PRIORITY
属性を用いて、特定の SELECT
がとても重要であると
指定することが可能です。. See section SELECT
構文.
INSERT
と SELECT
をあわせて使用した場合に問題が起きた場合、
新しい MyISAM
テーブルに切り替えます。 これは SELECT
と INSERT
を同時に行えます。
INSERT
と SELECT
構文を主に混在させるのなら、
INSERT
の DELAYED
属性指定はこの問題を解決させるでしょう。
See section INSERT
構文.
SELECT
と DELETE
で問題があるなら、
DELETE
の LIMIT
オプションが助けになるでしょう。
See section DELETE
構文.
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 テーブル型.
以下に挙げるテクニックを使用すれば、テーブルでのパフォーマンスの向上、 保存領域の縮小化が可能でしょう:
MEDIUMINT
は INT
より良いでしょう。
NOT NULL
に定義してください。これは全てをより速くし、
各フィールド毎に1ビットを節約します。
Note that if you really need
NULL
in your application you should definitely use it. Just avoid
having it on all columns by default.
VARCHAR
, TEXT
, BLOB
) を持たない場合は、
固定サイズレコード形式が使用されます。
これはかなり速いです。しかしあいにくいくらかの領域を浪費します。
See section MyISAM
Table Formats.
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:
WHERE
節にマッチした行の素早い検索
MAX()
or MIN()
value for a specific indexed
column. This is optimized by a preprocessor that checks if you are
using WHERE
key_part_# = constant on all key parts < N. In this case
MySQL will do a single key lookup and replace the MIN()
expression with a constant. If all expressions are replaced with
constants, the query will return at once:
SELECT MIN(key_part2),MAX(key_part2) FROM table_name where key_part1=10
ORDER BY key_part_1,key_part_2
)。
もし DESC
指定があれば、全てのキーは逆順に読まれます。
See section How MySQL Optimises ORDER BY
.
SELECT key_part3 FROM table_name WHERE key_part1=1
以下のような SELECT
文を発行したとします:
mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
もし col1
と col2
に複数フィールドインデックスが定義されている場合、
すぐに思ったとおりの結果が得られます。
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:
LIMIT
to only retrieve
part of the rows, MySQL will use an index anyway, as it can
much more quickly find the few rows to return in the result.
MySQL の全てのフィールドはインデックスを持つことができます。
適切なフィールドでのインデックスの使用は、SELECT
の
性能を向上する最良の方法です。
キーの最大数と最大インデックス長は storage engine 毎に定義されます。 See section MySQL テーブル型。すべてのテーブルハンドラで少なくとも 16 個のキーと少な くとも合計 256 バイトのインデックス長を持つことができます。
CHAR
と VARCHAR
フィールドには接頭部にインデックスを持つことが
できます。フィールド全体をインデックス化するより、
これははるかに早く、少ないディスク容量でできます。
CREATE TABLE
構文でフィールドにインデックスを作るには、
以下のようにします:
KEY index_name (col_name(length))
以下の例は name
フィールドの最初の10文字にインデックスを創り出します:
mysql> CREATE TABLE test ( -> name CHAR(200) NOT NULL, -> KEY index_name (name(10)));
BLOB
と TEXT
フィールドでは、そのフィールドの頭の部分に
インデックスを張らなくてはなりません。
フィールドの全体にインデックスは張れません。
MySQL バージョン 3.23.23 以降では、特殊な FULLTEXT
イン
デックスを生成することもできます。これは全文検索に使用されます。
MyISAM
テーブル型だけが FULLTEXT
インデックスをサポートしま
す。これは CHAR
, VARCHAR
と TEXT
フィールドだけに生成できます。イ
ンデックスは常にフィールド全体に対して行なわれ、部分インデックスはサポート
されません。詳細は section MySQL Full-text Search.
MySQL は異なるフィールドのセットに一つのインデックスを持つことができます。
インデックスは最大15個のコラムまで許されます。
(CHAR
と VARCHAR
フィールドの接頭部をインデックスとして使用できます)
複数フィールドインデックスは、 ソートされた配列(インデックス化されたフィールドの値が結合されている配列) を扱うことができます。
インデックス化されたコラムに対して、既知の値を 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_name
と first_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つスレッドはそれぞれ別の異なる状態を持つという
問題を最小化するため、テーブルは同時に動作する各スレッドにより個々に
オープンされます。 これは少しメモリを食いますが、パフォーマンスは良くなります。
ISAM
と MyISAM
テーブルでは、データファイルのために
一つのファイル記述子を使用します。
インデックスファイル記述子は全てのスレッド間で共有されます。
You can read more about this topic in the next section. See section MySQL はどのようにテーブルのオープン & クローズを行なうか?.
table_cache
, max_connections
, max_tmp_tables
は
サーバーが開いた状態にしておく事が出来るファイルの最大数に影響します。
もしこれらの変数のうちの一つ、あるいは複数を増加させるなら、
あなたのオペレーティング・システムの、1 プロセスあたりに開かれる
ファイル・デスクリプタ の最大値を増やすことになるかもしれません。
多くのシステムではこの制限を増やすことが可能です。
これをどうやって行うかは、あなたの使用している OS のドキュメントを見てください。
制限値の変更方法は、システムによってまちまちだからです。
table_cache
は max_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:
table_cache
entries and
a thread is no longer using a table.
mysqladmin refresh
or
mysqladmin flush-tables
.
FLUSH TABLES
statement.
キャッシュがいっぱいになった場合、サーバーは以下の処置を取って キャッシュを使用できるように配置します:
テーブルは各同時アクセスに (再び) オープンされます。これは、同じテーブルで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
.
もしたくさんのファイルが一つのディレクトリにある場合、オープン、クローズ、
create 操作は遅くなるでしょう。 もし SELECT
文を多くのテーブルに対し
実行した場合、テーブルキャッシュが一杯ならば、このオーバーヘッドは多くなるでしょ
う。
なぜなら、それぞれのテーブルにつきオープンし、クローズしなくてはならないからです。
このオーバーヘッドを緩和するには、テーブルキャッシュを大きくします。
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.
--skip-external-locking
(ver.4.0.3未満では --skip-locking
) MySQL オプション
を使用します。
Note that this will not impact MySQL's functionality as
long as you only run one server. Just remember to take down the server (or
lock relevant parts) before you run myisamchk
. On some system
this switch is mandatory because the external locking does not work in any
case.
MIT-pthread でコンパイルする時は --skip-external-locking
(ver.4.0.3未満では --skip-locking
) がデフォルトです。
これは全てのプラットフォームで MIT-pthread が flock()
を完全にサポートし
ていないためです。
It's also on default for Linux
as Linux file locking are not yet safe.
--skip-external-locking
(ver.4.0.3未満では --skip-locking
) が使用できないただ一つの状態は、
もしあなたが複数の MySQL サーバー (クライアントではない) を
同じデータに対して走らせている場合です。
You can still use LOCK TABLES
/UNLOCK TABLES
even if you
are using --skip-external-locking
(ver.4.0.3未満では --skip-locking
)
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 の後につけると、そのオプションは反映されません。
次のテストの多くは 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:
pgcc
を使用して -O6
で全てをコンパイルすると、
gcc
2.95.2 より、mysqld
サーバーは 1% 速くなります。
-static
) 無し)の場合、結果は 13% 遅くなります。
Note that you still can use a dynamic linked
MySQL library. It is only the server that is critical for
performance.
mysqld
binary with strip libexec/mysqld
,
the resulting binary can be up to 4% faster.
localhost
へ接続する場合、MySQL はデフォルトではソケット
を使用します)。
--with-debug=full
でコンパイルすると、ほとんどのクエリで 20% 遅くな
りますが、いくつかのクエリは実質的にはもっと長くなります(MySQL ベ
ンチマークでは 35% 遅くなりました)。
--with-debug
を使用すると、15% だけ遅くなります。
By starting a mysqld
version compiled with --with-debug=full
with --skip-safemalloc
the end result should be close to when
configuring with --with-debug
.
gcc
3.2
gcc
2.95.2 でオプション -mcpu=v8
-Wa,-xarch=v8plusa
をつけてコンパイルすると 4% 良い性能が得られます。
--log-bin
での実行は mysqld を 1% 遅くします。
-fomit-frame-pointer
or -fomit-frame-pointer -ffixed-ebp
makes mysqld
1-4% faster.
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.
以下に mysqld
サーバーがどのようにメモリーを使用するか、いくつか示します。
サーバーに与える変数名は、サーバーのメモリーの使用方に関連した名前となっています:
key_buffer
) は全てのスレッドで共有され、
残りは必要時に割り当てられます。 See section サーバーパラメーターのチューニング.
thread_stack
), 接続バッファ(variable
net_buffer_length
), 結果バッファ(variable
net_buffer_length
)。接続バッファと結果バッファは必要となった時、
動的に最大 max_allowed_packet
まで増えます。
クエリが走っている時、そのクエリの文字のコピーが割り当てられます。
ISAM
/ MyISAM
だけが、memory mapped されます。
これは 4GB の 32bit メモリ空間は多くの大きなテーブルを扱うには小さいためです。
64bit アドレス空間を持つシステムがより普及すれば、我々は mmemory mapping を通常
にサポートします。
record_rnd_buffer
).
HEAP
)のテーブルです。大きなレコー
ドサイズ (= 全フィールド長の合計) を持つ一時テーブルまたは、BLOB
を含む
テーブルはディスク上に置かれます。
MySQL バージョン 3.23.2 以前での問題は、HEAP
テーブルが
tmp_table_size
のサイズを越えると、エラー The table tbl_name is full
が出ることです。将来我々は、必要時にメモリ (HEAP
) テーブルをディスクベー
ス (MyISAM
) テーブルに自動的に変更することにより、これを修正します。この
問題を回避するため、mysqld
への tmp_table_size
オプションま
たはクライアント側で SQL オプション BIG_TABLES
(ver.4.0.3未満では SQL_BIG_TABLES
) で増加できます。
See section SET
構文.
MySQL バージョン 3.20 では、一時テーブルの最大サイズは
recordbuffer*16
でした。そのため、このバージョンを使用していると、
recordbuffer
を追加する必要があります。 mysqld
を --big-tables
で
開始することで、常に一時テーブルをディスク上に格納できます。しかしこれは
多くの複雑なクエリの速度に影響します。
malloc()
と free()
で行なわれます)。
3 * n
のサイズのバッファが割り当てられます。
( n
は BLOB
型のフィールドの長さを含めない、一レコードの最大長です )
BLOB
は 5 から 8 バイト + BLOB
データの長さを使用します。
The ISAM
/MyISAM
table handlers will use one extra row
buffer for internal usage.
BLOB
を持つ各テーブルでは、より大きな BLOB
の読み込みでバッファ
は動的に拡大されます。テーブルのスキャンをする場合、割り当てられたバッファは最
も大きい BLOB
と同じ大きさになります。
mysqladmin flush-tables
は使用されていない全てのテーブルをクローズし、
使用されている全てのテーブルを、実行中スレッドが終った時にクローズするよ
うにマークします。これは多くの使用メモリを解放するのに有効です。全てのロ
グファイルもクローズと再オープンされます。
mysqld 実行時、ps
や他のプログラムは、それが多くのメモリ
を使用していると報告するでしょう。これは異なったメモリアドレス上のスレッ
ドスタックによって発生します。例えば、Solaris ps はスタック間の未使用メ
モリを使用メモリとして計算します。'swap -s' で有効なスワップをチェックす
ることでこれを確かめられます。我々は市販のメモリリーク検出プログラムで
mysqld
をテストしました。そのため、メモリリークは全くありません。
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_name
に DEFAULT
を指定します。
CHARACTER SET
オプションを設定するための構文は、
他のオプションを設定する構文と異なっていることに注意してください.
PASSWORD = PASSWORD('some password')
PASSWORD FOR user = PASSWORD('some password')
mysql
データベースにアクセスができるユーザーだけが実行できます。
ユーザは user@hostname
形式で与えなくてはなりません。
ここで user
と hostname
は、mysql.user
テーブルの
User
, Host
フィールドに登録されていなくてはなりません。
例えば、User
と Host
フィールドが '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
構文は、
対象となるテーブルを処理中の SELECT
や LOCK 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
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
構文から返されるレコードの最大値。
もし SELECT
に LIMIT
節を使用している場合、LIMIT
は
SQL_SELECT_LIMIT
の値より優先されます。
新しい接続におけるこの値の標準値は ``unlimited''.
もしリミットを変えているならば、SQL_SELECT_LIMIT
に
DEFAULT
を指定することにより、標準値に戻すことができます。
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
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
コマンドに従って使用される値をセットします。
これは更新ログによって使用されます。
hdparm
to configure your disk's interface! The
following should be quite good hdparm
options for MySQL (and
probably many other applications):
hdparm -m 16 -d 1Note that the performance/reliability when using the above depends on your hardware, so we strongly suggest that you test your system thoroughly after using
hdparm
! Please consult the hdparm
man page for more information! If hdparm
is not used wisely,
filesystem corruption may result. Backup everything before experimenting!
-o async
option to set the filesystem to be updated asynchronously. If your computer is
reasonably stable, this should give you more performance without sacrificing
too much reliability. (This flag is on by default on Linux.)
-o noatime
option.
テーブルとデータベースのファイルを MySQL のデータベースディレクトリーから 違う場所に移動し、 それに対してシンボリックリンクを張ることができます。例 えば、もっと空き容量のあるファイルシステムへデータベースを移すため、あるい はテーブルを異なるディスクに広げることでシステムのスピードを増加するために これを行ないたくなるでしょう。
The recommended way to do this, is to just symlink databases to a different disk and only symlink tables as a last resort.
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
テーブルは db2
の tbl_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 上で、異なるディスクにデータを分割する.
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).
mysqld
is
not running) or with the INDEX/DATA DIRECTORY="path-to-dir"
command
in CREATE TABLE
. See section CREATE TABLE
構文.
myisamchk
will not replace a symlink with the data or index file but
work directly on the file the symlink points to. Any temporary files
will be created in the same directory where the data or index file is
located.
mysqld
as root
or allow
persons to have write access to the MySQL database directories.
ALTER TABLE RENAME
and you don't move
the table to another database, the symlinks in the database directory
will be renamed to the new names and the data and index files will be
renamed accordingly.
ALTER TABLE RENAME
to move a table to another database,
the table will be moved to the other database directory and the old
symlinks and the files they pointed to will be deleted. (In other words,
the new table will not be symlinked.)
--skip-symlink
option to mysqld
to ensure that no one can drop or rename a file
outside of the mysqld
data directory.
Things that are not yet supported:
ALTER TABLE
ignores all INDEX/DATA DIRECTORY="path"
options.
CREATE TABLE
doesn't report if the table has symbolic links.
mysqldump
doesn't include the symbolic link information in the output.
BACKUP TABLE
and RESTORE TABLE
don't respect symbolic links.
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.
この節は MySQL で文字列と数値を記述するさまざまな方法を説明します。 MySQL でのこれらの基本型の取り扱い時に、出会うであろうさまざまな ニュアンスと ``了解'' もカバーします。
文字列は文字の並びです。引用符(`'')または二重引用符(`"')で括ら れます(後者は ANSI モードで実行していない場合のみ)。 例:
'a string' "another string"
文字列中では、いくつかのシーケンスは特別な意味を持ちます。これらのシーケ ンスのそれぞれはエスケープ文字として知られるバックスラッシュ (`\')で始まります。MySQL は次のエスケープシーケンスを認識 します。
\0
NUL
) 文字。
\'
\"
\b
\n
\r
\t
\z
mysql database < filename
を使用しようとする場合に問題になります)。
\\
\%
\_
_
文字。これは `_' がワイルドカード文字として解釈される文脈
で、_
そのものを検索するために使用されます。
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
\
'
"
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
整数が浮動小数点の文脈で使用されるかもしれません; この場合、浮動小数点に 変換されます。
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 より前のバージョンでは、名前の規則は次に従います:
mysqld
に --default-character-set
オプションを
与えることで変更できます. (3.23.14 以上の場合のみ。
それ以前のバージョンでは MySQL 再コンパイルが必要)
See section データとソートに使用されるキャラクター・セット.
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
を記述する必要はありません。例えば、テー
ブル t1
と t2
がそれぞれフィールド c
を含み、t1
と
t2
の両方を使用する SELECT
ステートメントで c
を取
り出すとします。この場合、c
はステートメントで使用されるテーブル
間で唯一でないので曖昧です。そのため、t1.c
または t2.c
と
記述するこよによりどちらのテーブルを意味するかを示す必要があります。同様
に、データベース db1
のテーブル t
とデータベース
db2
のテーブル t
から取り出す場合、これらのテーブル中の項
目は、db1.t.col_name
と db2.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_table
と MY_TABLE
の両方を
参照しているからです:
mysql> SELECT * FROM my_table WHERE MY_TABLE.col=1;
フィールド名とフィールドの別名は全ての場合でケース非依存です。
テーブルの別名はケース依存です。
以下のクエリは動きません。なぜなら a
と A
のエイリアスを両方
参照しているからです:
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.
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
を対話モードで実行している場合と、
mysql
にファイルを読み込ませている場合 ( mysql < some-file
) の
両方で現れます。
MySQL は ANSI SQL コメントの `--' をサポートしません。 See section コメント開始としての `--'.
共通の問題は、フィールドの名前を、 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.
ACTION
BIT
DATE
ENUM
NO
TEXT
TIME
TIMESTAMP
MySQLは多くのフィールド型をサポートしており、それらは3つのカテゴリに グループ化されます: 数値型、日付及び時間型、そして文字列(文字)型。 この章ではまず、利用できる型の概要から始まり、それから各カテゴリの各フィールド 型の所要記憶容量の要約と、型の属性についてのより詳細な情報を提供します。 概要は意図的に簡潔にまとめています。値として指定できる書式のようなフィールド 型固有の付加情報は、詳細の説明部にて調べて下さい。
MySQLでサポートされるフィールド型は以下に示す通りです。 後に続く文字の意味は説明のために使われます:
M
D
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]
-128
〜127
。符号なしの範囲は
0
〜255
。
BIT
BOOL
TINYINT(1)
.
SMALLINT[(M)] [UNSIGNED] [ZEROFILL]
-32768
〜32767
。
符号なしの範囲は 0
〜65535
。
MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL]
-8388608
〜8388607
。
符号なしの範囲は 0
〜16777215
INT[(M)] [UNSIGNED] [ZEROFILL]
-2147483648
〜2147483647
。符号なしの範
囲は 0
〜4294967295
INTEGER[(M)] [UNSIGNED] [ZEROFILL]
INT
の同義語です。
BIGINT[(M)] [UNSIGNED] [ZEROFILL]
-9223372036854775808
〜9223372036854775807
。
符号なしの範囲は 0
〜18446744073709551615
。
BIGINT
フィールドについて意識すべきことのいくつか:
BIGINT
または DOUBLE
で行われるため、
符合無しの 9223372036854775807
(63 bits) よりも大きな整数を
ビット関数以外で使用すべきではありません!
それを行なうと、結果の最後の桁のいくつかは不正になるでしょう
BIGINT
を DOUBLE
に変換する時の丸めエラーのためです。
MySQL 4.0 can handle BIGINT
in the following cases:
BIGINT
column.
MIN(big_int_column)
and MAX(big_int_column)
.
+
, -
, *
, etc.) where
both operands are integers.
BIGINT
フィールドの正確な整数値を常に格
納することができます。この場合、double 表現を介在しません。
-
、+
及び*
は、両方の引数がINTEGER
値の時、
BIGINT
演算を使うことに注意して下さい! これは、2つの大きな整数の
かけ算を行なう(又は整数を返す関数の結果が大きな整数である)時、
結果が9223372036854775807
よりも大きい場合に予期しない結果を
受け取ることがあるということを意味しています。
FLOAT(precision) [UNSIGNED] [ZEROFILL]
precision
が <=24
で、倍精度浮動小数点数では 25〜53 の間です。
これらの型は次で述べるFLOAT
やDOUBLE
型に似ています。
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]
-3.402823466E+38
〜-1.175494351E-38
、 0
、
1.175494351E-38
〜3.402823466E+38
です。
Version 4.0 以上では、If
UNSIGNED
is specified, negative values are disallowed.
M
は表示幅で D
は小数部桁数です。引数が無いか引数が24以下の FLOAT
は単精度浮動小数点数を意味します。
DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
-1.7976931348623157E+308
〜-2.2250738585072014E-308
、 0
、2.2250738585072014E-308
〜1.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]
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
値をYYYYMMDDHHMMSS
、YYMMDDHHMMSS
、
YYYYMMDD
又はYYMMDD
という書式で表示し、それはM
に14
(もし
くは誤ってそれ以上の値を指定した時)、12
、8
又は6
のいずれが指
定されたかに依存します。しかしながらTIMESTAMP
フィールドへの値の割当ては、
文字列もしくは数値のいずれかの使用が許されます。
TIMESTAMP
フィールドは、最後に操作された時刻を自動的に設定するので、
INSERT
やUPDATE
操作の時刻を記録するのに役立ちます。
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)]
1901
〜2155
, 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 ではデフォルトです。
CHAR
は CHARACTER
の略記です。
MySQL は CHAR(0)
型のフィールドの生成を許します。これは主
に、実際にはもう値が使われていないフィールドが存在することに依存しているよ
うないくつかの古いアプリケーションに対応する必要がある時に便利です。2つの
値だけを取ることができるフィールドを必要とする時にもとても良いことです:
NOT NULL
として定義されていない CHAR(0)
は1ビットだけを占有
し、2つの値だけを取ることができます: NULL
または ""
。
See section CHAR
型と VARCHAR
型.
CHAR
CHAR(1)
.
[NATIONAL] VARCHAR(M) [BINARY]
M
の範囲は 0 から 255 文字です。
(MySQL Version 4.0.2 未満では 1 から 255 です)
BINARY
キーワードが与えられない場合、ソートと比較はケースに依存しません。
See section 暗黙のフィールド定義変更.
VARCHAR
は CHARACTER VARYING
の略記です。
See section CHAR
型と VARCHAR
型.
TINYBLOB
TINYTEXT
TEXT
/BLOB
。
See section 暗黙のフィールド定義変更. See section BLOB
と TEXT
型.
BLOB
TEXT
TEXT
/BLOB
。
See section 暗黙のフィールド定義変更. See section BLOB
と TEXT
型.
MEDIUMBLOB
MEDIUMTEXT
TEXT
/BLOB
。
See section 暗黙のフィールド定義変更. See section BLOB
と TEXT
型.
LONGBLOB
LONGTEXT
TEXT
/BLOB
。
See section 暗黙のフィールド定義変更。注意: サーバ/クライアントプロトコルと
MyISAM テーブルは、通信パケット単位 / テーブルレコードで、現在 16M の制限
があるため、この型の範囲全体はまだ使用できません。See section BLOB
と TEXT
型。
ENUM('value1','value2',...)
'value1', 'value2',...
(又は
NULL
)から選ばれます。ENUM
は最大65535個の固有値を持つことができます
。 See section ENUM
型.
SET('value1','value2',...)
'value1', 'value2',...
から選ばれなければなりません。
SET
は、最大 64個の要素を持つことができます。See section SET
型.
MySQL は ANSI/ISO SQL92 数値型をすべてサポートします。これらの型
は正確な数値データ型(NUMERIC
, DECIMAL
, INTEGER
,
SMALLINT
)、近似数値型(FLOAT
, REAL
, DOUBLE
PRECISION
)を含みます。キーワード INT
は INTEGER
の同義語で、
DEC
は DECIMAL
の同義語です。
MySQL では NUMERIC
と DECIMAL
型は、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)
と等しいです。同様に、
構文 DECIMAL
は DECIMAL(p,0)
と等しいです。ここで p
の値の決定は実装に許されてます。DECIMAL
/NUMERIC
データ型のこ
れらの異なる形式は、MySQL は現在サポートしていません。この型の主
な利益は精度と大きさの両方を明示的に制御する機能から引き出されるので、これ
は通常深刻な問題ではありません。
DECIMAL
と NUMERIC
値は、値の小数の精度を維持するため、バイ
ナリ浮動小数点数としてではなく、文字列として格納されます。1文字は値のそれ
ぞれの桁(scale
> 0 の場合)と `-' 記号(負数の場合)に使用されま
す。scale
が 0 の場合、DECIMAL
と NUMERIC
値は小数点
と小数部を含みません。
DECIMAL
と NUMERIC
値の最大範囲は DOUBLE
と同じです。
しかし DECIMAL
や NUMERIC
フィールドに与えられる実際の範囲は
フィールドに与えられた precision
と scale
によって強制されま
す。このフィールドに、指定された scale
で許されるよりも多い桁の小数
部を持つ数値が割り当てられた場合、値はその scale
に丸められます。
DECIMAL
や NUMERIC
フィールドに、指定された(またはデフォルト
の) precision
と scale
で示された範囲を超えた大きさの値を割
り当てた時、MySQL はその範囲の対応する最大値を表す値を格納します。
ANSI/ISO SQL92 標準に対する拡張として、上の表にリストしたように、
MySQL は整数型 TINYINT
, MEDIUMINT
, BIGINT
も
サポートします。MySQL によってサポートされる他の拡張として、オプ
ションで、型の基本キーワードに続けて括弧内に指定する整数値の表示幅(例えば
INT(4)
)があります。このオプションの幅指定は、フィールドに指定された
幅よりも少ない幅の値の表示の左側を埋めるために使用されます。しかしフィール
ドに格納することができる値の範囲や、フィールドに指定された幅を超える幅の値
について表示される桁数は制約されません。オプションの拡張属性
ZEROFILL
を指定して使用された場合、デフォルトの埋められる空白は 0
で置き換えられます。例えば、INT(5) ZEROFILL
として宣言されたフィー
ルドでは、値 4
は 0004
として取り出されます。注意: 整数フィー
ルド内に表示幅よりも大きい値を格納する場合、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番目の数値は、格納、表示される小数部の桁数を指定します(DECIMAL
と
NUMERIC
と同様)。MySQL がフィールドに指定されたよりも大き
い小数部の桁数を持つ数値をこのフィールドに格納する時、値の格納時に余計な桁
を取り除くように値が丸められます。
REAL
と DOUBLE PRECISION
型は精度指定を許しません。
ANSI/ISO SQL92 標準に対する拡張として、MySQL は DOUBLE
を
DOUBLE PRECISION
型の同義語として認識します。REAL
の精度は
DOUBLE PRECISION
の指定よりも小さいことを要求する標準と異なり、
MySQL はどちらも8バイトの倍精度小数点の値として実装しています
(非"ANSI モード"で実行した場合)。移植性を最大にするためには、近似数値
データ値の格納を要求するコードは、精度や小数部桁数の指定無しの
FLOAT
か DOUBLE PRECISION
を使用すべきです。
フィールドの型の値の許容範囲を超えた数値を代入しようとすると、MySQL は その値を許容範囲いっぱいに切り詰め、その結果を代わりに代入します。
例えば、 INT
フィールドの範囲は -2147483648
から 2147483647
です。
もし -9999999999
を INT
フィールドに挿入しようとすると、値は範囲の
最低値に修正され、 -2147483648
が代わりに代入されます。同様に、
9999999999
の場合、 2147483647
が代わりに代入されます。
そして、INT
フィールドが符号無しの場合、フィールドの範囲の大きさは
同じですが、限界値は 0
と4294967296
になります。
もし -9999999999
と 9999999999
を代入しようとすると、
値は 0
と 4294967296
として代入されます。
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-00
や
1999-01-00
のような日付を単純に登録できます(もちろん、このような日
付を DATE_SUB()
や DATE_ADD
のような関数で使用して、正しい値
が返ることは期待できません)。
これは、日付と時間型で作業する場合に、一般的に考慮しなければならないことです:
'98-09-04'
)でなくてはなりません。
月-日-年 や 日-月-年 の様などこでも使われているような形であってはなりません。
(例えば、'09-04-98'
や'04-09-98'
).
TIME
値が適切なTIME
の範囲の限界値に切り詰められる
ことです。)
以下に、それぞれの型の `ゼロ' の形式を示します:
フィールドタイプ | `ゼロ'値 |
DATETIME | '0000-00-00 00:00:00'
|
DATE | '0000-00-00'
|
TIMESTAMP | 00000000000000 (長さは表示サイズに依存し
ます)
|
TIME | '00:00:00'
|
YEAR | 0000
|
'0'
又は 0
を使用することにより、より簡潔に書くこともで
きます。
NULL
に変換されます。
これは ODBC がこれらの値を扱えないからです。
MySQL 自体は2000年問題に対して安全です(see section 2000 年対応)が、 MySQL に提示される入力値に関してはそうではありません。2桁の 年の入力は何世紀なのかわからないので全て曖昧です。このような値は MySQL が内部で年に4桁を使っていることから4桁の形式に変換されてしまいます。
MySQL は曖昧な日付を DATETIME
, DATE
, TIMESTAMP
および YEAR
型に関して、以下の
ルールに従って解釈します。
00-69
の範囲の年は 2000-2069
に変換。
70-99
の範囲の年は 1970-1999
に変換。
これらのルールはデータが何を意味しているかに対して妥当な推定を与えるに 過ぎないことに注意してください。この 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
タイプは INSERT
や UPDATE
操作に自動的に
現在の日付と時刻をマークする場合に提供される型です。
もし複数の TIMESTAMP
フィールドがある場合には最初
の一つだけが自動的に更新されます。
最初の TIMESTAMP
フィールドの自動更新は以下のいずれかの条件で起こります:
INSERT
または LOAD DATA INFILE
文で指定さ
れていないとき。
UPDATE
文で指定されず、かつ、他のフィールドの値
が変わった場合。
(もともとフィールドに入っていた値と同じ値に更新しようとする UPDATE
文は
TIMESTAMP
フィールドを更新しないことに注意。なぜならあるフィールドを現在
と同じ値に変えようとしても MySQL は効率のためにそれを無視するからです。)
TIMESTAMP
フィールドを NULL
にした場合。
最初以外の TIMESTAMP
フィールドも現在の日付と時刻にすることができます。そ
れらのフィールドをNULL
または NOW()
にすることです。
どの TIMESTAMP
フィールドも明示的に望む値をセットすることで現在の日時でな
い値にすることができます。それは最初の 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
値は以下の共通フォーマットセット
のいずれかを使って指定できます:
'YYYY-MM-DD HH:MM:SS'
か 'YY-MM-DD HH:MM:SS'
の形式。
"柔軟な"書き方を許しています -- 日付や時刻の区切り文字として、いかなる句読記号
も使用できます。例えば、'98-12-31 11:30:45'
, '98.12.31 11+30+45'
,
'98/12/31 11*30*45'
, '98@12@31 11^30^45'
は等価です。
'YYYY-MM-DD'
か 'YY-MM-DD'
の形式。
これも"柔軟な"書き方ができます。
例えば, '98-12-31'
,'98.12.31'
, '98/12/31'
,
'98@12@31'
は
等価です。
'YYYYMMDDHHMMSS'
または 'YYMMDDHHMMSS'
フォーマット。
「緩やかな」文法が認められていて、句読記号は日付、時刻部分の区切り
として使えます。例えば '98-12-31 11:30:45'
, '98.12.31 11+30+45'
,
'98/12/31 11*:30*:45'
, '98@12@31 11^30^45'
は全て等価です。
'YYYY-MM-DD'
または 'YY-MM-DD'
フォーマット。
これも「緩やかな」文法が認められています。例えば '98-12-31'
,
'98.12.31'
, '98/12/31'
, '98@12@31'
は全て等価です。
'YYYYMMDDHHMMSS'
または 'YYMMDDHHMMSS'
フォ
ーマットで日時として意味のあるもの。
例えば '19970523091528'
および '970523091528'
は
'1997-05-23 09:15:28'
と解釈されます。しかし '971122129015'
は無効で
(時と分の部分がおかしい)、 '0000-00-00 00:00:00'
になります。
'YYYYMMDD'
または 'YYMMDD'
フォーマットで、
日付として意味のあるもの。
例えば '19970523'
および '970523'
は '1997-05-23'
と解釈
されます。
しかし '971332'
は無効で(月と日の部分がおかしい)、 '0000-00-00'
になります。
YYYYMMDDHHMMSS
または YYMMDDHHMMSS
のフォーマットの数値で、日時と
して意味のあるもの。例えば 19830905132800
および 830905132800
は
'1983-09-05 13:28:00'
と解釈されます。
YYYYMMDD
または YYMDD
のフォーマットの数値で日付として意味のある
もの。
例えば 19830905
および 830905
は '1983-09-05'
として解釈さ
れます。
NOW()
や CURRENT_DATE
のように
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 は「ゼロ」日付
をテーブルに挿入します。これは年と月の部分は 99
と 03
ですが日の部
分が欠けている(ゼロ)ために値が有効な日付でないために起こります。
TIMESTAMP
フィールドは有効な値を、表示サイズに関係なく指定された値を最高
精度の時間分解能で格納します。このことはいくつかの意味合いを持ちます。
年の値が二桁で指定された場合、世紀の部分がないので曖昧な値となります。 MySQL は二桁の年の値を以下に示す規則にそって変換します:
TIMESTAMP
を ALTER TABLE
を使って拡張しようとした場
合、拡張前には「隠れていた」情報が現れます。
TIMESTAMP
フィールドを縮めた場合も、値が表示された時により少ない情
報しか現れないという点を除いて、情報は失われません。
TIMESTAMP
値は最高精度の時間分解能で格納されますが、内部的に格納され
た値を直接操作できる関数は UNIX_TIMESTAMP()
のみです。他の関数はフォーマ
ットされて取り出された値について操作します。つまり、 HOUR()
や
SECOND()
などの関数は TIMESTAMP
値の対応する部分がフォーマットされた
値で含まれないと使うことができません。例えば TIMESTAMP
列の HH
の部分は
表示サイズが少なくとも10以上ないと表示されないので、それより短い TIMESTAMP
値
に HOUR()
の操作を行っても無意味な値しか得られません。
ある日付型を他の日付型のオブジェクトに拡張して指定することができます。 しかしそれは値の変化や情報の欠落を起こす可能性があります。
DATE
の値を DATETIME
か TIMESTAMP
の物に与えた場合、
時刻の部分は '00:00:00'
になります。これは DATE
値が
時刻の情報を持っていないからです。
DATETIME
か TIMESTAMP
の値を DATE
の物に与えた場合、
時刻の部分は削られます。これは DATE
値が
時刻の情報を持っていないからです。
DATETIME
, DATE
, TIMESTAMP
値は同じフォーマットのセットを使
って表現できますが、どの型も同じ値の範囲を持っているわけではないことを覚えておい
てください。例えば TIMESTAMP
値は 1970
年より前や 2037
年よ
り後の値にはできません。つまり '1968-01-01'
という値は DATETIME
や
DATE
の値としては有効ですが TIMESTAMP
の値としては無効で、
そのようなオブジェクトを指定した場合は 0
に変換されます。
'10:11:12'
は `':'' を区切り文字とする時刻のように見えますが、日
付のコンテキストで使われるとこれは '2010-11-12'
と解釈されます。
'10:45:15'
は '45'
が有効な月ではないので '0000-00-00'
に
変換されます。
00-31
, months 00-12
, years 1000-9999
.
Any date not within this range will revert to 0000-00-00
.
Please note that this still allows you to store invalid dates such as
2002-04-31
. It allows web applications to store data from a form
without further checking. To ensure a date is valid, perform a check in
your application.
00-69
の範囲にある年の値は 2000-2069
年とする。
70-99
の範囲にある年の値は 1970-1999
年とする。
TIME
型
MySQL は TIME
の値を 'HH:MM:SS'
(時の部分が大きい場合は 'HHH:MM:SS'
)
というフォーマットで扱い、また表示します。
(時の部分が大きい場合は 'HHH:MM:SS'
)。
TIME
値の範囲は '-838:59:59'
から '838:59:59'
の範囲です。
時の部分がこんなに大きいのは、TIME
型は一日すなわち24時間以内
の時刻を表現するのに用いられるだけではなく経過時間や二つの事象の間隔
(どちらも24時間を越えたり、負の数になる場合もあります)を表現すること
もあるからです。
TIME
値は様々なフォーマットで指定可能です:
'D HH:MM:SS.fraction'
というフォーマット。
(MySQLはまだこの fraction を time フィールドに保存できません)。
以下の ``柔軟な'' 文法が使用できます:
HH:MM:SS.fraction
, HH:MM:SS
, HH:MM
, D HH:MM:SS
,
D HH:MM
, D HH
または SS
。
ここで、D
は 0〜33 の間の日です。
'HHMMSS'
というように区切りのないフォーマットで時刻として有効
なもの。例えば '101112'
は '10:11:12'
と解釈されますが '1097
12'
は無効で(分の部分が無意味) '00:00:00'
になります。
HHMMSS
のフォーマットで時刻として有効なもの。
例えば 101112
は '10:11:12'
と解釈されます。
次の別の形式も解釈できます: SS
, MMSS
,HHMMSS
,
HHMMSS.fraction
。注意: MySQL はまだ fraction 部を保存でき
ません。
CURRENT_TIME
のように 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
型は様々なフォーマットで指定可能です:
'1901'
から '2155'
の範囲にある4桁の文字列
1901
から 2155
の範囲にある4桁の数値。
'00'
から '99'
の範囲にある2桁の文字列。
'00'
から '69'
までおよび '70'
から
'99'
までの範囲はそれぞれ 2000
から 2069
まで
および 1970
から 1999
までの範囲の
YEAR型に変換されます。
1
から 99
の範囲にある2桁の数値。1
から 69
まで
および 70
から 99
までの範囲は
それぞれ 2001
から 2069
までおよび 1970
から 1999
まで
の範囲の YEAR
型に変換されます。
2桁の数値の場合は2桁の文字列の場合と若干異なっている点に注意してください。
なぜなら0を数値として指定し、それを2000年として解釈させることができないからです。
その場合は文字列で '0'
または '00'
を指定しなければ
なりません。そうでなければ数値0は無効なYEAR値を示す 0000
に変換されます。
NOW()
のように 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 暗黙のフィールド定義変更.
BLOB
と TEXT
型
BLOB
は大きなバイナリ型のオブジェクトで、可変長のデータを保持できます。
4 つの BLOB
型、すなわち TINYBLOB
, BLOB
,
MEDIUMBLOB
と LONGBLOB
は保持できるデータの最大長が違うだけです。
See section 各フィールド型の所要容量.
4 つの TEXT
型、すなわち TINYTEXT
, TEXT
, MEDIUMTEXT
と LONGTEXT
は 4 つの BLOB
型に対応し、同じ最大長と
格納条件を持っています。 TEXT
と BLOB
の違いは、
TEXT
はケースに依存しないでソートと比較され、
BLOB
はケースに依存して(文字コードで)比較されることだけです。
いうならば、TEXT
は、ケースに依存しない BLOB
です。
もし BLOB
や TEXT
フィールドにそれらの最大長以上の値が与えられた
場合、その値はきっちり収まるように切り落とされます。
ほとんどの点で、TEXT
フィールドを VARCHAR
の大きい物と見なすことが
出来ます。
同様に、BLOB
フィールドは VARCHAR BINARY
フィールドの大きくなった
物です。
違いは、
BLOB
と TEXT
項に
インデックスを持つことが出来ます。それ以前のバージョンでは
インデックスをもつことが出来ません。
VARCHAR
フィールドで行っているようには、BLOB
と TEXT
フィー
ルドの値の後ろについている連続した空白文字は切り落とされません。
BLOB
と TEXT
項は DEFAULT
値を持つことが出来ません。
MyODBC
は BLOB
を LONGVARBINARY
として、
TEXT
を LONGVARCHAR
として定義します。
BLOB
と TEXT
フィールドは極端に長いので、それらを使用する際には、
いくつかの困った事にでくわすかもしれません:
GROUP BY
か ORDER BY
を BLOB
フィールドや TEXT
フィールドで使用したいなら、フィールドの値を固定長のものに変換しなくてはなりま
せん。標準的な方法は、 SUBSTRING
関数を使用することです。
たとえば:
mysql> SELECT comment FROM tbl_name,SUBSTRING(comment,20) AS substr -> ORDER BY substr;もしこれをしない場合、フィールドの最初の
max_sort_length
バイトが
ソート時に使用されます。 max_sort_length
のデフォルト値は 1024;
この値は mysqld
サーバー起動時に -O
オプションを使用することで
変更できます。
フィールドの位置を指定することによってか、エイリアスを使用することによって、
BLOB
や TEXT
の値で group 化できます。
mysql> SELECT id,SUBSTRING(blob_col,1,100) FROM tbl_name GROUP BY 2; mysql> SELECT id,SUBSTRING(blob_col,1,100) AS b FROM tbl_name GROUP BY b;
BLOB
または TEXT
オブジェクトの最大長はその型により決定されますが、
あなたがクライアントとサーバの間で実際に送ることができるは最大長は、
利用可能なメモリ量とコミュニケーションバッファのサイズによって決定されます。
メッセージバッファサイズを変えることができますが、その場合、サーバーとクライアン
ト、両方共に変更しなければなりません。See section サーバーパラメーターのチューニング.
それぞれの BLOB
, TEXT
フィールドは、一意のアロケートされたオブジェ
クトによって、内部では表されることに注意してください.。
これはテーブルが開かれるときに一度だけアロケートされる他のフィールドとは対照的で
す。
ENUM
型
ENUM
はストリングオブジェクトで、
その値は、通常、テーブル作成時のフィールド定義で列挙された値の中から選ばれます。
値はある状況下では 空文字 (""
) か NULL
を取ることがあります:
ENUM
に無効な値 (列挙されている値の中に含まれない文字) を
代入した場合、 そのエラーになる文字の代わりに空文字が挿入されます。
ENUM
が NULL
と定義された場合, NULL
はそのフィールドで
許可される値となり、デフォルト値が NULL
になります。
もし ENUM
が NOT NULL
と定義されたならば、 デフォルト値は、
列挙リストの最初の値になります。
列挙されたそれぞれの値はインデックスを持ちます:
ENUM
値が与えられているレコードを見つけるために
以下のような SELECT
構文が使用できることを意味します:
mysql> SELECT * FROM tbl_name WHERE enum_col=0;
NULL
のインデックス値は 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
値の前にソートされます。
通常、LIKE
か FIND_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 ) |
VARCHAR
、BLOB
、及びTEXT
型は可変長型であり、所要容量は、フィ
ールドのとり得る最大サイズというよりはむしろフィールド値の実際の長さに依存します
(前の表でL
と表しました)。
例えば、VARCHAR(10)
フィールドは、最大10文字分の長さの文字列を保持すること
が出来ます。実際の所要容量は、文字列の長さ(L
)と、その長さを記録するための
1バイトを加えます。文字列'abcd'
においては、L
は4で、所要容量は5
バイトです。
BLOB
とTEXT
型は、フィールド値の長さを記録するのに、1、2、3、又は
4バイト必要とし、型のとり得る最大の長さに依存します。See section BLOB
と TEXT
型.
テーブルが可変長フィールド型を含む場合、そのレコードフォーマットもまた可変長とな るでしょう。 テーブルが作成された時、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
型.
SELECT
と WHERE
節で使用する関数
SQL ステートメント中の select_expression
または
where_definition
は後述の関数を使用した任意の式からなります。
演算と関数を式の中で呼ぶ時、本ドキュメントに示しているもの以外の、
NULL
を含む式は常に NULL
値を生成します
注意: 関数名とそれに続く語句の間には、空白はありません。 これは関数の呼び出しと、関数と同名のテーブル(かフィールド)の参照を、 MySQL パーサが区別するのを助けます。
mysqld
に --ansi
をつけて起動するか、
CLIENT_IGNORE_SPACE
を mysql_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
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.
( ... )
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 は以下の規則で比較を行います:
NULL
の場合は、比較結果は NULL
です。<=>
演算子を除きます。
TIMESTAMP
または DATETIME
フィールドで、他の引数が
定数の場合は、定数は比較前に timestamp に変換されます。これはより ODBC
フレンドリにするためです。
文字列の比較は、ケースに依存せず、標準のキャラクターセットに従って 行われます。(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
<=>
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 0To be able to work good with other programs, MySQL supports the following extra features when using
IS NULL
:
SELECT * FROM tbl_name WHERE auto_col IS NULLThis can be disabled by setting
SQL_AUTO_IS_NULL=0
. See section SET
構文.
NOT NULL
DATE
and DATETIME
columns you can find
the special date 0000-00-00
by using:
SELECT * FROM tbl_name WHERE date_column IS NULLThis is needed to get some ODBC applications to work (as ODBC doesn't support a
0000-00-00
date)
expr BETWEEN min AND max
expr
が min
以上、 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
NOT (expr BETWEEN min AND max)
.
expr IN (value,...)
expr
が IN
リストにある値のどれかならば、1
を返します
。
そうでなければ 0
を返します。
もし全ての値が定数なら、すべての値が expr
の型に従って評価され、
ソートされます。この検索にはバイナリサーチが使用されます。
これは IN
リストに定数を与えた場合、IN
が速くなることを意味します。
もし expr
がケース依存の文字式なら、ケース依存のやり方で比較されます。
mysql> SELECT 2 IN (0,3,5,'wefwf'); -> 0 mysql> SELECT 'wefwf' IN (0,3,5,'wefwf'); -> 1From 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)
expr
が NULL
なら 1
を、そうでなければ 0
を返します
mysql> SELECT ISNULL(1+1); -> 0 mysql> SELECT ISNULL(1/0); -> 1
NULL
の値を =
を使用して比較した場合は常に偽(false) となることに
注意してください!
COALESCE(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 NULL
は NULL
を返します:
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; -> 0Please 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 0
s. 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
||
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
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)
expr1
が NULL
でない場合は 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).
expr1
は INTEGER
として評価されます。これは浮動小数点を使用する
場合、比較演算も使用すべきであることを意味します:
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 が整数を返す | 整数 |
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
を返します。
str
が NULL
の場合は NULL
を返します:
mysql> SELECT ASCII('2'); -> 50 mysql> SELECT ASCII(2); -> 50 mysql> SELECT ASCII('dx'); -> 100See also the
ORD()
function.
ORD(str)
((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)
N
を from_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)
と同じです。
N
が NULL
なら NULL
を返します:
mysql> SELECT BIN(12); -> '1100'
OCT(N)
N
の8進数値を表す文字列を返します。N
は longlong 数値です。
これは CONV(N,10,8)
と同じです。N
が NULL
の場合は
NULL
を返します:
mysql> SELECT OCT(12); -> '14'
HEX(N_or_S)
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,...)
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)
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
は検索を開始する位置です。
str
に substr
がなければ 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
を埋めます。
str
が len
よりも長い場合は、len
文字に短くされます。
mysql> SELECT LPAD('hi',4,'??'); -> '??hi'
RPAD(str,len,padstr)
str
の長さが len
になるまで文字列 str
の終わりに padstr
を埋めます。
str
が len
よりも長い場合は、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)
str
の pos
位置から 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
から、区切り文字 delim
が count
個現れた位置から前の
文字列を返します。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_str
を to_str
に
置き換えます:
mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww'); -> 'WwWwWw.mysql.com'この関数はマルチバイトでも安全です。
REPEAT(str,count)
str
を count
回繰り返します。count <= 0
の場合は
空の文字列を返します。str
または count
が NULL
または、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
を
返します。
N
が 1
より小さい場合、または引数の数より大きい場合は 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)
str
が strlist
中にあれば、値 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]])
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)
NULL
, the return value is the word ``NULL'' without surrounding
single quotes.
mysql> SELECT QUOTE("Don't"); -> 'Don\'t!' mysql> SELECT QUOTE(NULL); -> NULL
MySQL は必要とあらば数値を文字列に変換します。 逆も同様に行います:
mysql> SELECT 1+"1"; -> 2 mysql> SELECT CONCAT(2,' test'); -> '2 test'
明示的に数値を文字列に変換したければ、CONCAT()
に引数として渡して下
さい。
文字列関数は引数としてバイナリ文字列が与えられると、結果の文字列もバイナリ 文字列になります。文字列に変換された数値はバイナリ文字列とみなされます。こ れは比較にだけ影響します。
通常、比較される表現がケース依存でない場合、比較はケース非依存で行われます。
expr LIKE pat [ESCAPE 'escape-char']
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
SOUNDEX(expr)=SOUNDEX(expr)
(available only in version 4.1 or later).
expr REGEXP pat
expr RLIKE pat
pat
に対し、文字式 expr
のパターンマッチを行います。
パターン pat
は正規表現の拡張が使用できます。See section MySQL の正規表現.
もし expr
が pat
にマッチするなら 1
を返し、
でなければ 0
を返します。
RLIKE
は REGEXP
と同義で、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.
BINARY
BINARY
演算子は、これ以降に続く文字をバイナリにキャストします。
これはたとえフィールドが BINARY
や BLOB
定義でなくても、
ケース依存でフィールドを比較することが出来る簡単な方法です:
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;
より柔軟に文字列を比較するために、我々は間もなく異なる文字セット間のキャス トを導入する予定です。
普通の算術演算が有効です。
-
, +
, *
は、二つの引数が正数ならば
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.600 で割った場合、
NULL
になります。
mysql> SELECT 102/(1-1); -> NULL演算結果が整数になる場合にだけ、
BIGINT
を用いて割り算は計算されます。
すべての数学関数はエラーの場合 NULL
を返します。
-
mysql> SELECT - 2; -> -2このオペレーターが
BIGINT
とともに使用された場合、
返り値は BIGINT
であることに注意してください! これは -2^63
の値を
持つかもしれない整数を、 -
で使用してはならないことを意味します!
ABS(X)
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)
%
%
演算子のような ).
N
を M
で割ったときの余りが返ります:
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)
X
を D
で指定した少数桁に丸めた値(四捨五入)を返します。
もし D
が 0
なら, 結果は小数点無しになるか
少数部分になるでしょう:
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)
X
:
mysql> SELECT LN(2); -> 0.693147 mysql> SELECT LN(-2); -> NULLThis 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); -> NULLThe arbitrary base option was added in MySQL version 4.0.3.
LOG(B,X)
is equivalent to LOG(X)/LOG(B)
.
LOG2(X)
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)
X
:
mysql> SELECT LOG10(2); -> 0.301030 mysql> SELECT LOG10(100); -> 2.000000 mysql> SELECT LOG10(-100); -> NULL
POW(X,Y)
POWER(X,Y)
X
の Y
乗:
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()
mysql> SELECT PI(); -> 3.141593 mysql> SELECT PI()+0.000000000000000000; -> 3.141592653589793116
COS(X)
X
。X
はラジアン:
mysql> SELECT COS(PI()); -> -1.000000
SIN(X)
X
。X
はラジアン:
mysql> SELECT SIN(PI()); -> 0.000000
TAN(X)
X
。X
はラジアン:
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)
X
と Y
のアークタンジェントを返します。両方の引数
の符号が結果の象限を決定するために使用されることを除いて、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,...)
INTEGER
を使用しているなら、あるいは、全ての引数が
整数値ならば、整数として比較します。
REAL
として使用されているか、全ての引数が実数ならば、
実数として比較します。
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
を切り捨てた値を返します。
D
が 0
の場合、結果は小数部や微小部を持ちません:
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.9Starting 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)
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-53
か 1-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); -> 53Note: 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); -> 52One 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)
WEEK()
の第2引数とまったく同じ
ように働きます。注意: 年の最初と最後の週では、年が date 引数内の年とは異な
ることがあります!
mysql> SELECT YEARWEEK('1987-01-01'); -> 198653Note 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)
P1
と P2
の差の月を返します。P1
と P2
は形
式 YYMM
または YYYYMM
です。
注意: 期間引数 P1
と P2
は日付値では ありません。
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)
ADDDATE()
と SUBDATE()
は
DATE_ADD()
, DATE_SUB()
と同義です。
MySQL バージョン 3.23 では, +
と -
を
DATE_ADD()
, DATE_SUB()
の代わりに使用できます. (See example below.)
date
には、DATETIME
か DATE
型の値を指定します。
この値から演算が開始されます。
expr
には、date から増減させる値を指定します。
expr
が `-' から始まっていれば、負数を示します。
type
はどれぐらいの期間かを示すキーワードです。
EXTRACT(type FROM date)
関数は、date から 'type' の部分を返します。
以下の表に、type
と expr
の関連を示します:
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"
|
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 値の一番
左の部分を指定し忘れたものだと仮定します。
例えば、もし type
を DAY_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
です.
もし MONTH
や YEAR_MONTH
や YEAR
を足し算して、
結果となる日付が新しい月の最大日よりも大きい日になるようなら、
その日は、新しい月の最大日に修正されます。
mysql> SELECT DATE_ADD('1998-01-30', Interval 1 month); -> 1998-02-28例のように、
INTERVAL
と type
キーワードは
ケース依存ではありません.
EXTRACT(type FROM date)
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; -> 19971215235026Note 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)
'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_TIMESTAMP
が TIMESTAMP
フィールドに使用された場合、
この関数は、暗黙の ``文字から 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 文字列を返します。
format
は DATE_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
The syntax of the CAST
function is:
CAST(expression AS type) or CONVERT(expression,type)
Where type is one of:
BINARY
CHAR
(New in 4.0.6)
DATE
DATETIME
SIGNED {INTEGER}
TIME
UNSIGNED {INTEGER}
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)
演算を使用するためです。
|
mysql> SELECT 29 | 15; -> 31The result is an unsigned 64-bit integer.
&
mysql> SELECT 29 & 15; -> 13The result is an unsigned 64-bit integer.
^
mysql> SELECT 1 ^ 1; -> 0 mysql> SELECT 1 ^ 0; -> 1 mysql> SELECT 11 ^ 3; -> 8The result is an unsigned 64-bit integer.
XOR
was added in version 4.0.2.
<<
BIGINT
) number 分、ビットをシフトします:
mysql> SELECT 1 << 2; -> 4The result is an unsigned 64-bit integer.
>>
BIGINT
) number 分、ビットをシフトします:
mysql> SELECT 4 >> 2; -> 1The result is an unsigned 64-bit integer.
~
mysql> SELECT 5 & ~1; -> 4The 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()
mysql> SELECT USER(); -> 'davida@localhost'MySQL バージョン 3.22.11 以降では、この関数はユーザー名とクライアントの ホスト名を含みます。 ユーザー名の部分だけ取り出すには次のようにします。 (これはホスト名が含まれていなくとも動くでしょう):
mysql> SELECT substring_index(USER(),"@",1); -> 'davida'
CURRENT_USER()
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])
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_str
は ENCODE()
から返された文字列
であるべきです。
MD5(string)
mysql> SELECT MD5("testing"); -> 'ae2b1fca515949e5d54fb22b8ed95575'これは "RSA Data Security, Inc. MD5 Message-Digest Algorithm".
SHA1(string)
SHA(string)
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)
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) ] )
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 .
|
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_stringEach
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])
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
を整形
します。 もし D
が 0
なら, 結果にはいかなる
小数点も小数部も含まれません。
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> SELECT VERSION(); -> '3.23.13-log'注意: バージョンが
-log
で終わる場合はロギングが有効であることを意
味します。
CONNECTION_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"); -> NULL2つ目の
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)
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)
mysql> SELECT INET_NTOA(3520061480); -> "209.207.224.40"
INET_ATON(expr)
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()
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.
GROUP BY
Clauses
GROUP BY
節を含まない文でグループ関数を使用すると
全てのレコードについてグループされたものとみなされます。
COUNT(expr)
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)
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.name
をGROUP 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 BY
とORDER 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();
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
節の前でなければなりません。
SELECT
の表現では、AS
による別名の指定が可能です。別名は、
フィールド名の表現として使われ、ORDER BY
及びHAVING
節とともに使用することができます。
例:
mysql> SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable ORDER BY full_name;
WHERE
clause,
because the column value may not yet be determined when the
WHERE
clause is executed.
See section alias
の問題.
FROM table_references
節は、(例えば、選択するレコードにより、1つ又はそれ以上の)
結合するテーブルのリストを示します。
このリストはまた、LEFT OUTER JOIN
参照を含むことがあります。
section JOIN
構文. を参照してください。
For each table specified, you may optionally specify an alias.
table_name [[AS] alias] [[USE INDEX (key_list)] | [IGNORE INDEX (key_list)] | FORCE INDEX (key_list)]]As of MySQL Version 3.23.12, you can give hints about which index MySQL should use when retrieving information from a table. This is useful if
EXPLAIN
shows that MySQL is
using the wrong index from the list of possible indexes. By specifying
USE INDEX (key_list)
, you can tell MySQL to use only one of the
possible indexes to find rows in the table. The alternative syntax
IGNORE INDEX (key_list)
can be used to tell MySQL to not use some
particular index.
In MySQL 4.0.9 you can also use FORCE INDEX
. This acts likes
USE INDEX (key_list)
but with the addition that a table scan
is assumed to be VERY expensive. In other words a table scan will
only be used if there is no way to use one of the given index to
find rows in the table.
USE/IGNORE/FORCE KEY
are synonyms for USE/IGNORE/FORCE INDEX
.
tbl_name
(within the current database),
or as dbname.tbl_name
to explicitly specify a database.
col_name
、tbl_name.col_name
、db_name.tbl_name.col_name
の
ようにしてフィールドを表すことができます。
SELECT
ステートメント内での列の参照が曖昧でなければ、tbl_name
や
db_name.tbl_name
のようなプリフィックスを詳細に記述する必要はありません。
より明示的なフィールドの指定形式をを必要とする曖昧な参照の例は、section データベース名、テーブル名、インデックス名、フィールド名、エイリアス名を参照のこと。
tbl_name AS alias_name
又はtbl_name alias_name
を
使って別名を使用することが可能です:
mysql> SELECT t1.name, t2.salary FROM employee AS t1, info AS t2 -> WHERE t1.name = t2.name; mysql> SELECT t1.name, t2.salary FROM employee t1, info t2 -> WHERE t1.name = t2.name;
ORDER BY
節やGROUP BY
節において、
フィールド名、フィールドのエイリアス名、又はフィールド番号にて指し示すことが
できます。フィールド番号は1から始まります。
mysql> SELECT college, region, seed FROM tournament -> ORDER BY region, seed; mysql> SELECT college, region AS r, seed AS s FROM tournament -> ORDER BY r, s; mysql> SELECT college, region, seed FROM tournament -> ORDER BY 2, 3;逆順で並べたい場合には、
ORDER BY
節の中で、あなたが並べたいと思っている
フィールドの名前の後ろに、 DESC
(descending) キーワードを
追加します。
デフォルトは昇順です; これは ASC
キーワードを指定したことになります。
WHERE
節で MySQL がサポートする任意の関数を使用することが
できます。See section SELECT
と WHERE
節で使用する関数.
HAVING
節は、select_expression
においてどのフィールドの名前や
エイリアス名でも指し示すことができます。
これは最後に適用され、クライアントにアイテムが送られる直前に実行されるので、
最適化されません。
WHERE
節で書くべきものにHAVING
を用いてはいけません。
例えば、次のように書いてはいけません:
mysql> SELECT col_name FROM tbl_name HAVING col_name > 0;その代わりに、次のように書いてください:
mysql> SELECT col_name FROM tbl_name WHERE col_name > 0;MySQL バージョン 3.22.5以降では、次のようにクエリを記述することができます:
mysql> SELECT user,MAX(salary) FROM users GROUP BY user HAVING MAX(salary)>10;MySQLの古いバージョンでは、この代わりに次のように記述できます:
mysql> SELECT user,MAX(salary) AS sum FROM users GROUP BY user HAVING sum>10;
DISTINCT
, DISTINCTROW
and ALL
specify
whether duplicate rows should be returned. The default is (ALL
),
all matching rows are returned. DISTINCT
and DISTINCTROW
are synonyms and specify that duplicate rows in the result set should
be removed.
SQL_SMALL_RESULT
, SQL_BIG_RESULT
, SQL_BUFFER_RESULT
,
STRAIGHT_JOIN
, HIGH_PRIORITY
は ANSI SQL に対する MySQL 拡張です。
HIGH_PRIORITY
は、テーブルの更新よりも SELECT
を優先させます。
これは一度で完了する、とても速いクエリにのみ適用すべきです。
もしリードロックされているテーブルがあったとし、
たとえ update 文がこのテーブルの解除を待っていたとしても、
SELECT HIGH_PRIORITY
クエリは実行されます。
SQL_BIG_RESULT
は GROUP BY
や DISTINCT
と共に使用する
事ができ、結果セットが多くのレコードを持つことをオプティマイザに知らせます。
この場合、必要なら MySQL はディスクベースの一時テーブルを直接使用
します。MySQL
はこの場合、GROUP BY
要素上のキーで一時テーブ
ルを行なう代わりにソートを行なうことを選択します。
SQL_BUFFER_RESULT
は結果を一時テーブルへ強制的に置きます。これは
MySQL がテーブルロックを速く解放して、クライアントに結果セットを
送るために長い時間が掛かる場合の助けになります。
SQL_CALC_FOUND_ROWS
(version 4.0.0 and up) tells MySQL to calculate
how many rows there would be in the result set, disregarding any
LIMIT
clause.
The number of rows can then be retrieved with SELECT FOUND_ROWS()
.
See section その他の関数.
Please note that in versions prior to 4.1.0 this does not work with
LIMIT 0
, which is optimised to return instantly (resulting in a
row count of 0). See section MySQL はどのように LIMIT
を最適化するか?.
SQL_CACHE
tells MySQL to store the query result in the query cache
if you are using QUERY_CACHE_TYPE=2
(DEMAND
).
See section MySQL Query Cache (4.0.1以上).
SQL_NO_CACHE
tells MySQL to not allow the query result to be stored
in the query cache. See section MySQL Query Cache (4.0.1以上).
SQL_SMALL_RESULT
(MySQL 固有のオプション) は GROUP BY
か DISTINCT
と共に使用する事ができ、
結果セットが小さくなることをオプティマイザに知らせます。この場合、
MySQL はソートする代わりに、速い一時テーブルを結果の保存のた
めに使用します。 MySQL バージョン 3.23 では、これは通常必要ではありません。
GROUP BY
を使用する場合、GROUP BY
内のすべてのフィールドを
ORDER BY
に記述したかのように、出力レコードは GROUP BY
に従っ
てソートされます。MySQL は、ASC
と DESC
を
GROUP BY
に記述できるように、GROUP BY
を拡張しています:
SELECT a,COUNT(b) FROM test_table GROUP BY a DESC
GROUP BY
節に記述されていないフィールドを
select できるように GROUP BY
の使用を拡張しています。あなたのクエリ
から期待した結果を得ない場合、GROUP BY
の説明を読んでください。
See section Functions for Use with GROUP BY
Clauses.
STRAIGHT_JOIN
は、FROM
節にて記述されたテーブルの順序に従って結合するよう、
オプティマイザに強制します。オプティマイザが、テーブルを最適な順序で結合しない
場合に、クエリのスピードアップのためにこれを使用することが可能です。
See section EXPLAIN
構文 (SELECT
についての情報を得る).
LIMIT
節は、 SELECT
構文で返されるレコード数を指定するのに
使用されます。 LIMIT
は一つか二つの数字の引数を取ります。
引数が2つ与えられたならば、最初の引数は最初のレコードからのオフセットを示し、
2つめの引数は返すレコードの最大数を示します。
初めのレコードのオフセットは0です(1ではありません)。
To be compatible with PostgreSQL MySQL also supports the syntax:
LIMIT # OFFSET #
.
mysql> SELECT * FROM table LIMIT 5,10; # 6〜15行目を返すTo retrieve all rows from a certain offset upto the end of the result set, you can use -1 for the second parameter:
mysql> SELECT * FROM table LIMIT 95,-1; # Retrieve rows 96-last.もし引数が一つなら、返すべきレコードの最大行数を指定したことになります。
mysql> SELECT * FROM table LIMIT 5; # 最初の5行を取り出すいいかえれば、
LIMIT n
は LIMIT 0,n
と同じです。
SELECT
の書式、SELECT ... INTO OUTFILE 'file_name'
は、
選択されたレコードをファイルに書き込みます。
ファイルはサーバ機に作成され、既に存在するファイルであってはなりません
(`/etc/passwd'のようなファイルの破壊を防止します)。
SELECT ... INTO OUTFILE
は主に、サーバマシン上でとても速くテーブル
をダンプすることを意図されています。サーバホストでない別のホスト上で結果ファ
イルを生成したい場合は、SELECT ... INTO OUTFILE
を使用できません。
この場合は代わりに、mysqldump --tab
や mysql -e "SELECT
..." > outfile
のようなクライアントプログラムを使用して、ファイルを生成す
べきです。
SELECT ... INTO OUTFILE
は、LOAD DATA INFILE
の逆です。
export_options
の構文は、LOAD DATA INFILE
ステートメントの一部で
使われるFIELDS
節やLINES
節と同じような構成です。
See section LOAD DATA INFILE
構文.
結果として取り出されるテキストファイルでは、
以下に示す文字が ESCAPED BY
指定の文字によってエスケープされます:
ESCAPED BY
文字自身
FIELDS TERMINATED BY
の最初の文字
LINES TERMINATED BY
の最初の文字
ASCII 0
は、ESCAPED BY
0 (ASCII 48
) にコンバートされます。
いかなる FIELDS TERMINATED BY
, ESCAPED BY
, LINES TERMINATED BY
指定されている文字も、エスケープしなければならない理由は、
テキストファイルを読み返せれるようにするためなのです。
ASCII 0
はいくつかのページャーでも見れるようにするために
エスケープされるのです。
結果のファイルは SQL の文を含んでいないので、何もエスケープする必要はありません。
次は、多くの古いプログラムによって使用されるフォーマットでファイルを得る例
です。
SELECT a,b,a+b INTO OUTFILE "/tmp/result.text" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY "\n" FROM test_table;
INTO OUTFILE
の代わりに INTO DUMPFILE
を使用すると、
MySQL はファイルに1レコードだけを書きます。フィールドや行の終端
とすべてのエスケープを含みません。これはファイル内に BLOB を格納したい場合
に便利です。
INTO OUTFILE
and INTO
DUMPFILE
is going to be writeable for all users! The reason is that the
MySQL server can't create a file that is owned by anyone else
than the user it's running as (you should never run mysqld
as root),
the file has to be world-writeable so that you can manipulate it.
FOR UPDATE
を使
用すると、検査されるレコードは書き込みロックされます。
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 JOIN
は join_condition
を取りません!
上に示す最後のLEFT OUTER JOIN
構文は、ODBCとの互換性のためだけに存在します:
tbl_name AS alias_name
やtblname alias_name
に
よる別名を指定することができます:
mysql> SELECT t1.name, t2.salary FROM employee AS t1, info AS t2 -> WHERE t1.name = t2.name;
INNER JOIN
と,
(コンマ)は、同義語です。どちらも使用される
テーブル間の直積をとります。通常はWHERE
条件にて、テーブルがどのように
リンクされるべきかを定義します。
ON
条件節は、WHERE
節で使用されるような条件文の書式です。
LEFT JOIN
の ON
や USING
において
右側のテーブルにマッチするレコードが無かった場合、
全てのフィールドがNULL
である1つのレコードが、右側のテーブルとして使用されます。
この事実は、あるテーブルについて、他のテーブルに対応するレコードが存在しない
レコードを探すということに利用できます:
mysql> SELECT table1.* FROM table1 -> LEFT JOIN table2 ON table1.id=table2.id -> WHERE table2.id IS NULL;この例は、
table1
の内、id
の値がtable2
に存在しない全ての
レコードを検索します。
(即ち、table2
内のレコードと一致しないtable1
の全てのレコード。)
もちろん、この場合のtable2.id
は、NOT NULL
と定義されているもの
と仮定します。
See section MySQL はどのように LEFT JOIN
と RIGHT JOIN
を最適化するか?.
USING
(column_list)
節のフィールド名リストは、両方のテーブルに
存在しなければなりません。USING
節が次のように:
A LEFT JOIN B USING (C1,C2,C3,...)定義されることは、
ON
式がこのように定義されるのと同義です:
A.C1=B.C1 AND A.C2=B.C2 AND A.C3=B.C3,...
NATURAL [LEFT] JOIN
は、
USING
節を伴った INNER JOIN
や LEFT JOIN
と
同じとして定義されます。
INNER JOIN
and ,
(comma) are semantically equivalent.
Both do a full join between the tables used. Normally, you specify
how the tables should be linked in the WHERE condition.
RIGHT JOIN
works analogously as LEFT JOIN
. To keep code
portable across databases, it's recommended to use LEFT JOIN
instead of RIGHT JOIN
.
STRAIGHT_JOIN
は、右側のテーブルの前に、常に左側のテーブルを読むことを
除けば、JOIN
と全く同じことです。これは、結合オプティマイザが、不当な
順序でテーブルを出力するようなまれな事態に使用できます。
EXPLAIN
が示す場合に有用です。USE INDEX
(key_list)
を指定することによって、テーブルからレコードを見つけるために、
指定されたインデックスの一つだけを使用するように MySQL に伝えるこ
とができます。別の構文 IGNORE INDEX (key_list)
は、MySQL
に特定のインデックスを使用しないように伝えるために使用できます。
In MySQL 4.0.9 you can also use FORCE INDEX
. This acts likes
USE INDEX (key_list)
but with the addition that a table scan
is assumed to be VERY expensive. In other words a table scan will
only be used if there is no way to use one of the given index to
find rows in the table.
USE/IGNORE KEY
are synonyms for USE/IGNORE INDEX
.
例:
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 JOIN
と RIGHT JOIN
を最適化するか?.
UNION
SyntaxSELECT ... 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:
SELECT
command can have INTO OUTFILE
.
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
SyntaxHANDLER 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:
SELECT
because:
HANDLER OPEN
.
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 ... VALUES
や INSERT ... SELECT
などで明示しなければ、全てのフィールドの値が VALUES()
の中に与えられ
なくてはなりません。テーブル内のフィールド順が不明な場合、
これを調べるためにDESCRIBE tbl_name
を使用して下さい。
CREATE TABLE
構文. で述べられています。
You can also use the keyword DEFAULT
to set a column to its
default value. (New in MySQL 4.0.3.) This makes it easier to write
INSERT
statements that assign values to all but a few columns,
because it allows you to avoid writing an incomplete VALUES()
list
(a list that does not include a value for each column in the table).
Otherwise, you would have to write out the list of column names
corresponding to each value in the VALUES()
list.
MySQL always has a default value for all fields. This is something
that is imposed on MySQL to be able to work with both transactional
and not transactional tables.
Our view is that checking of fields content should be done in the
application and not in the database server.
expression
は、値リスト内で先頭に近い方のフィールドを参照しなければなりません。
例えば、次のように記述できます:
mysql> INSERT INTO tbl_name (col1,col2) VALUES(15,col1*2);しかし、次のようには記述できません:
mysql> INSERT INTO tbl_name (col1,col2) VALUES(col2*2,15);
LOW_PRIORITY
を指定した場合、INSERT
の実行はそのテー
ブルから値を読み込むクライアントがいなくなるまで遅らされます。この場合、ク
ライアントは insert 文が完了するまで待たされます。テーブルが頻繁に使用され
る場合、長い時間かかります。これはクライアントを一度に継続させる
INSERT DELAYED
と対称的です。
See section INSERT DELAYED
構文. Note that LOW_PRIORITY
should normally not be used with MyISAM
tables as this disables
concurrent inserts. See section MyISAM
テーブル (3.23.0以上).
IGNORE
キーワードを INSERT
に 値とともに 与えるなら、
テーブル内の PRIMARY
や UNIQUE
キーにすでに存在する重複した
ものは無視され、挿入されません。
多重行の値を含むレコードの INSERT
にキーワード IGNORE
を
指定しない場合、テーブルの PRIMARY
キーや UNIQUE
キーに
重複が起こる際に、挿入処理が異常終了します。
IGNORE
を指定した場合、重複するキー値を持つレコードは挿入されません。
C API 関数 mysql_info()
により、テーブルにいくつのレコードが挿入
されたかチェックすることができます。
ON DUPLICATE KEY UPDATE
clause (new in MySQL 4.1.0), and
a row is inserted that would cause a duplicate value in PRIMARY
or
UNIQUE
key, an UPDATE
of the old row is performed. For
example, the command:
mysql> INSERT INTO table (a,b,c) VALUES (1,2,3) --> ON DUPLICATE KEY UPDATE c=c+1;in case of column
a
is declared as UNIQUE
and already
holds 1
once, would be identical to the
mysql> UPDATE table SET c=c+1 WHERE a=1;Note: that if column
b
is unique too, the
UPDATE
command would be written as
mysql> UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;and if
a=1 OR b=2
matches several rows, only one row
will be updated! In general, one should try to avoid using
ON DUPLICATE KEY
clause on tables with multiple UNIQUE
keys.
When one uses ON DUPLICATE KEY UPDATE
,
the DELAYED
option is ignored.
DONT_USE_DEFAULT_FIELDS
オプションにより制限されていた
場合、NULL
値を許さない全てのフィールドに明示的に値をしないと
INSERT
ステートメントは、エラーを生成します。
See section 典型的な configure
オプション.
mysql_insert_id
関数で AUTO_INCREMENT
フィールドに使用された
値を見つけることができます。
See section mysql_insert_id()
.
多重の値リストを持つ INSERT ... SELECT ...
又は INSERT ... VALUES()
ステートメントを使用する場合、クエリーに関する情報を得るために
C API関数 mysql_info()
を使用することができます。
その情報の書式は以下に示す文字列のようになります:
Records: 100 Duplicates: 0 Warnings: 0
Duplicates
は、既に存在するユニークインデックスの値と重複することにより、
挿入できなかったレコード数を表します。
Warnings
は、挿入されたフィールドが何らかの疑わしい値であったという
数を表します。警告は、次のような条件の下で発生します:
NOT NULL
定義されたフィールドへのNULL
の挿入。フィールドには
初期値が設定されます。
`10.34 a'
のような値のセット。引きずっている
ゴミは取り除かれ、残りの数値部分が挿入されます。
値が数値として判断できなかった場合、フィールドには 0
がセットされます。
CHAR
、VARCHAR
、VARCHAR
、TEXT
又はBLOB
フィールドへの最大長を超える文字列の挿入。値はフィールドの最大長に切り捨てられます。
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:
INSERT
statement cannot appear in the
FROM
clause of the SELECT
part of the query because it's
forbidden in ANSI SQL to SELECT
from the same table into which you are
inserting. (The problem is that the SELECT
possibly would
find records that were inserted earlier during the same run. When using
subquery clauses, the situation could easily be very confusing!)
AUTO_INCREMENT
columns work as usual.
mysql_info()
to get information about
the query. See section INSERT
構文.
INSERT ... SELECT
.
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
オプションを INSERT
や REPLACE
で使用する場合、
以下のことがおきます。
ここで ``スレッド'' とは INSERT DELAYED
コマンドを受けたスレッドをさし、
``ハンドラー'' とは特定のテーブルのための全ての
INSERT DELAYED
構文を操作するスレッドを指します。
DELAYED
構文を実行するとき、
そのテーブルに対する全ての DELAYED
構文
を処理するためにハンドラースレッドが作成されます。
もしそのようなハンドラーが存在していない場合には。
DELAYED
ロックを既に持っているか
どうかをチェックします; もし持っていないなら、そうするように
ハンドラーに告げます。
たとえ他のスレッドが READ
か WRITE
ロックをそのテーブルに
持っていたとしても、 DELAYED
ロックを得ることができます。
しかし、そのハンドラーは全ての ALTER TABLE
ロックか
FLUSH TABLES
を待ちます。 そのテーブル構造が最新であるのを
確実にするために。
INSERT
ステートメントを実行しますが、レコードをテーブル
に書く代わりに、ハンドラスレッドによって管理されるキューに最後のレコードの
コピーを置きます。文法エラーはスレッドによって通知され、クライアントプログ
ラムに報告されます。
AUTO_INCREMENT
の値を
報告できません; それはサーバーから得ることができません。 なぜなら、
INSERT
はインサートオペレーションが完全に終了する前に
返るからです。 もし C API を使用しているなら、 mysql_info()
関数は
同様の理由によりなにも返しません。
delayed_insert_limit
レコードが書かれた後、そのハンドラーは
いかなる SELECT
文もまだ延期されていないかを確認します。
もしそうなら、続ける前にこれらに対して実行を可能にします。
INSERT DELAYED
コマンドが delayed_insert_timeout
秒以内に
受け付けられなければ、ハンドラーは終了します。
delayed_queue_size
以上のレコードが
既に延期されているならば、そのスレッドは、キューに余裕がある間待ちます。
これは mysqld
サーバーが delayed されたキューに全ての
メモリーを確実に使用しないようにするのに役立ちます。
Command
項
内に、 delayed_insert
と共に表示されます。
これは FLUSH TABLES
コマンドか KILL thread_id
を実行することで、
kill できるでしょう。
しかし、これらは、終了する前に、キュー内の全てのレコードをテーブルに
保存しようとします。
この間、このスレッドは、他のスレッドから来たいかなる
新しい INSERT
コマンドも受け付けません。
もし、この後に INSERT DELAYED
コマンドを実行するなら、
新しいハンドラースレッドが作成されます。
上記のことは、もし INSERT DELAYED
コマンドが既に走っているなら、
INSERT DELAYED
コマンドは、普通の INSERT
コマンドよりも高い
優先度を持つということです!
他の update コマンドは INSERT DELAY
キューが空になるまで、
あるいは誰かが KILL thread_id
や FLUSH TABLES
を実行して
ハンドラーをキルするまで、
待たされます。
INSERT DELAYED
コマンドについての情報を
与えます:
Variable | Meaning |
Delayed_insert_threads | ハンドラースレッドの数 |
Delayed_writes | INSERT DELAYED で書かれるレコード数
|
Not_flushed_delayed_rows | 書き込みを待つレコード数 |
SHOW STATUS
構文を発行したり
mysqladmin extended-status
コマンドを実行することで見れます.
注意: 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_name
を WHERE
節なしで行うよりも、
とても遅いです。なぜなら一度で消そうとするからです。
キーワード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-特化 DELETE
の LIMIT 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:
COMMIT
が呼ばれたかのように
TRUNCATE TABLE
は自動的に現在のトランザクションを終了します。
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;
REPLACE
と IGNORE
キーワードは、すでに存在するユニークキーに
重複しているレコードの入力に対する制御です。
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
を使用します。
FIELDS
とLINES
節の構文は両方のコマンドとも同じです。
どちらの節もオプションですが、両方を指定する場合は、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 BY
とFIELDS ESCAPED BY
の値は
単一の文字でなければなりません。
FIELDS TERMINATED BY
とLINES 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 [OPTIONALLY] ENCLOSED BY
文字
FIELDS TERMINATED BY
値とLINES TERMINATED BY
値の最初の文字
'0'
で、'ゼロ
値'バイトではありません)
FIELDS ESCAPED BY
文字が空であれば、どの文字もエスケープされません。
特に、フィールド値が上に示した文字を含んでいるならば、エスケープ文字に空を指定す
るのはあまり良い考えとは言えないでしょう。
入力において、FIELDS ESCAPED BY
文字が空でない場合、この文字の出現は取り去
られ、後続の文字はフィールド値の一部としてそのまま受け取られます。
例外は、エスケープされた`0'や`N'です
(例えば、エスケープ文字が`\'である時の\0
や\N
)。
これらのシーケンスは、ASCII 0('ゼロ値'バイト) 、NULL
として処理されます。
code{NULL}操作の規則は下を参照して下さい。
`\'-escape syntaxに関するこれ以外の情報は、section 文字列と数値をどのように書くか?参照。
フィールドとレコード操作オプションが確実に相互作用する事例:
LINES TERMINATED BY
が空文字列でFIELDS TERMINATED BY
が空でない場合
、各レコードもまたFIELDS TERMINATED BY
で終らせられます。
FIELDS TERMINATED BY
とFIELDS ENCLOSED BY
値が両方とも空(''
)
の時、(区切られない)固定長行フォーマットが使用されます。
固定長行フォーマットでは、フィールド間に区切り文字列が使用されません。
その代わり、フィールド値は、フィールドの``表示''幅を使って書き込まれたり、読み込
まれます。
例えば、あるフィールドがINT(7)
で定義されている場合、フィールドの値は7文字
の桁を使って書き込まれます。
入力においてフィールドは、7文字の読み込みにより得られます。
固定長行フォーマットはまた、NULL
値の操作に好んで用いられます;下を参照のこ
と。
注意: マルチバイト文字セットを使用している場合は固定長フォーマットは働きま
せん。
FIELDS
とLINES
オプションによるNULL
値の多様な取扱い:
FIELDS
とLINES
の初期値のために、出力時にNULL
は\N
とし
て書き込まれ、入力時に\N
はNULL
として読み込まれます(当然のことなが
ら、ESCAPED BY
文字は`\'とします)。
FIELDS ENCLOSED BY
が空で無い時、定数NULL
のフィールド値はNULL
値として読み込まれます(これは、文字列'NULL'
として読み込まれるFIELD
S ENCLOSED BY
文字列で囲まれたNULL
とは異なります)。
FIELDS ESCAPED BY
が空の時、NULL
はNULL
として書き込まれます。
FIELDS TERMINATED BY
とFIELDS ENCLOSED BY
がい
ずれも空の場合に起こります)において、NULL
は、空白文字列として書き込まれま
す。
これは、ファイル内では、NULL
値と空白値の見分けがつかないということを示し
ていることに注意して下さい。ファイルからデータを読み戻す時に両者を区別しなければ
ならない場合、固定長行フォーマットは使用すべきではありません。
LOAD DATA INFILE
でサポートされないケース:
FIELDS TERMINATED BY
とFIELDS ENCLOSED BY
の両方が空)と
BLOB
フィールド。
LOAD DATA
INFILE
は、正しい入力処理ができないでしょう。
例えば、以下のFIELDS
節は問題の原因となります:
FIELDS TERMINATED BY '"' ENCLOSED BY '"'
FIELDS ESCAPED BY
が空で、フィールド値に、FIELDS ENCLOSED BY
値や
LINES TERMINATED BY
値の後にFIELDS TERMINATED BY
値がくるようなものを含
む場合、フィールドや行の読み込みが早めに打ち切られてしまいます。
これは、LOAD DATA INFILE
が、フィールドやレコードの終了位置を正しく決めら
れないことにより発生します。
次の例は、persondata
テーブルの全てのフィールドを読み込みます:
mysql> LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata;
フィールドリストが指定されていませんから、LOAD DATA INFILE
は、入力レコー
ドがテーブルのそれぞれのフィールドを含むものと想定します。
FIELDS
とLINES
の初期値が使用されます。
テーブルの一部のフィールドのみ読み込みたい場合、フィールドリストを指定します:
mysql> LOAD DATA INFILE 'persondata.txt' -> INTO TABLE persondata (col1,col2,...);
テーブル内のフィールド順と入力ファイルのフィールド順が異なる場合にも、My SQLにテーブルのフィールドと入力フィールドの対応を教えるために、フィールドリスト を指定しなければなりません。
入力レコードのフィールド数の方が少ない場合、入力フィールド値が与えられないフィー
ルドは、初期値が設定されます。
初期値の割当てについては、section CREATE TABLE
構文.
で述べられています。
空のフィールド値は変換されます:
0
にセットされます。
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
SyntaxDO 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
.
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 フィールド型を参照のこと。
NULL
もNOT NULL
も指定されなかった場合、フィールドはNULL
が指
定されたものとして扱われます。
AUTO_INCREMENT
も指定することができます。
AUTO_INCREMENT
のフィールドに値NULL
又は0
を挿入した場合、フィ
ールドにはvalue+1
の値がセットされます。value
は、そのテーブル内の当
該フィールドにおける現在の最大値です。
AUTO_INCREMENT
は 1
からはじまります.
See section mysql_insert_id()
.
削除したレコードが、AUTO_INCREMENT
フィールドの最大値を含んでいた場合、
その値は、ISAM
と BDB
テーブルでは、次に再利用されますが、
MyISAM
と InnoDB
テーブルでは再利用されません。
また、テーブル内の全てのレコードを DELETE FROM table_name
(WHERE
節
無しで) を
AUTOCOMMIT
モードで使用して削除した場合は、すべてのテーブル型で始めから採
番し直します。
注意: 1つのテーブルには1つしかAUTO_INCREMENT
フィールドを指定でき
ません。
また、インデックスを指定する必要があります。
MySQL 3.23 は auto_increment フィールドが正の数を持っている場合に
だけ、正しく動作します。負の数の挿入はとても大きな正の数の挿入とみなされま
す。これは、数値が正から負への 'wrap' over する時の精度の問題を回避するた
めと、アクシデント的に 0 を含む auto_increment フィールドを得ることがない
ことを確実にするために、行なわれます。
In MyISAM and BDB tables you can specify AUTO_INCREMENT
secondary
column in a multi-column key. See section Using AUTO_INCREMENT
.
MySQL をいくつかの ODBC アプリケーションと互換にするために、次の
クエリで最後に挿入されたレコードを見つけることができます:
SELECT * FROM tbl_name WHERE auto_col IS NULL
CREATE TABLE
automatically commits the current InnoDB
transaction if MySQL binary logging is used.
TIMESTAMP
フィールドにおけるNULL
値は、他のフィールド属性と違った扱
われ方をします。定数NULL
をTIMESTAMP
フィールドに格納することはでき
ません。NULL
値の指定は現在時刻をセットすることを意味します。
TIMESTAMP
フィールドがこのように振舞うので、通常はNULL
属性や
NOT NULL
属性は適用できません。それらを指定しても無視されます。
一方、MySQLクライアントからは、より安易にTIMESTAMP
フィールドを
利用でき、サーバもTIMESTAMP
フィールドへのNULL
の適用を報告しますが
、TIMESTAMP
フィールドは実際にはNULL
値を保存することはありません。
code{DESCRIBE tbl_name}を使用して、テーブル定義文を取得することにより、この現象
を確認することができます。
TIMESTAMP
フィールドに0
を指定することは、NULL
を指定すること
と等しくないことに注意してください。なぜなら、0
はTIMESTAMP
の値とし
て不正であるからです。
DEFAULT
value has to be a constant, it cannot be a function or
an expression.
フィールドに対して DEFAULT
値が指定されない場合は MySQL が
自動的にそれを割り当てます。
フィールドが NULL
を値として取り得る場合は、デフォルト値は
NULL
です。
フィールドが NOT NULL
として宣言された場合は、デフォルト値はフィー
ルド型に依存します:
AUTO_INCREMENT
定義された以外の数値型のフィールドに対しては、
初期値は0
となります。
AUTO_INCREMENT
フィールドでは、デフォルト値は次のシーケンス番号になります。
TIMESTAMP
型以外の日付型と時刻型のフィールドに対しては、
初期値はその型において適切な``ゼロ''値となります。
例外: フィールドがそのテーブル内で最初のTIMESTAMP
フィールドである場合、初
期値は現在時刻になります。
See section 日付と時間の型.
ENUM
以外の文字列型のフィールドに対しては、初期値は空文字列となります。
ENUM
では、デフォルト値は最初の列挙の値です。
NOW()
or CURRENT_DATE
.
KEY
は、INDEX
の同義語です。
UNIQUE
キーは固有値しか持つことができません。既に存在
するレコードとキーの値が重複するレコードを挿入しようとした場合、エラーが発生しま
す。
PRIMARY KEY
はユニーク KEY
で、すべてのキーフィールドは
NOT NULL
として定義されなければならないという特別な制限を伴います。
MySQL ではキーは PRIMARY
と名付けられます。テーブルは
PRIMARY KEY
を一つだけ持つことができます。PRIMARY KEY
を持た
ない場合に、アプリケーションがテーブル内の PRIMARY KEY
を尋ねると、
MySQL は PRIMARY KEY
として、NULL
フィールドを持た
ない最初の UNIQUE
キーを返します。
PRIMARY KEY
は複数フィールドインデックスとできます。しかしながら、1つのフ
ィールド定義内ではPRIMARY KEY
属性を用いて複合インデックスを定義することが
できませんので、フィールド定義内における指定は、プライマリ・キーが単独フィールド
の場合のみとして下さい。複合フィールドの場合は、
PRIMARY KEY(index_col_name,...)
文を使用しなければなりません。
PRIMARY
や UNIQUE
キーが1つのフィールドだけからなり、その型が整数
の場合、それを _rowid
としても参照することができます
(バージョン 3.23.11 での新機能)。
index_col_name
内の最初のフィールド名に(_2
, _3
, ...)のような
サフィックスを付加したものが割り当てられます。
テーブルが使用しているインデックス名は、
SHOW INDEX FROM tbl_name
により確認することができます。
See section Retrieving information about Database, Tables, Columns, and Indexes.
MyISAM
テーブルのみが、NULL
値をもつフィールドに対して
インデックスを持つことが出来ます。
その他のテーブル型の場合、フィールドを NOT NULL
で定義しなくてはなりませ
ん。
col_name(length)
文を共に指定することで、CHAR
フィールド又は
VARCHAR
フィールドの一部分だけをインデックスとして定義できます。
これによりインデックスファイルを適度に小さくすることができます。
See section Column Indexes.
MyISAM
テーブル型のみが、 BLOB
と TEXT
フィールド上に
インデックスを持つことが出来ます。 BLOB
と TEXT
フィールドに
インデックスを張る場合、常に、インデックスの長さを指定しなくてはなりません:
CREATE TABLE test (blob_col BLOB, INDEX(blob_col(10)));
TEXT
フィールドやBLOB
フィールドで ORDER BY
や
GROUP BY
を使用すると、
最初のmax_sort_length
バイトだけが使用されます。
See section BLOB
と TEXT
型.
FULLTEXT
インデックスも
生成できます。それらは全文検索に使用されます。MyISAM
テーブル型
だけが FULLTEXT
インデックスをサポートします。それらは CHAR
,
VARCHAR
, TEXT
フィールドからだけ生成できます。
インデックスは常にフィールド全体に起こります。部分インデックスは
サポートされません。オペレーションの詳細は section MySQL Full-text Search を見てください。
InnoDB
tables support checking of
foreign key constraints. See section InnoDB
テーブル (3.23.6以上). Note that the
FOREIGN KEY
syntax in InnoDB is more restricted than
the syntax presented above. InnoDB does not allow
index_name
to be specified, and the columns of the referenced
table always have to be explicitly named. Starting from
4.0.8 InnoDB supports both ON DELETE
and ON UPDATE
actions on foreign keys.
See the InnoDB manual section for the precise syntax. See section InnoDB
テーブル (3.23.6以上).
For other table types, MySQL Server does parse the FOREIGN KEY
,
CHECK
, and REFERENCES
syntax in CREATE TABLE
commands,
but without further action being taken. See section 外部キー.
NULL
フィールドは、1ビット余計に消費し、直近のバイトに丸められます。
レコードの長さ = 1 + (フィールドの長さの合計) + (NULLフィールドの数 + 7)/8 + (可変長フィールドの数)
table_options
と SELECT
オプションは、
MySQL 3.23 以上でのみ実装されます。
テーブル型は:
Table type | Description |
BDB または BerkeleyDB | トランザクションセーフなテーブル See section BDB or BerkeleyDB Tables.
|
HEAP | このテーブルのデータは、メモリー内にのみ蓄えられる See section HEAP Tables (3.23.0以上).
|
ISAM | オリジナルのテーブル See section ISAM Tables.
|
InnoDB | レコードロッキングを持ったトランザクション安全テーブル See section InnoDB テーブル (3.23.6以上).
|
MERGE | 一つのテーブルとして使用される MyISAM テーブルの集まり See section MERGE Tables (3.23.25以上).
|
MRG_MyISAM | An alias for MERGE tables |
MyISAM | ISAM にかわる 新しい バイナリ互換のテーブル。 See section MyISAM テーブル (3.23.0以上).
|
TYPE=BDB
が指定されて、
MySQL のディストリビューションが BDB
テーブルをサポートし
ない場合、代わりにテーブルは MyISAM
として生成されます。
その他のテーブルオプションを使って、テーブルの振る舞いを最適化します。
たいていの場合は、オプションを明示する必要がありません。
明示的に指定されなかった場合、オプションはすべてのテーブル型に作用します。
Option | Description |
AUTO_INCREMENT | あなたがこのテーブルにセットしたい、次の AUTO_INCREMENT 値
|
AVG_ROW_LENGTH | テーブルに含まれるレコードの長さのおおよその平均値。 可変長のレコードを持つ大きなテーブルに対してのみ、これをセットします。 |
CHECKSUM | MySQL に全てのレコードをチェックさせたい場合、これを 1 にセットします。 (これは更新を遅くさせますが、不整合の生じたテーブルを見つけ出しやすくなります) (MyISAM) |
COMMENT | テーブルの、60文字コメント |
MAX_ROWS | あなたがテーブルに保存したいと考えている最大レコード数。 |
MIN_ROWS | あなたがテーブルに保存したいと考えている最低レコード数 |
PACK_KEYS | より小さいインデックスにしたいなら、これを 1 にします。 これは更新を遅くしますが、読み出しは速くなります (MyISAM, ISAM). Setting this to 0 will disable all packing of keys. Setting this to DEFAULT (MySQL 4.0) will tell the storage engine to only pack long CHAR /VARCHAR columns.
|
PASSWORD | .frm ファイルをパスワード付きで暗号化。 このオプションは、標準の MySQL バージョンではなにも行いません。
|
DELAY_KEY_WRITE | テーブルがクローズされるまでキーテーブルの更新を送らせたい場合、1に設定します(MyISAM)。 |
ROW_FORMAT | レコードがどのように格納されるかを定義します。現在 DYNAMIC と STATIC オプションが MyISAM テーブルのために使用できるだけです。 |
MyISAM
テーブルを使用するならば、MySQL は
max_rows * avg_row_length
の値を、テーブルがどのくらい大きくなるか
の推定に使用します。
もし、上記のオプションをなにも指定しなかった場合、テーブルの最大サイズは
4G になります。(か、あなたの OS が 2G しかサポートしていなければ 2G まで)
この理由は、大きなファイルを本当に必要としない場合は、インデックスをより小
さく、より速くするため、ポインタサイズを小さく保持するためです。
PACK_KEYS
を使用しない場合、デフォルトは文字列だけをパックし、数値
はパックしません。PACK_KEYS=1
を使用するとさらに数値もパックされま
す。
バイナリ数値キーをパックする時、MySQL はプレフィックス圧縮を使用
します。これは、同じ数値を多く持つ場合にだけこの大きな恩恵を得るということ
を意味します。プレフィックス圧縮は、前のキーの何バイトが次のキーと同じであ
るかを示すための余計な1バイトがすべてのキーに必要となることを意味します(注
意: レコードへのポインタは、圧縮の向上のため high-byte-first-order でキー
の直後に格納されます)。これは、2つのレコードが同じキー多く持つ場合、後のす
べての'同じ'キーは通常2バイト(レコードへのポインタを含む)だけを必要とする
ということです。これを、通常のケースと比較してみてください。通常のケースは、
後のキーは'キーの格納サイズ' + ポインタサイズ(通常4)を必要とします。一方、
すべてのキーが全く異なっていると、キーが NULL
値を持つことができる
キーではない場合では、キー毎に1バイトを消費します(この場合、パックされたキー
の長さは、キーが NULL
の時にマークのために使用されるのと同じバイト
数で格納されます)。
CREATE
ステートメントの後に SELECT
を指定するならば、
MySQL は、SELECT
で返ってくる全ての項目を収めるために、
新しいフィールドを作成します。
例えば:
mysql> CREATE TABLE test (a INT NOT NULL AUTO_INCREMENT, -> PRIMARY KEY (a), KEY(b)) -> TYPE=MyISAM SELECT b,c FROM test2;これは 3つのフィールド a, b, c を
MyISAM
テーブルに作成します。
SELECT
ステートメントからのフィールドがテーブルの右側に追加され、上
書きされないことに注意してください。次の例を見てください:
mysql> SELECT * FROM foo; +---+ | n | +---+ | 1 | +---+ mysql> CREATE TABLE bar (m INT) SELECT n FROM foo; Query OK, 1 row affected (0.02 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM bar; +------+---+ | m | n | +------+---+ | NULL | 1 | +------+---+ 1 row in set (0.00 sec)テーブル
foo
の各レコードについて、foo
からの値と新しいフィー
ルドのデフォルト値を伴って bar
のレコードが 挿入されます。
CREATE TABLE ... SELECT
will not automatically create any indexes
for you. This is done intentionally to make the command as flexible as
possible. If you want to have indexes in the created table, you should
specify these before the SELECT
statement:
mysql> CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;もしデータをテーブルにコピーしている最中にエラーが起きたなら、 このテーブルは自動的に消去されることに注意してください。 更新ログ/バイナリログはオリジナルテーブルを再生成するために使用できます。 MySQL は
CREATE TABLE .... SELECT
中に並行しての挿入を許し
ません。
RAID_TYPE
オプションは、大規模ファイルをサポートしていない OS 上の
2G/4Gの制限を破る手助けをします。Note that this option is not recommended for
filesystem that supports big files!
また、RAID
ディレクトリを別の物理
ディスクに置くことにより、IO ボトルネックからさらに速度を得ることができま
す。RAID_TYPE
は、MySQL を --with-raid
でコンフィグ
すれば、どんな OS 上でも働きます。現在、RAID_TYPE
は
STRIPED
だけが許されています(1
と RAID0
はこれの別名
です)。
RAID_TYPE=STRIPED
を MyISAM
テーブルに指定すると、
MyISAM
はデータベースディレクトリ中に 00, 01, 02 という名前の
RAID_CHUNKS
サブディレクトリを生成します。これらのディレクトリのそ
れぞれに、MyISAM
は table_name.MYD
を生成します。データファ
イルにデータが書き込まれる時、RAID
ハンドラは最初の
RAID_CHUNKSIZE
*1024 バイトを最初のファイルに、次の
RAID_CHUNKSIZE
*1024 バイトを次のファイルにマップします。
UNION
は同じテーブルの集まりを一つとして使用したい時に使用されます。
これは MERGE テーブルでだけ動作します。See section MERGE
Tables (3.23.25以上).
今のところ、MERGE
テーブルをマップするテーブル上に SELECT
,
UPDATE
, DELETE
権限を持つことが必要です。マップされたすべて
のテーブルは MERGE
テーブルとして、同じデータベース内にある必要があ
ります。
MERGE
table, you have to specify with
INSERT_METHOD
into with table the row should be inserted.
See section MERGE
Tables (3.23.25以上). This option was introduced in MySQL 4.0.0.
PRIMARY
キーは最初に置かれ、次にすべての
UNIQUE
キー、それから通常のキーが続きます。これは MySQL オ
プティマイザを助け、どのキーを使用するかの優先度付けを行ない、重なった
UNIQUE
キーをさらにすばやく検出します。
DATA DIRECTORY="directory"
または INDEX
DIRECTORY="directory"
を使用することで、the storage engine が
テーブルとインデックスファイルを置くべき場所を指定できます。--skip-symlink
オプショ
ンを使用しない時、これは MySQL
4.0 で MyISAM
テーブルでだけ
動作します。 See section Using Symbolic Links for Tables.
いくつかのケースにおいてMySQLは、CREATE TABLE
ステートメントで与
えられたフィールド定義を暗黙の内に変更します
(これは ALTER TABLE
で起きるかもしれません)
VARCHAR
columns with a length less than four are changed to
CHAR
.
VARCHAR
、TEXT
及び
BLOB
)を持つならば、3文字より大きいフィールド長の全てのCHAR
フィールドは、
VARCHAR
フィールドに変更されます。
このことは、フィールドの使用方法には影響しません。
MySQLでは、VARCHAR
は文字列を格納するための1つの手段に過ぎません。
MySQLは、スペース埋めのコンバージョンを行いますし、テーブル操作もより速
く行います。 See section MySQL テーブル型.
TIMESTAMP
フィールドの表示サイズは、2〜14の範囲の偶数でなければなりません。
表示サイズを0や14より大きく指定した場合、サイズは14に強制されます。1から13の範
囲の奇数の場合、大きい方の偶数値に強制されます。
TIMESTAMP
フィールドには NULL
を代入できません; NULL
は
現在の日時をセットします。
NULL
and NOT NULL
属性は通常の方法では適用されず、それらを
与えた場合は無視されます。
DESCRIBE tbl_name
は常に TIMESTAMP
フィールドに NULL
値が割
り当てられた事を告げます。
もし 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 TABLE
に RENAME
以外のオプションを使用する場合、
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
を使うには、そのテーブルに ALTER
, INSERT
,
CREATE
権限が必要です。
IGNORE
はANSI SQL92に対するMySQLの拡張です。
これは、新しいテーブルのユニークキーで重複があった場合の動作を制御します。
IGNORE
が指定されない場合、コピーは異常終了し、ロールバックされます。
IGNORE
が指定された場合、ユニークキーの重複があったレコードに対し、最初の
レコードだけを使用し、他は削除されます。
ALTER TABLE
ステートメントの中で、ADD
、ALTER
、
DROP
、それからCHANGE
節の複合的な発行が可能です。
これは、ALTER TABLE
ステートメント毎に1つだけしかこれらの節を
許さないANSI SQL92に対するMySQLの拡張です。
CHANGE col_name
、DROP col_name
及びDROP
INDEX
はANSI SQL92に対するMySQLの拡張です。
MODIFY
は Oracle
の ALTER TABLE
拡張です。
COLUMN
は蛇足であり、記述を省くことが可能です。
ALTER TABLE tbl_name RENAME TO new_name
を使用すると、
MySQLはtbl_name
に一致するテーブルの名前を単純に変更します。
テンポラリテーブルの作成は必要としません。
See section RENAME TABLE
構文.
create_definition
は、CREATE TABLE
におけるADD
やCHANGE
と同じ構文を使用します。
See section CREATE TABLE
構文.
CHANGE old_col_name create_definition
節を使用することによりフィールドの名
前を変更することができます。
このようなことを行うためには、フィールドの旧名称と新名称、それからそのフィールド
の現在の型を指定する必要があります。例えば、あるINTEGER
フィールドを
a
からb
に変更する場合、以下のように実行することができます:
mysql> ALTER TABLE t1 CHANGE a b INTEGER;もしフィールドの名前を変えることなく、型だけを変更したい場合であっても、 この
CHANGE
構文は、たとえ同じ名前であっても、
2つの名前を指定するよう要求します。
例:
mysql> ALTER TABLE t1 CHANGE b b BIGINT NOT NULL;しかし MySQL バージョン 3.22.16a からは,
MODIFY
を使用して、
名称変更をすることなくフィールドの型を変更することができます。
mysql> ALTER TABLE t1 MODIFY b BIGINT NOT NULL;
CHANGE
や MODIFY
を使用して、フィールドの一部にインデックス
が存在するようなフィールドを短くしようとしても(例えば VARCHAR
フィー
ルドの最初の10文字上ににインデックスがある場合)、インデックスされた文字数
よりもフィールドを短くすることはできません。
CHANGE
や MODIFY
を用いてフィールドの型を変更する場合、
MySQLは可能な限り新しい型にデータをコンバートしようと試みます。
FIRST
又はADD ... AFTER col_name
を使用して、
テーブルのレコード内の指定した位置に、フィールドを追加すること
ができます。
デフォルトでは、フィールドは(そのレコードの)最後に追加されます。
From MySQL Version 4.0.1, you can also use the FIRST
and
AFTER
keywords in CHANGE
or MODIFY
.
ALTER COLUMN
は、フィールドの新たな初期値を指定したり、フィールドの古い初
期値を削除したりします。
古い初期値が削除され、フィールドがNULL
を許す場合、新たな初期値は
NULL
となります。
NULL
が許されない場合、section CREATE TABLE
構文 で
説明されている通り、MySQL は初期値を割り当てます。
section CREATE TABLE
構文.
DROP INDEX
は、インデックスを削除します。これはANSI SQL92に対する
MySQL の拡張です。 See section DROP INDEX
構文.
DROP TABLE
を代わりに使用してください。
DROP PRIMARY KEY
は、プライマリ・インデックスを削除します。もしプライマリ
インデックスが存在しなければ、そのテーブルの最初のUNIQUE
インデックスが削
除されます。
(MySQLは、明示的にPRIMARY KEY
が指定されなければ最初のUNIQU
E
キーをPRIMARY KEY
として扱います。)
If you add a UNIQUE INDEX
or PRIMARY KEY
to a table, this
is stored before any not UNIQUE
index so that MySQL can detect
duplicate keys as early as possible.
ORDER BY
は指定した順のレコードで新しいテーブルを生成することができ
ます。注意: 挿入と削除の後にはこの順序は保持されません。テーブルを、後で
order をしたいフィールドの順にしておくと MySQL のソートがより簡単
になる場合があります。このオプションは、主に一定の順でレコードをクエリする
つもりであることを知っているときに、主に有用です; テーブルに大きな変更をし
た後にこのオプションを使用することで、より高い性能を得ることができるdしょ
う。
ALTER TABLE
を MyISAM
テーブルに使用する場合、すべての非ユニー
クインデックスは(REPAIR
のような)別のバッチで生成されます。これは多
くのインデックスがある場合、ALTER TABLE
をより速くします。
ALTER TABLE ... DISABLE KEYS
makes MySQL to stop updating
non-unique indexes for MyISAM
table.
ALTER TABLE ... ENABLE KEYS
then should be used to recreate missing
indexes. As MySQL does it with special algorithm which is much
faster then inserting keys one by one, disabling keys could give a
considerable speedup on bulk inserts.
mysql_info()
により、どれだけのレコードがコピーされたか、(I
GNORE
が指定されている時は)どれだけのレコードがユニークキーの重複により削除され
たかを調べることができます。
FOREIGN KEY
、CHECK
及びREFERENCES
節は、
ADD CONSTRAINT FOREIGN KEY (...) REFERENCES ... (...)
を
サポートする InnoDB 型以外のテーブルでは実際には何もしません。
Note that InnoDB does not allow an index_name
to be specified. See section InnoDB
テーブル (3.23.6以上).
他のテーブルに対するこれらの構文は、互換性のためだけに用意されており、
他のSQLサーバからのコードの移植を容易にしたり、
参照情報と共にテーブルを作成するようなアプリケーションを動作
させることを目的としています。
See section MySQL と ANSI SQL92 との違い.
以下は、ALTER TABLE
の使用例を表す例です。
次に示すように作成されたテーブルt1
から始めます:
mysql> CREATE TABLE t1 (a INTEGER,b CHAR(10));
テーブルt1
の名前をt2
に変更するには:
mysql> ALTER TABLE t1 RENAME t2;
フィールド a
を INTEGER
から TINYINT NOT NULL
に
(名前は同じままで)変更し、
b
を CHAR(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
フィー
ルドはインデックスであるべきだからで、 c
を NOT 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
実行時には、ロックされたテーブルや有効なトランザクションを持
つことはできません。元のテーブルで ALTER
と DROP
権限を、新
しいテーブルで CREATE
と INSERT
権限を持つことも必要です。
MySQL が複数のテーブルのリネームで何らかのエラーに遭遇した場合、 リネームしたすべてのテーブルを逆にリネームし、すべてを元の状態に戻します。
RENAME TABLE
was added in MySQL 3.23.23.
DROP TABLE
SyntaxDROP [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
.
RESTRICT
と CASCADE
は移植を簡単にするために許されています。
しばらくはこれらは何も行ないません。
注意: 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,...)
として指定すると、複数フィールドインデックス
を作成します。
インデックスの値は、与えられたフィールドの値を連結して、構成されます。
CHAR
と VARCHAR
フィールドでは、インデックスはフィールドの一部分だ
けを使用して
作成されます。これは col_name(length)
構文を使用します。
(BLOB
と TEXT
節では 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 INDEX
は index_name
という名前のインデックスをテーブル
tbl_name
から破棄します。
DROP INDEX
は MySQL バージョン 3.22 より以前のバージョンではなに
もしません。
3.22 以降で、DROP INDEX
はインデックスの破棄のために
ALTER TABLE
を呼びだしています。
See section ALTER TABLE
構文.
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 暗黙のフィールド定義変更.
SHOW
構文は似たような情報を提供します。
See section SHOW
構文.
BEGIN/COMMIT/ROLLBACK
構文
デフォルトでは MySQL は autocommit
モードで動作します。こ
れは、更新を実行するとすぐに MySQL が更新をディスクに格納すること
を意味します。
もし トランザクションセーフのテーブル(like BDB
,
InnoDB
) を使用するなら, 以下のコマンドで MySQL を
非 autocommit
モード状態にすることができます:
SET AUTOCOMMIT=0
この後、ディスクに変更を格納するためには COMMIT
を使用し、また、変
更を無視するためには ROLLBACK
する必要があります。
ある一連のステートメントのために AUTOCOMMIT
モードからスイッチし
たい場合は、START TRANSACTION
か BEGIN
または
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
ロックを持つ場合、
このスレッドだけがテーブルの READ
と WRITE
ができます。
他のスレッドはブロックされます。
READ LOCAL
と READ
の違いは、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 WRITE
は READ
ロックをしているスレッドが一つもないと
わかっている場合に使用すべきです。
LOCK TABLES
works as follows:
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 文に干渉することができません。
これらはテーブルをロックした方がよい、まれな場合です:
READ
ロッ
クされたテーブルの更新はできませんし、他のスレッドは WRITE
ロックされた
テーブルを読むことはできません。
The reason some things are faster under LOCK TABLES
is that
MySQL will not flush the key cache for the locked tables until
UNLOCK TABLES
is called (normally the key cache is flushed after
each SQL statement). This speeds up inserting/updateing/deletes on
MyISAM
tables.
MySQL
のトランザクションをサポートしない the storage engine を使用
している場合、他のスレッドが SELECT
,UPDATE
の間に来ないことを
保証したいならば、LOCK TABLES
を使用する必要があります。
次の例は安全のためには LOCK TABLES
を必要とします:
mysql> LOCK TABLES trans READ, customer WRITE; mysql> SELECT sum(value) FROM trans WHERE customer_id= some_id; mysql> UPDATE customer SET total_value=sum_from_previous_statement -> WHERE customer_id=some_id; mysql> UNLOCK TABLES;
LOCK TABLES
を使用しない場合、SELECT
の実行と UPDATE
の
実行を行う間に、他のスレッドが新しい trans
行を挿入する隙ができます。
インクリメント アップデイト (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
コマンド行オプション.
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:
+
-
MATCH() ... AGAINST()
without the IN BOOLEAN
MODE
modifier.
< >
<
operator
decreases the contribution and the >
operator increases it.
See the example below.
( )
~
-
operator.
*
"
"
, matches only
rows that contain this phrase literally, as it was typed.
And here are some examples:
apple banana
+apple +juice
+apple macintosh
+apple -macintosh
+apple +(>pie <strudel)
apple*
"some words"
MATCH()
function must be columns from the
same table that is part of the same FULLTEXT
index, unless the
MATCH()
is IN BOOLEAN MODE
.
MATCH()
column list must exactly match the column list in some
FULLTEXT
index definition for the table, unless this MATCH()
is IN BOOLEAN MODE
.
AGAINST()
must be a constant string.
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!
ft_min_word_len
.
See section SHOW VARIABLES
.
Change it to the value you prefer, and rebuild your FULLTEXT
indexes.
(This variable is only available from MySQL version 4.0.)
ft_stopword_file
variable.
See section SHOW VARIABLES
.
Rebuild your FULLTEXT
indexes after modifying the stopword list.
(This variable is only available from MySQL version 4.0.10 and onwards)
#define GWS_IN_USE GWS_PROBTo:
#define GWS_IN_USE GWS_FREQThen recompile MySQL. There is no need to rebuild the indexes in this case. Note: by doing this you severely decrease MySQL's ability to provide adequate relevance values for the
MATCH()
function.
If you really need to search for such common words, it would be better to
search using IN BOOLEAN MODE
instead, which does not observe the 50%
threshold.
ft_boolean_syntax
variable.
See section SHOW VARIABLES
.
Still, this variable is read-only, its value is set in
`myisam/ft_static.c'.
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;
FULLTEXT
index faster.
MERGE
tables.
FULLTEXT
in CREATE/ALTER TABLE
).
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):
query_cache_size=0
.
By disabling the query cache code there is no noticeable overhead.
(query cache can be excluded from code with help of configure option
--without-query-cache
)
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.
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
.
query_cache_limit
Don't cache results that are bigger than this. (Default 1M).
query_cache_size
The amount of memory (specified in bytes) allocated to store results from
old queries. If this is 0, the query cache is disabled (default).
query_cache_type
This may be set (only numeric) to
Option | Description |
0 | (OFF, don't cache or retrieve results) |
1 | (ON, cache all results except SELECT SQL_NO_CACHE ... queries)
|
2 | (DEMAND, cache only SELECT SQL_CACHE ... queries)
|
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.
|
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. |
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.
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):
COMMIT
command.
ROLLBACK
to ignore your changes (if you are not
running in auto-commit mode).
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
file that indicates whether
the table was closed correctly. If mysqld
is started with
--myisam-recover
, MyISAM
tables will automatically be
checked and/or repaired on open if the table wasn't closed properly.
INSERT
new rows in a table that doesn't have free blocks
in the middle of the datafile, at the same time other threads are
reading from the table (concurrent insert). An free block can come from
an update of a dynamic length row with much data to a row with less data
or when deleting rows. When all free blocks are used up, all future
inserts will be concurrent again.
AUTO_INCREMENT
column. MyISAM
will automatically update this on INSERT/UPDATE
. The
AUTO_INCREMENT
value can be reset with myisamchk
. This
will make AUTO_INCREMENT
columns faster (at least 10%) and old
numbers will not be reused as with the old ISAM
. Note that when an
AUTO_INCREMENT
is defined on the end of a multi-part-key the old
behaviour is still present.
AUTO_INCREMENT
column) the key tree will be split so that the high node only contains one
key. This will improve the space utilisation in the key tree.
BLOB
と TEXT
フィールドにインデックスが張れます
NULL
値をインデックスの張られたフィールドに許します. This takes 0-1
bytes/key.
myisamchk
を再コンパイル無しに、64個まで増やすことが出来ます.
myisamchk
を --update-state
オプションで実行すると、
myisamchk
はテーブルにチェックをおこなったマークをつけます。
myisamchk --fast
は、このマークが無いテーブルだけをチェックします。
myisamchk -a
stores statistics for key parts (and not only for
whole keys as in ISAM
).
myisampack
は BLOB
と VARCHAR
フィールドをパックすることが
可能です。
DATA/INDEX DIRECTORY="path"
option to
CREATE TABLE
). See section CREATE TABLE
構文.
MyISAM
also supports the following things, which MySQL
will be able to use in the near future:
VARCHAR
型のサポート; a VARCHAR
column starts
with a length stored in 2 bytes.
VARCHAR
may have fixed or dynamic record length.
VARCHAR
and CHAR
may be up to 64K.
All key segments have their own language definition. This will enable
MySQL to have different language definitions per column.
UNIQUE
. This will allow
you to have UNIQUE
on any combination of columns in a table. (You
can't search on a UNIQUE
computed index, however.)
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
コマンド行オプション.
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 BLOB
s 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
構文.
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:
CHAR
, NUMERIC
, DECIMAL
フィールドは、そのフィールド
長に足りない部分にはスペースが埋められます。
myisamchk
) unless a huge number of
records are deleted and you want to return free disk space to the operating
system.
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 table
か myisamchk
を使用して、テーブルの
フラグメンテーションを修正することが可能です。
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:
''
)なのか、
どの数値フィールドがゼロなのかを示します。
(これはフィールドの値が NULL
値とは違います)。
もし、文字型フィールドの文字列の長さ(後に続く空白は取り除かれる)が ゼロ で
あったり、あるいは、数値フィールドの値が ゼロ であった場合は、
そのフィールドはビット・マップにマークされ、値はディスクには保存されません。
空文字ではない場合は、文字列のバイト数がビット・マップに記録され、
文字列自身がフィールドに保存されます。
myisamchk
-r
from time to time to get better performance. Use myisamchk -ei
tbl_name
for some statistics.
3 + (フィールド数 + 7) / 8 + (char フィールドの数) + 数値フィールドをパックしたサイズ + 文字の長さ + (NULL フィールドの数 + 7) / 8There is a penalty of 6 bytes for each link. A dynamic record is linked whenever an update causes an enlargement of the record. Each new link will be at least 20 bytes, so the next enlargement will probably go in the same link. If not, there will be another link. You may check how many links there are with
myisamchk -ed
. All links may be removed with myisamchk -r
.
これは、myisampack
ツール (pack_isam
は ISAM
テーブル用)に
myisampack
で圧縮されたテーブルを読むことが可能です。
0
are stored using 1 bit.
BIGINT
フィールド(8bytes)の値全てが 0
から 255
に
収まっていれば、TINYINT
フィールド (1 byte) に保存されます。
ENUM
.
myisamchk
で、伸長できます。
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文を返す前に テーブルへの変更を全て書き出す)、 以下のような事が起きた場合には、テーブルが壊れるかもしれません:
mysqld
プロセスが書き込み途中で kill された
壊れたテーブルの、典型的な症状は:
Incorrect key file for table: '...'. Try to repair it
エラーが出る
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.
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:
FLUSH
or
because there isn't room in the table cache) the counter is
decremented if the table has been updated at any point.
In other words, the only ways this can go out of sync are:
MyISAM
tables are copied without a LOCK
and
FLUSH TABLES
.
myisamchk --recover
or myisamchk
--update-state
on a table that was in use by mysqld
.
mysqld
servers are using the table and one has done a
REPAIR
or CHECK
of the table while it was in use by
another server. In this setup the CHECK
is safe to do (even if
you will get the warning from other servers), but REPAIR
should
be avoided as it currently replaces the datafile with a new one, which
is not signaled to the other servers.
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
テーブルは以下の問題の解決を助けます:
myisampack
, and then create a MERGE
to use these as one.
MERGE
table on this could be much faster than using
the big table. (You can, of course, also use a RAID to get the same
kind of benefits.)
MERGE
table for others. You can even have many
different MERGE
tables active, with possible overlapping files.
MERGE
file than trying to repair a really big file.
MERGE
table uses the
index of the individual tables. It doesn't need to maintain an index of
its one. This makes MERGE
table collections VERY fast to make or
remap. Note that you must specify the key definitions when you create
a MERGE
table!.
MERGE
table on them on demand.
This is much faster and will save a lot of disk space.
MERGE
over one table. There shouldn't be any really notable performance
impacts of doing this (only a couple of indirect calls and memcpy()
calls for each read).
MERGE
の欠点は:
MERGE
には、同一構造の MyISAM
テーブルしか使用できません。
AUTO_INCREMENT
フィールドは、INSERT
時に、自動で更新されません。
REPLACE
は動作しません。
MERGE
テーブルはより多くのファイル・デスクリプタを使用します。
If you are using a
MERGE
table that maps over 10 tables and 10 users are using this, you
are using 10*10 + 10 file descriptors. (10 datafiles for 10 users
and 10 shared index files.)
MERGE
storage engine will need to issue a read on all underlying tables to check
which one most closely matches the given key. If you then do a "read-next"
then the MERGE
storage engine will need to search the read buffers
to find the next key. Only when one key buffer is used up, the storage engine
will need to read the next key block. This makes MERGE
keys much slower
on eq_ref
searches, but not much slower on ref
searches.
See section EXPLAIN
構文 (SELECT
についての情報を得る).
DROP TABLE
,
ALTER TABLE
,
DELETE FROM table_name
without a WHERE
clause,
REPAIR TABLE
,
TRUNCATE TABLE
,
OPTIMIZE TABLE
, or
ANALYZE TABLE
on any of the table that is
mapped by a MERGE
table that is "open". If you do this, the
MERGE
table may still refer to the original table and you will
get unexpected results. The easiest way to get around this deficiency
is to issue the FLUSH TABLES
command, ensuring no MERGE
tables remain "open".
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_METHOD
や NO
を指定しなかったなら、
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:
DROP
the table and re-create it
ALTER TABLE table_name UNION(...)
FLUSH TABLE
on the
MERGE
table and all underlying tables to force the storage engine to
read the new definition file.
MERGE
Table Problems
The following are the known problems with MERGE
tables:
MERGE
table cannot maintain UNIQUE
constraints over the
whole table. When you do INSERT
, the data goes into the first or
last table (according to INSERT_METHOD=xxx
) and this MyISAM
table ensures that the data are unique, but it knows nothing about
others MyISAM
tables.
DELETE FROM merge_table
used without a WHERE
will only clear the mapping for the table, not delete everything in the
mapped tables.
RENAME TABLE
on a table used in an active MERGE
table may
corrupt the table. This will be fixed in MySQL 4.0.x.
MERGE
doesn't check if the underlying
tables are of compatible types. If you use MERGE
tables in this
fashion, you are very likely to run into strange problems.
ALTER TABLE
to first add an UNIQUE
index to a
table used in a MERGE
table and then use ALTER TABLE
to
add a normal index on the MERGE
table, the key order will be
different for the tables if there was an old non-unique key in the
table. This is because ALTER TABLE
puts UNIQUE
keys before
normal keys to be able to detect duplicate keys as early as possible.
MERGE
table efficiently and may
sometimes produce non-optimal joins. This will be fixed in MySQL 4.0.x.
DROP TABLE
on a table that is in use by a MERGE
table will
not work on Windows because the MERGE
storage engine 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
VIEW
s.
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:
ISAM
tables are not binary portable across OS/Platforms.
pack_isam
rather than with myisampack
.
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:
MAX_ROWS
in the CREATE
statement
to ensure that you accidentally do not use all memory.
=
and <=>
(but are VERY fast).
HEAP
tables can only use whole keys to search for a row; compare this
to MyISAM
tables where any prefix of the key can be used to find rows.
HEAP
テーブルは 固定長のレコードです。
HEAP
は BLOB
/TEXT
型をサポートしません。
HEAP
は AUTO_INCREMENT
フィールドをサポートしません。
HEAP
は NULL
が許されているフィールドにインデックスを張れません。
HEAP
テーブルに、一意ではないキーを持たせることが可能です。
(this isn't common for hashed tables).
HEAP
テーブルは全てのクライアントに共有されます (他のテーブルと同じように)
ORDER BY
).
HEAP
tables are allocated in small blocks. The tables
are 100% dynamic (on inserting). No overflow areas and no extra key
space are needed. Deleted rows are put in a linked list and are
reused when you insert new data into the table.
HEAP
tables that you want to use at
the same time.
DELETE FROM heap_table
,
TRUNCATE heap_table
, DROP TABLE heap_table
を実行すべきです.
MyISAM
table to a HEAP
table.
HEAP
tables bigger than max_heap_table_size
.
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 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 SELECT
s. 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.
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:
SET
command of MS-DOS to print the value of WINDIR.
Where to specify options in Unix? On Unix `mysqld' reads options from the following files, if they exist, in the following order:
--defaults-extra-file=...
.
`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 .
|
あなたが 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
If InnoDB prints an operating system error in a file operation, usually the problem is one of the following:
innodb_data_home_dir
or innodb_data_file_path
.
もし 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.
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)は正確です。
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 が完了するのを待つよりも。
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.
バージョン 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 は 新しいログファイルを作成したことを告げるでしょう。
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.
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 データベースは、全てのファイルを単純にコピーするだけで、
移動が可能です。 ファイルは、前述のデータベースのバックアップの節で
述べたものです。
もし浮動小数点数のフォーマットが違う機械であったとしても、
テーブルに FLOAT
や DOUBLE
の型を使用していないのであれば、
手順は同じです: すなわち単にファイルをコピーするだけです。
もし浮動小数点数のフォーマットが違う機械で、テーブルに
浮動小数点数を保存している場合は、
`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.
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:
READ UNCOMMITTED
This is also called
'dirty read': non-locking SELECT
s are performed
so that we do not look at a possible earlier version of a record;
thus they are not 'consistent' reads under this isolation level;
otherwise this level works like READ COMMITTED
.
READ COMMITTED
Somewhat Oracle-like isolation level.
All SELECT ... FOR UPDATE
and
SELECT ... LOCK IN SHARE MODE
statements
only lock the index records, NOT the gaps before them, and
thus allow free inserting of new records next to locked
records.
UPDATE
and DELETE
which use
a unique index with a unique search condition,
only lock the index record found, not the gap before it.
But still in range type
UPDATE
and DELETE
InnoDB
must set next-key or gap locks and block insertions
by other users to the
gaps covered by the range. This is necessary
since 'phantom rows' have to be blocked for MySQL
replication and recovery to work.
Consistent reads behave like in
Oracle: each consistent read, even within the same
transaction, sets and reads its own fresh snapshot.
REPEATABLE READ
This is the default isolation level of
InnoDB.
SELECT ... FOR UPDATE
, SELECT ... LOCK IN SHARE MODE
,
UPDATE
, and DELETE
which use
a unique index with a unique search condition,
only lock the index record found, not the gap before it.
Otherwise these operations employ next-key locking, locking
the index range scanned with next-key or gap locks, and
block new insertions by other users.
In consistent reads there is an important difference
from the previous isolation level: in this level
all consistent reads within the same transaction read the
same snapshot established by the first read. This convention
means that if you issue several plain SELECT
s
within the same transaction, these SELECT
s are
consistent also with respect to each other.
SERIALIZABLE
This level is like
the previous one, but
all plain SELECT
s are implicitly converted to
SELECT ... LOCK IN SHARE MODE
.
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.
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.
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.
SELECT ... FROM ...
: this is a consistent read, reading a
snapshot of the database and setting no locks.
SELECT ... FROM ... LOCK IN SHARE MODE
: sets shared next-key locks
on all index records the read encounters.
SELECT ... FROM ... FOR UPDATE
: sets exclusive next-key locks
on all index records the read encounters.
INSERT INTO ... VALUES (...)
: sets an exclusive lock
on the inserted row; note that this lock is not a next-key lock
and does not prevent other users from inserting to the gap before the
inserted row. If a duplicate key error occurs, sets a shared lock
on the duplicate index record.
INSERT INTO T SELECT ... FROM S WHERE ...
sets an exclusive
(non-next-key) lock on each row inserted into T
. Does
the search on S
as a consistent read, but sets shared next-key
locks on S
if the MySQL logging is on. InnoDB has to set
locks in the latter case because in roll-forward recovery from a
backup every SQL statement has to be executed in exactly the same
way as it was done originally.
CREATE TABLE ... SELECT ...
performs the SELECT
as a consistent read or with shared locks, like in the previous
item.
REPLACE
is done like an insert if there is no collision
on a unique key. Otherwise, an exclusive next-key lock is placed
on the row which has to be updated.
UPDATE ... SET ... WHERE ...
: sets an exclusive next-key
lock on every record the search encounters.
DELETE FROM ... WHERE ...
: sets an exclusive next-key
lock on every record the search encounters.
FOREIGN KEY
constraint is defined on a table,
any insert, update, or delete which requires checking of the constraint
condition sets shared record level locks on the records it
looks at to check the constraint. Also in the case where the
constraint fails, InnoDB sets these locks.
LOCK TABLES ...
: sets table locks. In the implementation
the MySQL layer of code sets these locks. The automatic deadlock detection
of InnoDB cannot detect deadlocks where such table locks are involved:
see the following section.
Also, since MySQL does know about row level locks,
it is possible that you
get a table lock on a table where another user currently has row level
locks. But that does not put transaction integerity into danger.
See section InnoDB テーブルの制限.
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:
SHOW INNODB STATUS
in MySQL versions >= 3.23.52 and >= 4.0.3
to determine the cause of the latest deadlock. That can help you to tune
your application to avoid deadlocks.
SELECT ... FOR UPDATE
or ... LOCK IN SHARE MODE
, try using a lower isolation
level READ COMMITTED
.
EXPLAIN SELECT
to determine that MySQL picks
appropriate indexes for your queries.
SELECT
to return data
from an old snapshot, do not add the clause FOR UPDATE
or LOCK IN SHARE MODE
to it. Using READ COMMITTED
isolation level is good here, because each consistent read
within the same transaction reads from its own fresh snapshot.
LOCK TABLES t1 WRITE, t2 READ, ... ;
[do something with tables t1 and t2 here]; UNLOCK TABLES
.
Table level locks make you transactions to queue nicely,
and deadlocks are avoided. Note that LOCK TABLES
implicitly starts a transaction, just like the command BEGIN
,
and UNLOCK TABLES
implicitly ends the transaction in a COMMIT
.
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.
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;
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_method
を O_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 だけではなく、他のテーブル型にインサートする時も使用できます。
バージョン 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
出力に関するいくつかの注釈:
UNIV_SYNC_DEBUG
を有効にして、InnoDB をコンパイルしているならば。
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.
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 されるというのは、 データベースのアプリケーションではよくある事です。 この場合は、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.
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.
データベースがスタートアップした後、ユーザーが
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.
ディスク 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.
設定ファイルに記述したデータファイルを 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.
'Table is full'
エラーとなり、
InnoDB は SQL 文をロール・バックします。
INSERT INTO ... SELECT ...
.
This will probably change so that the SQL statement will be rolled
back if you have not specified the IGNORE
option in your
statement.
mysql_install_db
スクリプトを使用して
システムテーブルを再構築しない限り、MySQL は起動できません。
SHOW TABLE STATUS
は、
InnoDB テーブルに関する統計を正確に返しません
(ただしテーブルが使用している物理サイズは正確)。
The row count is only a rough estimate used in SQL optimisation.
CREATE TABLE T (A CHAR(20), B INT, UNIQUE (A(5))) TYPE = InnoDB;もし、フィールドの先頭部分に、非ユニークインデックスを作成しようとすると、 InnoDB は そのフィールドの全体にインデックスを張ります。
INSERT DELAYED
は InnoDB テーブルではサポートされていません。
LOCK TABLES
オペレーションは、 InnoDB のロー・レベル・ロック
(row level lock) を感知しません。
これは、たとえ他のユーザーによるトランザクション(row lovel lock をしている)が
あるテーブルに存在していたとしても、
あなたが同じテーブルに対して、テーブル・ロックをかけれるということです。
Thus
your operations on the table may have to wait if they collide with
these locks of other users. Also a deadlock is possible. However,
this does not endanger transaction integrity, because the row level
locks set by InnoDB will always take care of the integrity.
Also, a table lock prevents other transactions from acquiring more
row level locks (in a conflicting lock mode) on the table.
BLOB
や TEXT
フィールドにインデックスを張ることができません。
DELETE FROM TABLE
does not regenerate the table but instead
deletes all rows, one by one, which is not that fast. In future versions
of MySQL you can use TRUNCATE
which is fast.
HANDLER
SQL commands now work also for InnoDB
type tables. InnoDB
does the HANDLER
reads always as
consistent reads. HANDLER
is a direct access path to read
individual indexes of tables. In some cases HANDLER
can be
used as a substitute of server-side cursors.
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
TablesBDB
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.
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
構文.
BDB
tables:BDB
storage engine maintains
log files. For maximum performance you should place these on another disk
than your databases by using the --bdb-logdir
option.
BDB
log
file is started, and removes any log files that are not needed for
current transactions. One can also run FLUSH LOGS
at any time
to checkpoint the Berkeley DB tables.
For disaster recovery, one should use table backups plus
MySQL's binary log. See section データベースのバックアップ.
Warning: If you delete old log files that are in use, BDB
will
not be able to do recovery at all and you may lose data if something
goes wrong.
PRIMARY KEY
in each BDB
table to be
able to refer to previously read rows. If you don't create one,
MySQL will create an maintain a hidden PRIMARY KEY
for
you. The hidden key has a length of 5 bytes and is incremented for each
insert attempt.
BDB
table are part of the same index or
part of the primary key, then MySQL can execute the query
without having to access the actual row. In a MyISAM
table the
above holds only if the columns are part of the same index.
PRIMARY KEY
will be faster than any other key, as the
PRIMARY KEY
is stored together with the row data. As the other keys are
stored as the key data + the PRIMARY KEY
, it's important to keep the
PRIMARY KEY
as short as possible to save disk and get better speed.
LOCK TABLES
works on BDB
tables as with other tables. If
you don't use LOCK TABLE
, MySQL will issue an internal
multiple-write lock on the table to ensure that the table will be
properly locked if another thread issues a table lock.
BDB
tables is done on page level.
SELECT COUNT(*) FROM table_name
is slow as BDB
tables doesn't
maintain a count of the number of rows in the table.
MyISAM
tables as the data in
BDB
tables stored in B-trees and not in a separate datafile.
BDB
table may make an automatic rollback and any
read may fail with a deadlock error.
MyISAM
tables. In other words, the key information will take a little more
space in BDB
tables compared to MyISAM
tables.
BDB
table to allow you to insert new rows in
the middle of the key tree. This makes BDB
tables somewhat larger than
MyISAM
tables.
BDB
table. If you don't
issue a lot of DELETE
or ROLLBACK
statements, this number
should be accurate enough for the MySQL optimiser, but as MySQL
only stores the number on close, it may be incorrect if MySQL dies
unexpectedly. It should not be fatal even if this number is not 100%
correct. One can update the number of rows by executing ANALYZE
TABLE
or OPTIMIZE TABLE
. See section ANALYZE TABLE
Syntax . See section OPTIMIZE TABLE
構文.
BDB
table, you will get an error
(probably error 28) and the transaction should roll back. This is in
contrast with MyISAM
and ISAM
tables where mysqld
will
wait for enough free disk before continuing.
BDB
in the near future:BDB
tables at the same time. If you are
going to use BDB
tables, you should not have a very big table cache
(like >256) and you should use --no-auto-rehash
with the mysql
client. We plan to partly fix this in 4.0.
SHOW TABLE STATUS
doesn't yet provide that much information for
BDB
tables.
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.
BDB
Tables
Here follows the restrictions you have when using BDB
tables:
BDB
tables store in the `.db' file the path to the file as it was
created.
(This was done to be able to detect locks in a multi-user environment that
supports symlinks).
The effect of this is that BDB
tables are not movable between directories!
BDB
tables, you have to either use
mysqldump
or take a backup of all table_name.db
files and
the BDB
log files. The BDB
log files are the files in the base
data directory named log.XXXXXXXXXX
(ten digits);
The BDB
storage engine stores unfinished transactions in the log files
and requires these logs to be present when mysqld
starts.
BDB
Tableshostname.err log
when
starting mysqld
:
bdb: Ignoring log file: .../log.XXXXXXXXXX: unsupported log version #it means that the new
BDB
version doesn't support the old log
file format. In this case you have to delete all BDB
logs
from your database directory (the files with names that have the format
log.XXXXXXXXXX
) and restart mysqld
. We would also
recommend you to do a mysqldump --opt
of your old BDB
tables, delete the old tables, and restore the dump.
001119 23:43:56 bdb: Missing log fileid entry 001119 23:43:56 bdb: txn_abort: Log undo failed for LSN: 1 3644744: InvalidThis is not fatal but we don't recommend that you delete tables if you are not in auto-commit mode, until this problem is fixed (the fix is not trivial).
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.
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/).
-lz
last when linking
with -lmysqlclient
.
ここでは 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
DBI
InterfacePortable 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
$sth
$rc
$rv
汎用 DBI メソッド
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_USER
と DBI_PASS
をそれぞれ使う。
ホスト名を指定しない場合は、'localhost'
がデフォルトとなる。
ポート番号を指定しない場合は、MySQL ポート()
がデフォルトとなる。
As of Msql-Mysql-modules
Version 1.2009,
the $data_source
value allows certain modifiers:
mysql_read_default_file=file_name
mysql_read_default_group=group_name
[client]
group. By specifying the mysql_read_default_group
option, the default group becomes the [group_name]
group.
mysql_compression=1
mysql_socket=/path/to/socket
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)
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
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
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)
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 handleYou 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
AUTO_INCREMENT
を使うとき、
新しい自動繰り上がり値がここに記憶される。例:
Example:
$new_id = $sth->{insertid};As an alternative, you can use
$dbh->{'mysql_insertid'}
.
is_blob
BLOB
値であることを示す。例:
$keys = $sth->{is_blob};
is_key
$keys = $sth->{is_key};
is_num
$nums = $sth->{is_num};
is_pri_key
$pri_keys = $sth->{is_pri_key};
is_not_null
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 は 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
.
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).
MyODBC
は Open 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
をインストールしなくては
なりません。
GRANT
コマンドで可能です。
See section GRANT
と REVOKE
構文.
MyODBC の設定画面には、MySQL 接続時のオプションがいくつか 設定できるようになっています。 もし問題がある場合は、これらを試します。
Windows95 上のサーバ名の記述には3つの可能性があります:
ip hostname例えば:
194.216.84.21 my_hostname
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
にすると,
client
と odbc
グループは `C:\my.cnf' ファイルから読まれます。
mysql_options()
で使用できる全てのオプションが利用可能です。
See section mysql_options()
.
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
は以下でテストされました: 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.
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:
Microsoft Data Access
Components
) from http://www.microsoft.com/data/. This will fix
the following bug in Access: when you export data to MySQL, the
table and column names aren't specified. Another way to around this bug
is to upgrade to MyODBC Version 2.50.33 and MySQL Version
3.23.x, which together provide a workaround for this bug!
You should also get and apply the Microsoft Jet 4.0 Service Pack 5 (SP5)
which can be found here
http://support.microsoft.com/support/kb/articles/Q 239/1/14.ASP.
This will fix some cases where columns are marked as #deleted#
in Access.
Note that if you are using MySQL Version 3.22, you must to apply the
MDAC patch and use MyODBC 2.50.32 or 2.50.34 and above to go around
this problem.
Return matching rows
. For Access 2.0, you should additionally enable
Simulate ODBC 1.0
.
TIMESTAMP(14)
or simple TIMESTAMP
is recommended instead of other TIMESTAMP(X)
variations.
#DELETED#
.
DOUBLE
float fields. Access fails when comparing with
single floats. The symptom usually is that new or updated rows may show
up as #DELETED#
or that you can't find or update rows.
tem
If you are linking a table through MyODBC, which has BIGINT
as
one of the column, then the results will be displayed as #DELETED
. The
work around solution is:
TIMESTAMP
as the data type, preferably
TIMESTAMP(14)
.
'Change BIGINT columns to INT'
in connection options dialog in
ODBC DSN Administrator
#DELETED#
, but newly
added/updated records will be displayed properly.
#Deleted#
or that you can't find or update rows.
Another user has changed your data
after
adding a TIMESTAMP
column, the following trick may help you:
Don't use table
data sheet view. Create instead a form with the
fields you want, and use that form
data sheet view. You should
set the DefaultValue
property for the TIMESTAMP
column to
NOW()
. It may be a good idea to hide the TIMESTAMP
column
from view so your users are not confused.
"Query|SQLSpecific|Pass-Through"
を選択すれば
直すことが可能です。
BLOB
フィールドを OLE OBJECTS
と認識します。
もし MEMO
フィールドを代わりに使用したいなら、 ALTER TABLE
を使って、
TEXT
型にフィールドを変更しなくてはなりません。
DATE
フィールドをいつも正しく扱うことが出来ません。
もしこれらの問題があった場合、フィールド型を DATETIME
に変えてください。
BYTE
, Access will try
to export this as TINYINT
instead of TINYINT UNSIGNED
.
This will give you problems if you have values > 127 in the column!
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.CloseAnother workaround is to use a
SELECT COUNT(*)
statement
for a similar query to get the correct row count.
Return matching rows
.
Don't optimize column widths
and Return matching rows
.
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!
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.
VARCHAR
rather than ENUM
, as
it exports the latter in a manner that causes MySQL grief.
CONCAT()
関数を使用し、文字として SELECT してみて
ください。 例えば:
select CONCAT(rise_time), CONCAT(set_time) from sunrise_sunset;この方法で文字として返ってきた値を、Excel97 で時間として扱うようにすべきです。 この例の
CONCAT()
の目的は、フィールドの型が文字列であると ODBC をだます
ことです。
CONCAT()
がなければ、ODBC はフィールドの型が日付とわかるので、
Excel が今度はそれを理解できなくなります。
これは Excel のバグです。なぜなら文字を自動で日付に直すのですから。
これは単にテキストファイルの情報を扱う場合ならばいいのですが、
各項目の型を知らせる ODBC 接続の情報を扱う場合は、とても愚かな方法です。
MyODBC
driver and the Add-in Microsoft Query help.
For example, create a db with a table containing 2 columns of text:
mysql
client command-line tool.
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);
Return matching rows
.
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.
[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.
Don't optimize column widths
.
AUTO_INCREMENT
フィールドの値を ODBC で得る方法
共通の問題は、INSERT
で自動的に生成されるIDの値を得ることです。
ODBCでは、以下のようにします( 例中の auto
が AUTO_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;
もし MyODBC
使用時に難しい問題にあたった場合、
ODBC マネージャのログファイル (ODBCADMIN からリクエストしたときのログ)
と MyODBC
のログを取り始めるべきです。
これはいかなる問題にも解決の糸口になるはずです。
MyODBC
のログを取るには、以下のように行ないます:
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).
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!
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 スレッドクライアントを作る方法. を参考にしてください。
MYSQL
MYSQL_RES
SELECT
, SHOW
, DESCRIBE
, EXPLAIN
)の結果を表わ
します。クエリから返される情報は、この節の残りでは結果セットと呼
ばれます。
MYSQL_ROW
mysql_fetch_row()
の呼び出しによりレコードが獲得
されます。
MYSQL_FIELD
mysql_fetch_field()
を繰り返し呼び出すことにより、各フィールドの
MYSQL_FIELD
構造体を得ることができます。
フィールド値はこの構造体の一部ではありません; それは MYSQL_ROW
構造
体に含まれています。
MYSQL_FIELD_OFFSET
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
char * table
table
値は空文字列です。
char * def
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->type
を FIELD_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 には次に一覧された関数が存在します。これらの関数は次の節でかな り詳細に説明されています。 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 はエラー情報へのア
クセスを提供します。これらは、最後に呼び出された成功または失敗し得る関数に
ついてのエラーコードとエラーメッセージを返し、エラーがいつ何で発生したかを
確定することができます。
以下の説明では、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
CR_SERVER_LOST
CR_UNKNOWN_ERROR
ER_UNKNOWN_COM_ERROR
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)
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.
The default character set
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
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
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
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)
によって与えられます。
row
が mysql_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)
Returns version number of server as an integer (new in 4.1).
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.
None.
mysql_get_host_info()
char *mysql_get_host_info(MYSQL *mysql)
使用中の接続タイプを表わす文字列を返します。サーバのホスト名を含みます。
サーバホスト名と接続タイプを表わす文字列。
無し。
mysql_get_proto_info()
unsigned int mysql_get_proto_info(MYSQL *mysql)
現在の接続に使用されているプロトコルバージョンを返します。
現在の接続に使用されているプロトコルバージョンを表わす符号無し整数値。
無し。
mysql_get_server_info()
char *mysql_get_server_info(MYSQL *mysql)
サーバのバージョン番号を表わす文字列を返します。
サーバのバージョン番号を表わす文字列。
無し。
mysql_info()
char * mysql_info(MYSQL *mysql)
最も最近に実行されたクエリについての情報を文字列で返します。が、
以下に挙げる構文に限ります。
他の構文ではmysql_info()
は NULL
を返します。
文字列の形式
はクエリの型によって様々です。次に説明します (数値は例です; 文字列はクエ
リに適した値を含みます):
INSERT INTO ... SELECT ...
Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
Records: 3 Duplicates: 0 Warnings: 0
UPDATE
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
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
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
CR_SERVER_LOST
CR_UNKNOWN_ERROR
mysql_list_processes()
MYSQL_RES *mysql_list_processes(MYSQL *mysql)
現在のサーバスレッドを示す結果セットを返します。これは mysqladmin
processlist
や SHOW PROCESSLIST
クエリで
報告されるものと同じ種類の情報です。
mysql_free_result()
で結果セットを解放する必要があります。
成功時 MYSQL_RES
結果セット。失敗した場合は NULL
。
CR_COMMANDS_OUT_OF_SYNC
CR_SERVER_GONE_ERROR
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
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_FILE
と MYSQL_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
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
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
構造体のアドレスです。
mysql_real_connect()
を呼ぶ前に、MYSQL
構造体の初期化のため
に mysql_init()
を呼ぶ必要があります。
mysql_options()
呼び出しで多くの接続オプションを変更できます。
See section mysql_options()
.
host
の値はホスト名か IP アドレスのどちらでも可能です。
host
が NULL
または文字列 "localhost"
の場合はロー
カルホストへの接続とみなされます。OS がソケットをサポートする場合(UNIX)
または名前つきパイプをサポートする場合(Windows)、サーバへの TCP/IP 接続の
代わりに使用されます。
user
パラメータはユーザの MySQL ログイン ID が入っています。
user
が NULL
の場合、現在のユーザとみなされます。Windows
ODBC 下では、現在のユーザは明示的に指定されなければなりません。UNIX 下で
は現在のログイン名が適用されます。
Windows ODBC では, カレントのユーザー名を与えなければなりません。
See section ODBC 管理プログラムの各種項目を埋めるには?.
passwd
パラメータは user
のパスワードが入っています。
もし passwd
が NULL
の場合、空白のパスワードフィールドを持つ
user
テーブル内のレコードだけが適合チェックされます。このような方
法で、パスワードが記述されたかどうかによってユーザが異なる権限を得るよう
に、データベース管理者が MySQL 特権システムを設定することができ
ます。
注意: mysql_connect()
を呼び出す前に passwd
を暗号化しない
でください。パスワードの暗号化はクライアント API で自動的に処理されます。
db
が NULL
でない場合、接続はこの値をデフォルトデータベー
スにセットします。
port
が 0 でない場合、値は TCP/IP 接続のポート番号として使用され
ます。host
パラメータが接続のタイプを決定することに注意してくださ
い。
unix_socket
が NULL
でない場合、文字列は使用されるソケット
または名前つきパイプを記述します。host
パラメータが接続のタイプを
決定することに注意してください。
フラグ名 | フラグの意味 |
CLIENT_COMPRESS | Use compression protocol. |
CLIENT_FOUND_ROWS | 影響された行数ではなく見つかった行数を返します |
CLIENT_IGNORE_SPACE | Allow spaces after function names. Makesall functions names reserved words. |
CLIENT_INTERACTIVE | Allow interactive_timeout seconds(instead of wait_timeout seconds) of inactivity before closing the connection.
|
CLIENT_NO_SCHEMA | db_name.tbl_name.col_name を許しません。これは ODBC のためです; その構文を使用した場合、パーサがエラーを生成します。これはいくつかの ODBC プログラムのバグのトラップに役立ちます。
|
CLIENT_COMPRESS | 圧縮プロトコルを使用します |
CLIENT_ODBC | クライアントが ODBC クライアント。これは mysqld をさらに ODBC-フレンドリに変更します。
|
CLIENT_SSL | Use SSL (encrypted protocol). |
mysql_real_connect()
の最初の引数に NULL
ポインタを記述す
ることもできます。これは C API が接続構造体のメモリを割り当て、
mysql_close()
呼び出し時に自動的に解放されます。この方法の不利な
点は、接続が失敗した場合に mysql_real_connect()
からのエラーメッ
セージを取り出すことができないことです。
最初の引数が NULL
ポインタでない場合は、存在する MYSQL
構
造体のアドレスであるべきです。
接続が成功した場合は MYSQL*
接続ハンドルです。接続が失敗した場合
は C NULL
ポインタです。
接続に成功すると、戻り値はその最初のパラメータの値と同じです。
CR_CONN_HOST_ERROR
CR_CONNECTION_ERROR
CR_IPSOCK_ERROR
CR_OUT_OF_MEMORY
CR_SOCKET_CREATE_ERROR
CR_UNKNOWN_HOST
CR_VERSION_ERROR
--old-protocol
オプション付きで開始していない新
しいサーバに接続する場合に発生します。
CR_NAMEDPIPEOPEN_ERROR
CR_NAMEDPIPEWAIT_ERROR
CR_NAMEDPIPESETSTATE_ERROR
CR_SERVER_LOST
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
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
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
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
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
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
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
CR_SERVER_LOST
CR_UNKNOWN_ERROR
You need to use the following functions when you want to create a threaded client. See section スレッドクライアントを作る方法.
my_init()
void my_init(void)
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()
.
None.
mysql_thread_init()
my_bool mysql_thread_init(void)
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()
.
None.
mysql_thread_end()
void mysql_thread_end(void)
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.
None.
mysql_thread_safe()
unsigned int mysql_thread_safe(void)
This function indicates whether the client is compiled as thread-safe.
1 is the client is thread-safe, 0 otherwise.
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)
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.
#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; }
0 if okay, 1 if an error occurred.
mysql_server_end()
void mysql_server_end(void)
This function must be called once in the program after all other MySQL functions. It shuts down the embedded server.
None.
mysql_query()
が成功を返した後、mysql_store_result()
が NULL
を返す時があるのは何故?
mysql_query()
の呼び出しが成功した後に
mysql_store_result()
が NULL
を返すことがあります。これが
起こったとき、次の条件のどれかの発生を意味します:
malloc()
が失敗した (例えば、結果セットが大き過ぎた場合)。
INSERT
, UPDATE
, DELETE
)。
ステートメントが空でない結果を提供するかどうかは
mysql_field_count()
の呼び出しによっていつでもチェックできます。
mysql_field_count()
が 0 を返す場合、結果は空で最後のクエリは値を
返さないステートメントです (例えば、INSERT
や DELETE
)。
mysql_field_count()
が非 0 値を返す場合、ステートメントは空でない
結果を提供します。
例はmysql_field_count()
関数の説明を参照してください。
mysql_error()
または mysql_errno()
を呼び出すことによって
エラーのテストもできます。
クエリによって返される結果セットに加えて、次の情報も得ることができます:
mysql_affected_rows()
は、INSERT
, UPDATE
または
DELETE
を行なった時の最後のクエリで、影響された行数を返します。
WHERE
節がない DELETE
が使用されて、テーブルが切り詰められ
た場合は例外です。これはとても速いです! この場合、
mysql_affected_rows()
は影響された行数を 0 と返します。
mysql_num_rows()
は結果セットのレコード数を返します。
mysql_store_result()
では、mysql_num_rows()
は
mysql_store_result()
が復帰したすぐ後に呼び出すことができます。
mysql_use_result()
では、mysql_num_rows()
は
mysql_fetch_row()
ですべてのレコードを取り出した後にだけ呼ぶ出すこ
とができます。
mysql_insert_id()
は、AUTO_INCREMENT
インデックスを持つテー
ブルに行を挿入した最後のクエリによって生成された ID を返します。
See section mysql_insert_id()
.
LOAD DATA INFILE...
, INSERT INTO ...
SELECT ...
, UPDATE
) は追加情報を返します。結果は
mysql_info()
で返されます。
返す文字列の形式については、mysql_info()
の説明を参照してください。
mysql_info()
は追加情報がない場
合は NULL
ポインタを返します。
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 でリンクする時、いくつかのシステム上では次のエラーになります:
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
) を含める必要があることを意味します。
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:
mysql_query()
と mysql_store_result()
の間
で、他のスレッドが同じ接続を使用しないことを確実にする必要があります。
mysql_store_result()
で取り出された別々の結果セッ
トにアクセスできます。
mysql_use_result
を使用する場合、結果セットがクローズされるまで、他
のスレッドが同じ接続上で何も尋ねないことを確実にする必要があります。
However, it really is best for threaded clients that share the same
connection to use mysql_use_result()
.
mysql_query()
and
mysql_store_result()
call combination. Once
mysql_store_result()
is ready, the lock can be released and other
threads may query the same connection.
pthread_mutex_lock()
and pthread_mutex_unlock()
to
establish and release a mutex lock.
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:
my_init()
at the start of your program if it calls
any other MySQL function before calling mysql_real_connect()
.
mysql_thread_init()
in the thread handler before calling
any MySQL function.
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.
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()
.
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.
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.
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' オプションファイル.
[server]
section. These will be read by
both MySQL versions.
[mysqld]
section.
[embedded]
section.
[ApplicationName_SERVER]
section.
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
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 Connector/C++ (or MySQL++
) is the official MySQL API for C++. More
information can be found at http://www.mysql.com/products/mysql++/.
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_init()
with NULL
as an argument, not a
pre-allocated MYSQL struct.
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.
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/.
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/.
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/
以下のサイトに、Ruby の MySQL インターフェースがあります。
www.tmtm.org とみたまさひろ氏の Web ページ
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!
The MySQL server creates the following threads:
process_alarm()
to force timeouts on connections
that have been idle too long.
mysqld
is compiled with -DUSE_ALARM_THREAD
, a dedicated
thread that handles alarms is created. This is only used on some systems where
there are problems with sigwait()
or if one wants to use the
thr_alarm()
code in ones application without a dedicated signal
handling thread.
--flush_time=#
option, a dedicated thread is created
to flush all tables at the given interval.
INSERT DELAYED
gets its
own thread.
--master-host
, a slave replication thread will be
started to read and apply updates from the master.
mysqladmin processlist
only shows the connection, INSERT DELAYED
,
and replication threads.
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.
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.
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:
mysql-test/t/*.test
;
terminated statements and is similar to the
input of mysql
command-line client. A statement by default is a query
to be sent to MySQL server, unless it is recognised as internal
command (eg. sleep
).
SELECT
, SHOW
,
EXPLAIN
, etc., must be preceded with @/path/to/result/file
. The
file must contain the expected results. An easy way to generate the result
file is to run mysqltest -r < t/test-case-name.test
from
mysql-test
directory, and then edit the generated result files, if
needed, to adjust them to the expected output. In that case, be very careful
about not adding or deleting any invisible characters - make sure to only
change the text and/or delete lines. If you have to insert a line, make sure
the fields are separated with a hard tab, and there is a hard tab at the end.
You may want to use od -c
to make sure your text editor has not messed
anything up during edit. We, of course, hope that you will never have to edit
the output of mysqltest -r
as you only have to do it when you find a
bug.
mysql-test/r
directory and name them test_name.result
. If the
test produces more than one result, you should use test_name.a.result
,
test_name.b.result
, etc.
--error error-number
. The error number can be
a list of possible error numbers separated with ','
.
source include/master-slave.inc;
. To switch between
master and slave, use connection master;
and connection slave;
.
If you need to do something on an alternate connection, you can do
connection master1;
for the master, and connection slave1;
for
the slave.
let $1=1000; while ($1) { # do your queries here dec $1; }
sleep
command. It supports fractions
of a second, so you can do sleep 1.3;
, for example, to sleep 1.3
seconds.
mysql-test/t/test_name-slave.opt
. For
the master, put them in mysql-test/t/test_name-master.opt
.
If your MySQL version doesn't pass the test suite you should do the following:
mysqlbug
script
so that we can get information about your system and MySQL
version. See section バグや問題を報告する方法.
mysql-test-run
, as well as
contents of all .reject
files in mysql-test/r
directory.
cd mysql-test mysql-test-run --local test-nameIf this fails, then you should configure MySQL with
--with-debug
and run mysql-test-run
with the
--debug
option. If this also fails send the trace file
`var/tmp/master.trace' to ftp://support.mysql.com/pub/mysql/secret
so that we can examine it. Please remember to also include a full
description of your system, the version of the mysqld binary and how you
compiled it.
mysql-test-run
with the --force
option to
see if there is any other test that fails.
Result length mismatch
or Result
content mismatch
it means that the output of the test didn't match
exactly the expected output. This could be a bug in MySQL or
that your mysqld version produces slight different results under some
circumstances.
Failed test results are put in a file with the same base name as the
result file with the .reject
extension. If your test case is
failing, you should do a diff on the two files. If you cannot see how
they are different, examine both with od -c
and also check their
lengths.
mysql-test/var/log
directory for hints of what went wrong.
mysql-test-run
with the --gdb
and/or --debug
options.
See section Creating Trace Files.
If you have not compiled MySQL for debugging you should probably
do that. Just specify the --with-debug
options to configure
!
See section MySQL ソースディストリビューションのインストール.
There are two ways to add new functions to MySQL:
CREATE FUNCTION
と DROP FUNCTION
ステー
トメントを使用して、動的に追加、削除されます。
See section CREATE FUNCTION/DROP FUNCTION
Syntax.
mysqld
サーバに統合され、恒久的に有効になります。
それぞれの方法には、有利な点と不利な点があります:
新しい関数を追加するためにどちらの方法を使用しても、ABS()
や
SOUNDEX()
のようなネイティブ関数と同じように使用することができま
す。
CREATE FUNCTION/DROP FUNCTION
SyntaxCREATE [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 type | C/C++ type |
STRING | char *
|
INTEGER | long long
|
REAL | double
|
xxx_init()
(オプション)
xxx()
の初期化関数。これは次のように使用されます:
XXX()
の引数の数のチェック
REAL
関数では) 小数部の最大桁数の指定
NULL
になり得るかどうかの指定
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)
xxx_add()
(required)
When using aggregate UDF functions MySQL works the following way:
xxx_init()
to let the aggregate function allocate the memory it
will need to store results.
GROUP BY
expression.
xxx_reset()
function.
xxx_add()
function.
xxx()
to get the result for the aggregate.
xxx_deinit()
to let the UDF free any memory it has allocated.
全ての関数はスレッド安全でなくてはいけません(メイン関数だけでなく、初期
化関数と終了関数も同様です)。これは変更されうるグローバル変数や静的変数
を割り当てることは許されないことを意味します! メモリが必要な場合は、
xxx_init()
で割り当て、xxx_deinit()
でそれを解放すべきです。
メイン関数は下に示すように宣言されるべきです。戻り値型と引数は、
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_null
を 1
に設定すべきです。デフォルト値は、引数のい
ずれかが maybe_null
として宣言された場合、1
です。
unsigned int decimals
1.34
, 1.345
, 1.3
が渡された場合、
デフォルトは 3 です。1.345
が 3 桁の小数部を持つためです。)
unsigned int max_length
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
を参照して、
メモリを使用または解放します。
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
要素を求める型に設定できます。これは MySQL に
xxx()
の各呼び出しにこれらの型を引数に強制するようにさせます。例
えば、最初の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
を参照できます:
STRING_RESULT
型の引数は、バイナリデータまたは任意の長さのデータ
の処理を許すため、文字列ポインタ+長さとして与えられます。文字列内容は
args->args[i]
として有効で、文字列長は args->lengths[i]
で
す。文字列は NULL 終端とみなすべきではありません。
INT_RESULT
型の引数について、args->args[i]
を
long long
値にキャストする必要があります:
long long int_val; int_val = *((long long*) args->args[i]);
REAL_RESULT
, you must cast
args->args[i]
to a double
value:
double real_val; real_val = *((double*) 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 long
と double
関
数については関数値です。文字列関数については、result
と
length
引数で文字列が返されます。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_null
を
1
に設定してください:
*is_null = 1;
To indicate an error return in the main function, set the error
parameter to 1
:
*error = 1;
xxx()
が任意の行について *error
に 1
を設定する場合、
関数値は現在の行についてと、その後の XXX()
が呼び出されるステート
メントによって処理される任意の行について NULL
です。(xxx()
は続く行については呼び出しさえされません。) 注意: 3.22.10 より
前の MySQL バージョンでは、*error
と *is_null
の
両方に設定すべきです:
*error = 1; *is_null = 1;
UDF を実装するファイルはサーバが動作するホスト上でコンパイルされインストー ルされないければなりません。この処理はサンプル UDF ファイル `udf_example.cc' について次に説明します。これは MySQL ソー ス配布に含まれています。このファイルは次の関数を含みます:
metaphon()
は文字列引数の metaphon 文字列を返します。これは時には
soundex 文字列ですが、さらに英語用に調整されています。
myfunc_double()
は引数の文字の ASCII 値の合計を引数の長さの合計で
割った値を返します。
myfunc_int()
は引数の長さの合計を返します。
sequence([const int])
returns an sequence starting from the given
number or 1 if no number has been given.
lookup()
はホスト名の IP 番号を返します。
reverse_lookup()
は IP 番号のホスト名を返します。この関数は文字列
"xxx.xxx.xxx.xxx"
または4つの数値とともに呼ばれます。
動的ロード可能ファイルは、次のような何らかのコマンドを使用して、共有オブ ジェクトファイルとしてコンパイルされるべきです:
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 FUNCTION
と DROP FUNCTION
ステートメントは
mysql
データベース内のシステムテーブル func
を更新します。
関数の名前、型、共有ライブラリ名はテーブルに保存されます。作成と破棄機能
のためには、mysql
データベースに INSERT
と
DELETE
権限を持つ必要があります。
既に生成してある関数を追加するために CREATE FUNCTION
を使用すべき
ではありません。関数の再インストールが必要な場合は、DROP FUNCTION
でそれを削除し、それから CREATE FUNCTION
で再インストールすべきで
す。例えば、関数の新しいバージョンの再コンパイルをした場合、
mysqld
が新しいバージョンを得るために、これを行なう必要があるでしょ
う。そうでなければ、サーバは古いバージョンの使用を継続します。
mysqld
を --skip-grant-tables
オプションで起動しなくても、
有効な関数はサーバの開始毎に再読み込みされます。この場合、UDF 初期化は飛
ばされ、UDF が無効になります。(有効な関数は CREATE FUNCTION
でロー
ドされているもので、DROP FUNCTION
で削除されていないものです。)
ネイティブ関数を追加するためのプロシジャを以下に示します。バイナリ配布に はネイティブ関数を追加できないことに注意してください。プロシジャは MySQL ソースコードの変更を必要とするためです。MySQL を ソース配布から自分でコンパイルする必要があります。また、MySQL の他のバージョンに移行する場合(例えば、新しいバージョンがリリースされた 時)、新しいバージョンでこのプロシジャを繰り返す必要があります。
新しいネイティブ MySQL 関数を追加するためには、次のステップに従っ てください:
sql_functions[]
配列内で関数名を定義している `lex.h' に1行
追加してください。
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
の
全ての出来事をチェックしてください。
Item_num_func
または Item_str_func
から継承するクラス
を宣言してください。
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()
.
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()
オブジェクト関数については、次のいくつかの追加検討事項があ
ります:
String *str
引数は、結果を保持するために使用される文字列バッファ
を提供します。
(For more information about the String
type,
take a look at the `sql_string.h' file.)
::str()
function should return the string that holds the result or
(char*) 0
if the result is NULL
.
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' によって定義されています。 クエリーの結果を調べ、 分析結果を返します:
max elements
(デフォルト値は256)とは、 一つの行において
analyse
プロシージャが認識する値の数(重複するものは除く)の
最大値です。 最大エレメント数は analyse
プロシージャがその行に
最適なデータ型が ENUM
型であるかどうかを判別するために使
われます。
max memory
(デフォルト値は8192)とは、 analyse
プロシージャが
1つの行に含まれる重複しない全ての値を探し出す際に、 1つの行に
割り当てるメモリーの最大サイズです。
SELECT ... FROM ... WHERE ... PROCEDURE ANALYSE([max elements,[max memory]])
今のところ、 この項目にはソースコードしかありません。
プロシージャに関する全ての情報は以下のファイルにありますのでご覧下さい:
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.
When you run into problems, the first thing you should do is to find out which program / piece of equipment is causing problems:
kbd_mode -a
on it.
top
, ps
, taskmanager
, or some similar program,
to check which program is taking all CPU or is locking the machine.
top
, df
, or a similar program if you are out of
memory, disk space, open files, or some other critical resource.
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:
top
. Let the
program run for a while, it may be evaluating something heavy.
mysqld
server that is causing problems, can you
do mysqladmin -u root ping
or mysqladmin -u root processlist
?
mysql
, for example)
when you try to connect to the MySQL server?
Does the client jam? Do you get any output from the program?
When sending a bug report, you should of follow the outlines described in this manual. See section 質問またはバグ報告.
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:
hostname.err file
. See section What To Do If MySQL Keeps Crashing.
mysqld
and the involved tables where
checked with CHECK TABLE
before you did the query, can you do
a test case for this? See section Making a Test Case When You Experience Table Corruption.
wait_timeout
variable in the MySQL server ?
mysqladmin variables
gives you the value of this
mysqld
with --log
and check if the
issued query appears in the log ?
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
エラーが起こりうる理由として:
mysqld
is not running.
mysqld
は
MIT-pthreads パッケージを使用します。See section MySQL がサポートする OS.
MIT-pthreads スレッドは UNIX ソケットをサポートしません。
そのため、サーバに接続する時は常にホスト名を与える必要があります。
サーバーへの接続をチェックするために、以下を試してください:
shell> mysqladmin -h `hostname` version
mysqld
が使用する UNIX ソケット を削除した (default `/tmp/mys
qld.sock').
だれかが cron
で MySQL ソケットを削除しているかもしれません。(例
えば `/tmp' ディレクトリから古いファイルを削除するようなクローンで)。
いつでも mysqladmin version
を実行して
mysqladmin
が使用するソケットが本当に存在するかをチェックできます。
この場合の修正は、`mysqld.sock' を消さないように cron
を変更するか、
またはソケットをどこか他の場所に移すことです。
See section MySQL ソケットファイル `/tmp/mysql.sock' を変更する方法、削除から守る方法.
--socket=/path/to/socket
オプションで mysqld
サーバーを起動できます。
もしサーバーのソケットのパスを変えた場合、MySQL クライアントに、新しい
パスを教えなければなりません。
See section MySQL ソケットファイル `/tmp/mysql.sock' を変更する方法、削除から守る方法.
mysqld
スレッドをキルしなければなりません。
たとえば、mysql_zap
スクリプトを、新しく MySQL サーバーを
起動する前に実行します。 See section What To Do If MySQL Keeps Crashing.
mysqld
so that it uses a directory that you can access.
もし Can't connect to MySQL server on some_hostname
エラーの場合,
何が問題なのかを見つけるために、以下の手順を踏みます:
telnet your-host-name tcp-ip-port-number
を実行すると
サーバーがアップするなら、 RETURN
を何回かたたいてください。
もしこのポートで MySQL サーバーが走っているなら、
走っている MySQL サーバーのバージョンナンバーを含んだ
レスポンスが得られるはずです。
もし telnet: Unable to connect to remote host: Connection refused
のような
エラーになったならば、このポートを使用しているサーバーはありません。
mysqld
デーモンに接続してみてください。
mysqldmin variables
で、mysqld
が使用するように指定された
TCP/IP ポート(変数 port
)をチェックしてください。
mysqld
サーバーが --skip-networking
オプションで起動されていないか
確認してください。
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.
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.
これは以下が起きたことを示します:
mysql_close()
を呼び出さなかった。
wait_timeout
か interactive_timeout
以上、いかなるリクエストもしない状態だった。
See section SHOW VARIABLES
.
See section SHOW VARIABLES
.
上記が起きたときには、サーバーは Aborted_clients
変数を増やします。
サーバー変数 Aborted_connects
は以下の時に増えます:
connect_timeout
秒以上
かかった時
See section SHOW VARIABLES
.
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.
max_allowed_packet
is too small or queries require more memory
than you have alloacated for mysqld
. See section Packet too large
エラー.
The table is full
エラーtmp_table_size
よりも大きくなっ
た時に発生します。この問題を回避するために、mysqld
のオプション
-O tmp_table_size=#
で増加、または、SQL オプション BIG_TABLES
(ver.4.0.3未満では SQL_BIG_TABLES
)
を問題のクエリの前に使用できます。
See section SET
構文.
You can also start mysqld
with the --big-tables
option.
This is exactly the same as using BIG_TABLES
for all queries.
In MySQL Version 3.23, in-memory temporary tables will automatically be
converted to a disk-based MyISAM
table after the table size gets
bigger than tmp_table_size
.
InnoDB
tables and run out of room in the
InnoDB
tablespace. In this case the solution is to extend the
InnoDB
tablespace.
ISAM
or MyISAM
tables on an OS that only
supports files of 2G in size and you have hit this limit for the data
or index file.
MyISAM
tables and the needed data or index size is
bigger than what MySQL has allocated pointers for. (If you don't specify
MAX_ROWS
to CREATE TABLE
MySQL will only allocate pointers
to hold 4G of data).
You can check the maximum data/index sizes by doing
SHOW TABLE STATUS FROM database LIKE 'table_name';or using
myisamchk -dv database/table_name
.
If this is the problem, you can fix it by doing something like:
ALTER TABLE table_name MAX_ROWS=1000000000 AVG_ROW_LENGTH=nnn;You only have to specify
AVG_ROW_LENGTH
for tables with BLOB/TEXT
fields as in this case MySQL can't optimise the space required based
only on the number of rows.
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
テーブル内に正しいパ
スワードを持たないエントリを見つけたことを意味します。
これは単にエントリが許可システムに拒否されているだけです。
起こり得ることとその解決:
mysqld
を、古いバージョン用の user
テーブルで走
らせているのかもしれません。
mysqlshow mysql user
を行うことによってこれを検証できます。
パスワードフィールドが 16 文字よりも短いかどうかをチェックしてください。
もしそうなら、これを修正するために、scripts/add_long_password
スクリプト
を実行してください。
mysqld
を --old
-protocol
オプションで起動していないのかもしれません。
新しいパスワードで user
テーブル内のユーザを更新するか、--old-protocol
付きで mysqld
を再起動してください。
user
テーブルのパスワードを、PASSWORD()
関数を使用しないで登録した
のかもしれません。
この場合、user
テーブルのパスワードを、mysql
を使用して更新します。
PASSWORD()
関数は以下のようにして使用します:
mysql> UPDATE user SET password=PASSWORD('your password') -> WHERE user='XXX';
Table 'xxx' doesn't exist
エラー
もし Table 'xxx' doesn't exist
か Can'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
これは次を意味します:
--with-charset=xxx
か
--with-extra-charsets=xxx
コンフィギャ・オプションで再コンパイルする必要があります。
See section 典型的な configure
オプション.
All standard MySQL binaries are compiled with
--with-extra-character-sets=complex
which will enable support for
all multi-byte character sets. See section データとソートに使用されるキャラクター・セット.
mysqld
に
組み込まれておらず、さらに 定義ファイルも特定の場所に存在しなかった場合。
この場合は以下のようにします:
configure
オプション.
--character-sets-dir=path-to-charset-dir
オプションを
持っています。
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
.
ulimit
と open-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_mysqld
は sh
で起動すべきです!
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
エラーで uncompress
や
compress
が定義されていないエラーを受けたならば、
-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:
LD_LIBRARY_PATH
環境変数に、`libmysqlclient.so' が存在する
ディレクトリを加える。
LD_LIBRARY
環境変数に、`libmysqlclient.so' が存在する
ディレクトリを加える。
ldconfig
.
他の解決方法は、あなたのプログラムを -static
フラグで static にリンクするか、
動的な MySQL ライブラリをリンク前に移動してから、リンクします。
二つ目の場合は、他のプログラムがそのダイナミックライブラリを使用していないか
注意してください!
mysqld
(MySQL サーバ) はいかなるユーザーでも開始し実行することが
できます。mysqld
をユーザ user_name
で実行するように変更するためには、
次を行なう必要があります:
mysqladmin shutdown
).
user_name
が読み書きできるように、データベースディレクトリとその中のファ
イルのパーミッションを変更します。(これは UNIX root
ユーザーで実行する必
要があるでしょう):
shell> chown -R user_name /path/to/mysql/datadirMySQL データベースディレクトリのディレクトリーやファイルがシンボリック リンクの場合、 これらリンクの先のディレクトリとファイルも変更します。
chown -R
はシンボリ
ックリンク先を変更してくれません。
user_name
でサーバを起動します。または MySQL 3.22 以降を
使用する場合は、mysqld
を UNIX root
で起動し
--user=user_name
スイッチを使用します。
mysqld
は、接続を許可する前に、与えられた UNIX user user_name
で実
行するように切り替えます。
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.
全ての 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:
mysqld
or the machine in the middle
of an update.
mysqld
that caused it to die in the
middle of an update.
mysqld
servers on the same data on a
system that doesn't support good filesystem locks (normally handled by
the lockd
daemon ) or if you are running
multiple servers with --skip-external-locking
mysqld
confused.
ALTER TABLE
on a
repaired copy of the table!
何かがクラッシュする理由を知るのは非常に難しいので、まず、他の人で動くも のがあなたでクラッシュするのかどうかをチェックしてください。次のことを行っ てください。
mysqld
デーモンを mysqladmin shutdown
で停止し, 全てのテーブルで
myisamchk --silent --force */*.MYI
を実行し、そして mysqld
デーモ
ンを再起動します. これはきれいな状態から開始することになります。
See section データベース管理.
mysqld --log
を使用し、ログの情報から特定のクエリがサーバーをキルしている
かを見つけ出してください。 95% のバグは特定のクエリに関係があります!
通常これは、 MySQL が再起動される前の、ログファイルの最後のクエリの一つ
です。 See section The General Query Log.
If you can repeatadly kill MySQL with one of the queries, even
when you have checked all tables just before doing the query, then you
have been able to locate the bug and should do a bug report for this!
See section バグや問題を報告する方法.
fork_test.pl
と fork2_test.pl
を試します。
configure
に
--with-debug
オプションか --with-debug=full
オプションを
つけて MySQL を再コンフィグし、
再コンパイルしてください。See section MySQL server のデバッグ.
--skip-external-locking
(ver. 4.0.3未満では --skip-locking
)
オプションを mysqld
に使用してください。いくつかのシステム上では、
lockd
ロックマネージャは正しく動きません;
--skip-external-locking
(ver. 4.0.3未満では --skip-locking
)
オプションは mysqld
に外部ロッキングを使用
しないように伝えます。(これは同じデータ上で2つの mysqld
サーバを
動すことができず、myisamchk
の使用時に注意しなければいけないことを
意味します。しかし、テストとしてこのオプションを試すことは指示できます。)
mysqld
が動いているのに応答がないように見えた時
mysqladmin -u root processlist
を試しましたか? 時々
mysqld
はそう思えても死んでいません。問題は全ての接続が使用中であ
ることか、いくつかの内部ロック問題があることです。mysqladmin
processlist
は通常これらの場合でも接続を作ることができ、現在の接続数と
それらの状態についての有用な情報を提供できます。
mysqladmin -i 5 status
や mysqladmin -i 5 -r status
をクエリ中に行ってください。
gdb
(または他のデバッガ) から mysqld
を開始してください。
See section Debugging mysqld under gdb.
mysqld
has crashed inside
gdb:
backtrace info local up info local up info localWith gdb you can also examine which threads exist with
info
threads
and switch to a specific thread with thread #
, where
#
is the thread id.
BLOB/TEXT
フィールドは使用しておらず、VARCHAR
フィールド
だけ使用しているなら、全ての VARCHAR
フィールドを
ALTER TABLE
で CHAR
に変更してみてください。
これは MySQL に固定長レコードを使用させるようにします。
固定長レコードは少し余分な領域をとりますが、よりエラーに対して
強くなります。
現在の可変長のレコードのコードは MySQL AB で少なくとも3年以上問題なく
使用されています。 しかし可変長のレコードはよりエラーの傾向があり、
上記の事柄を試すことは良いアイデアです!
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
ユーザーのパスワードを忘れた場合、
これを以下のようにして入れ直すことが可能です。
mysqld
サーバーを kill
で落とす。
(kill -9
ではありません!)
PID 番号は通常 MySQL データディレクトリに `.pid' ファイルに
書かれています:
shell> kill `cat /mysql-data-directory/hostname.pid`これを、 Unix
root
ユーザーか、MySQL サーバーを実行した
ユーザーで行います。
mysqld
を --skip-grant-tables
オプションで起動。
mysqladmin password
コマンドでパスワードを変更します。
shell> mysqladmin -u root password 'mynewpassword'
mysqld
and restart it normally,
or just load the privilege tables with:
shell> mysqladmin -h hostname flush-privileges
Alternatively, you can set the new password using the mysql
client:
mysqld
with the --skip-grant-tables
option as described above.
mysqld
server with:
shell> mysql -u root mysql
mysql
client:
mysql> UPDATE user SET Password=PASSWORD('mynewpassword') -> WHERE User='root'; mysql> FLUSH PRIVILEGES;
mysqld
and restart it normally.
ディスクフルが起きた場合 MySQL は次のことを行います:
この問題の場合、以下のようにします:
mysqladmin kill
をスレッドに送る
必要があります。スレッドは次に(1分)ディスクをチェックした時にアボートし
ます。
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 は一時ファイルを格納する場所として 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' が消されるな
ら、ほとんどの 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:
/etc/my.cnf
:
[client] socket=path-for-socket-file [mysqld] socket=path-for-socket-fileSee section `my.cnf' オプションファイル.
safe_mysqld
and most
clients with the --socket=path-for-socket-file
option.
MYSQL_UNIX_PORT
環境変数に設定することにより可能です。
configure
option
--with-unix-socket-path=path-for-socket-file
. See section 典型的な configure
オプション.
ソケットのテストをする場合、以下のようにします:
shell> mysqladmin --socket=/path/to/socket version
もし SELECT NOW()
があなたのローカル時間ではなく GMT を返すなら、
TZ
環境変数をローカルのTimezone に設定しなくてはなりません。
環境変数の設定は、サーバーを実行する前に行われなくてはなりません。
たとえば、safe_mysqld
や mysql.server
スクリプトで
行います。
See section Environment Variables.
デフォルトでは 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:
DATE
and DATETIME
columns.
DATE
column and you only know part
of the date.
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
が使用されます。
MySQL は現在 副問い合わせ は未サポート(バージョン4.1以上)です。また、
Version 4.0 以前では DELETE
構文で複数のテーブルを扱う事もサポートしていません。
したがって、2つのテーブルに関連するレコードを消すには、以下のようにして行います:
WHERE
条件を使用して、基本となるテーブルから行を SELECT
DELETE
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
節の引
数の数に無関係になります。
複雑なクエリーを行って、もしなんの結果も返さなければ、 そのクエリーの何が悪いかを見つけるため、以下の手続きを行います:
EXPLAIN
を使用してクエリーをテストし、明白な間違いを見つけます。
See section EXPLAIN
構文 (SELECT
についての情報を得る).
WHERE
節で使用されているフィールドだけを Select してみます
LIMIT 10
をクエリーで使用することは良くありません。
SELECT
してみます。
その場合、select するのは、上記で最後に取り除いたテーブルに対して行います。
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.
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 にテストを投稿してくだ
さい。
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 | +------+-------+-------+
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 *
やそのテーブル内での位置に依存してしまうような
取り出し方はけっしてするべきではありません。
というのは取り出されるデータの順序が常に保障されるものではないからです。
単にフィールドの情報が変更されただけでアプリケーションがエラーが発生する可能性を有しているのです。
にもかかわらずフィールドの順序を変えたい場合には次のような方法があります。
INSERT INTO new_table SELECT fields-in-new_table-order FROM old_table
.
を実行します。
old_table
をドロップするかリネームして下さい。
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 TABLES
を用いる処理における制限を以下に示します。
HEAP
, ISAM
, MyISAM
, MERGE
, InnoDB
の
いづれかの型のみを持つことが可能です。
mysql> SELECT * FROM temporary_table, temporary_table AS t2;
ALTER TABLE org_name RENAME new_name
は動作します。しかし、
TEMPORARY
テーブルにRENAME
を使用することはできません。
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.
libmysql.dll
, by bsilva@umesd.k12.or.us.
TmySQL
, a library to use MySQL with Delphi.
guile
that allows guile
to interact with SQL
databases. By Hal Roberts.
mydsn.dll
. mydsn should be used to build
and remove the DSN registry file for the MyODBC driver in Coldfusion
applications. By Miguel Angel Solrzano.
PROCEDURE
that can be loaded runtime.
mysqldump
output to a C header file. By Harry Brueckner,
brueckner@mail.respublica.de.
access_to_mysql.txt
, except that this
one is fully configurable, has better type conversion (including
detection of TIMESTAMP
fields), provides warnings and suggestions
while converting, quotes all special characters in text and
binary data, and so on. It will also convert to mSQL
v1 and v2,
and is free of charge for anyone. See
http://www.cynergi.net/exportsql/ for the latest version. By
Pedro Freire, support@cynergi.net. Note: Doesn't work with
Access2!
exportsql
. By Brian Andrews.
Note: Doesn't work with Access2!
exportsql.txt
. That is,
it imports data from MySQL into an Access database via
ODBC. This is very handy when combined with exportsql, because it lets you
use Access for all DB design and administration, and synchronise with
your actual MySQL server either way. Free of charge. See
http://www.netdive.com/freebies/importsql/ for any updates.
Created by Laurent Bossavit of NetDIVE.
Note: doesn't work with Access2!
mSQL
to MySQL. By alfred@sb.net
mysqldump
and pipe it to
the sqlconv.pl
script. The script will parse through the
mysqldump
output and will rearrange the fields so they can be
inserted into a new table. An example is when you want to create a new
table for a different site you are working on, but the table is just a
bit different (that is - fields in different order, etc.).
By Steve Shreeve.
This appendix lists the developers, contributors, and supporters that have helped to make MySQL what it is today.
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.
mysqld
).
mysys
library.
ISAM
and MyISAM
libraries (B-tree index file
handlers with index compression and different record formats).
HEAP
library. A memory table system with our superior full dynamic
hashing. In use since 1981 and published around 1984.
replace
program (take a look at it, it's COOL!).
MyODBC
, the ODBC driver for Windows95.
mSQL
tools like msqlperl
, DBD
/DBI
, and
DB2mysql
.
crash-me
and the foundation for the MySQL benchmarks.
texi2html
.
mysys
are left.
mysqlimport
PROCEDURE ANALYSE()
zlib
) in the client/server protocol.
INSERT
mysqldump
-e option
LOAD DATA LOCAL INFILE
SQL_CALC_FOUND_ROWS
SELECT
option
--max-user-connections=...
option
net_read
and net_write_timeout
GRANT
/REVOKE
and SHOW GRANTS FOR
UNION
in 4.0
DELETE
/UPDATE
MySQL++
C++ API and the MySQLGUI
client.
CASE
expression.
MD5()
and COALESCE()
functions.
RAID
support for MyISAM
tables.
SHOW CREATE TABLE
.
mysql-bench
libmysqld
, the embedded server.
MERGE
library.
ALTER TABLE ... ORDER BY ...
.
UPDATE ... ORDER BY ...
.
DELETE ... ORDER BY ...
.
MySQLCC
(MySQL Control Center
)
SHA1()
, AES_ENCRYPT()
and AES_DECRYPT()
functions.
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:
mysqlshutdown.exe
and
mysqlwatch.exe
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.)
WHERE column REGEXP regexp
.
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).
mysqldump
(previously msqldump
, but ported and enhanced by
Monty).
DBD
(Perl) interface.
mysqlhotcopy
.
_MB
character set macros and the ujis and sjis character sets.
mysqlaccess
, a program to show the access rights for a user.
xmysql
, a graphical X client for MySQL Server.
DBD::mysql
module.
FROM_UNIXTIME()
time formatting, ENCRYPT()
functions, and
bison
advisor.
Active mailing list member.
DBI
/DBD
. Have
been of great help with crash-me
and running benchmarks. Some new
date functions. The mysql_setpermissions
script.
DBI
/DBD
section in the manual.
CREATE FUNCTION
and
DROP FUNCTION
.
AGGREGATE
extension to UDF functions.
mysqlaccess
more secure.
pthread_mutex()
for OS/2.
MERGE
tables to handle INSERTS
. Active member
on the MySQL mailing lists.
DECIMAL
.
Author of mysql_tableinfo
.
mysqli
extension (API) for use with MySQL 4.1 and up.
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:
DBD-mysql
questions.
xmysql
-related questions and basic installation questions.
mysqlbug
.
DBD
, Linux, some SQL syntax questions.
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
.
mysqld
version.
--skip-show-database
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 が見つからない場合、そのバージョンはまだリリースされていません!
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:
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
SELECT * from t1 where t1.a=(SELECT t2.b FROM t2); SELECT * from t1 where (1,2,3) in (SELECT a,b,c from t2);
SELECT t1.a from t1, (select * from t2) t3 WHERE t1.a=t3.a;
INSERT ... ON DUPLICATE KEY UPDATE
syntax. This allows you to
UPDATE
an existing row if existed from before. (REPLACE
allows
you to overwrite an existing row, which is a different thing).
BTREE
index on HEAP
tables.
SHOW WARNINGS
; Shows warnings for the last command.
See section SHOW WARNINGS | ERRORS
.
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] table LIKE table
.
For a full list of changes, please refer to the changelog sections for each individual 4.1.x release.
localhost
.
REPAIR of MyISAM tables now uses less temporary disk space when
sorting char columns
.
DATE
/DATETIME
checking is now a bit stricter then before
to be able to automatically distinguish between date, datetime, and time
with microseconds. For example, dates of type YYYYMMDD HHMMDD
are not
supported anymore; One must either have separators between each
DATE
/TIME
part or not at all.
help
week
in the mysql
client and get help for the week()
function.
mysql_get_server_version()
.
record_in_range()
method to MERGE
tables to be
able to choose the right index when there are many to choose from.
RAND()
and user variables @var
.
ANSI_QUOTES
on the fly.
EXPLAIN SELECT
now can be killed. See section KILL
構文.
REPAIR TABLE
now can be killed. See section KILL
構文.
USE|IGNORE|FORCE INDEX
.
DROP TEMPORARY TABLE
now only drops temporary tables and doesn't
end transactions.
UNION
in derived tables
TIMESTAMP
is now returned as string of type 'YYYY-MM-DD HH:MM:DD'
.
CREATE TABLE foo (a int not null primary key)
the
PRIMARY
word is now optional.
CREATE TABLE
the attribute SERIAL
is now an alias for
BIGINT NOT NULL AUTO_INCREMENT UNIQUE
.
SELECT ... FROM DUAL
is an alias for SELECT ...
.
(To be compatible with some other databases).
CHAR
/VARCHAR
it's now
automatically changed to TEXT
or BLOB
; One will get a
warning in this case.
BLOB
/TEXT
types with the
syntax BLOB(length)
and TEXT(length)
. MySQL will
automatically change it to one of the internal BLOB
/TEXT
types.
CHAR BYTE
is an alias for CHAR BINARY
.
VARCHARACTER
is an alias for VARCHAR
.
integer MOD integer
and integer DIV integer
.
SERIAL DEFAULT VALUE
added as an alias for AUTO_INCREMENT
.
TRUE
and FALSE
added as alias for 1 and 0, respectively.
SELECT .. LIMIT 0
to return proper row count for
SQL_CALC_FOUND_ROWS
.
--tmpdir=dirname1:dirname2:dirname3
.
SELECT * from t1 where t1.a=(SELECT t2.b FROM t2)
.
SELECT a.col1, b.col2 FROM (SELECT MAX(col1) AS col1 FROM root_table) a, other_table b WHERE a.col1=b.col1;
BTREE
index on HEAP
tables.
CREATE TABLE
.
SHOW FULL COLUMNS FROM table_name
shows column comments.
ALTER DATABASE
.
SHOW [COUNT(*)] WARNINGS
shows warnings from the last command.
CREATE TABLE
... SELECT
by defining the column in the CREATE
part.
CREATE TABLE foo (a tinyint not null) SELECT b+1 AS 'a' FROM bar;
expr SOUNDS LIKE expr
same as SOUNDEX(expr)=SOUNDEX(expr)
.
VARIANCE(expr)
returns the variance of expr
CREATE
[TEMPORARY] TABLE [IF NOT EXISTS] table (LIKE table)
. The table can
be either normal or temporary.
--reconnect
and disable-reconnect
for the
mysql
client, to reconnect automatically or not if the
connection is lost.
Version 4.0 of the MySQL server includes many enhancements and new features:
InnoDB
table type is now included in the standard binaries,
adding transactions, row-level locking, and foreign keys.
See section InnoDB
テーブル (3.23.6以上).
MERGE
tables, now supporting INSERT
s and
AUTO_INCREMENT
.
See section MERGE
Tables (3.23.25以上).
UNION
syntax in SELECT
.
See section UNION
Syntax.
DELETE
statements.
See section DELETE
構文.
libmysqld
, the embedded server library.
See section libmysqld, the Embedded MySQL Server Library.
GRANT
privilege options for even tighter control and
security.
See section GRANT
と REVOKE
構文.
GRANT
system, particularly
useful for ISPs and other hosting providers.
See section Limiting user resources.
SET
構文.
For a full list of changes, please refer to the changelog sections for each individual 4.0.x release.
Functionality added or changed:
SHOW PROCESSLIST
will now include the client TCP port after the
hostname to make it easier to know from which client the request
originated.
Bugs fixed:
sort_buffer
variable.
INSERT INTO u SELECT ... FROM t
was written too late to the
binary log if t was very frequently updated during the execution of
this query. This could cause a problem with mysqlbinlog
or
replication. The master must be upgraded, not the slave. (bug #136).
WHERE
clause (bug #142).
multi-table updates
with InnoDB
tables. This bug occured as, in many cases, InnoDB
tables can not
be updated "on the fly", but offsets to the records have to be stored in
a temporary table.
server
RPM subpackage (bug #141).
.MYI
files.
BACKUP TABLE
to overwrite existing files.
UPDATE
s when user had all privileges
on the database where tables are located and there were any entries in
tables_priv
table, i.e. grant_option
was true.
TRUNCATE
any table in the same database.
LOCK TABLE
followed by DROP
TABLE
in the same thread. In this case one could still kill the thread
with KILL
.
LOAD DATA LOCAL INFILE
was not properly written to the binary
log (hence not properly replicated). (bug #82).
RAND()
entries were not read correctly by mysqlbinlog
from
the binary log which caused problems when restoring a table that was
inserted with RAND()
. INSERT INTO t1 VALUES(RAND())
. In
replication this worked ok.
SET SQL_LOG_BIN=0
was ignored for INSERT DELAYED
queries. (bug #104).
SHOW SLAVE STATUS
reported too old positions
(columns Relay_Master_Log_File
and Exec_master_log_pos
)
for the last executed statement from the master, if this statement
was the COMMIT
of a transaction. The master must be upgraded for that,
not the slave. (bug #52).
LOAD DATA INFILE
was not replicated by the slave if
replicate_*_table
was set on the slave. (bug #86).
RESET SLAVE
, the coordinates displayed by SHOW
SLAVE STATUS
looked un-reset (though they were, but only
internally). (bug #70).
LOAD DATA
.
ANALYZE
procedure with error.
CHAR(0)
columns that could cause wrong
results from the query.
AUTO_INCREMENT
column,
as a secondary column in a multi-column key (see section Using AUTO_INCREMENT
), when
data was inserted with INSERT ... SELECT
or LOAD DATA
into
an empty table.
STOP SLAVE
didn't stop the slave until the slave
got one new command from the master (this bug has been fixed for MySQL 4.0.11
by releasing updated 4.0.11a windows packages, which include this individual
fix on top of the 4.0.11 sources). (bug #69).
LOAD DATA
command
was issued with full table name specified, including database prefix.
pthread_attr_getstacksize
on
HP-UX 10.20 (Patch was also included in 4.0.11a sources).
bigint
test to not fail on some platforms (e.g. HP-UX and
Tru64) due to different return values of the atof()
function.
rpl_rotate_logs
test to not fail on certain platforms (e.g.
Mac OS X) due to a too long file name (changed slave-master-info.opt
to .slave-mi
).
Functionality added or changed:
NULL
is now sorted LAST if you use ORDER BY ... DESC
(as it was before before MySQL 4.0.2). This is change was required to
follow ANSI SQL 99. (The original change was because we thought that
ANSI SQL 99 required NULL to be always sorted at the same position, but
this was wrong).
START TRANSACTION
(ANSI SQL-99 syntax) as alias for BEGIN
.
This is recommended to use instead of BEGIN
to start a transaction.
OLD_PASSWORD()
as a synonym for PASSWORD()
.
ALL
in group functions.
INNER JOIN
and JOIN
syntaxes.
For example, SELECT * FROM t1 INNER JOIN t2
didn't work before.
Bugs fixed:
multi-table-delete
and InnoDB tables.
BLOB NOT NULL
columns used with IS NULL
.
CREATE TABLE (...)
AUTO_INCREMENT=#
.
MIN(key_column)
could in some cases return NULL
on a column
with NULL
and other values.
MIN(key_column)
and MAX(key_column)
could in some cases
return wrong values when used in OUTER JOIN
.
MIN(key_column)
and MAX(key_column)
could return wrong
values if one of the tables was empty.
INTERVAL
,
CASE
, FIELD
, CONCAT_WS
, ELT
and
MAKE_SET
functions.
--lower-case-table-names
(default on windows)
and you had tables or databases with mixed case on disk, then
executing SHOW TABLE STATUS
followed with DROP DATABASE
or DROP TABLE
could fail with Errcode 13
.
Functionality added or changed:
--log-error[=file_name]
to mysqld_safe
and
mysqld
. This option will force all error messages to be put in a
log file if the option --console
is not given. On Windows
--log-error
is enabled as default.
Warning:
to Note:
in the log files.
GROUP BY ... ORDER BY NULL
then result is not sorted.
SHOW VARIABLES
.
gethostbyaddr()
to resolve a hostname. You can fix
this for earlier MySQL versions by starting mysqld with
--thread-stack=192K
.
mysql_waitpid
to the binary distribution and the
MySQL-client
RPM subpackage (required for mysql-test-run
).
MySQL
RPM package to MySQL-server
. When
updating from an older version, MySQL-server.rpm
will simply replace
MySQL.rpm
.
replicate_wild_do_table=db.%
or
replicate_wild_ignore_table=db.%
, these rules will be applied to
CREATE/DROP DATABASE
too.
MASTER_POS_WAIT()
.
Bugs fixed:
rand()
distribution from the first call.
mysqld
to hang when a
table was opened with the HANDLER
command and then
dropped without being closed.
NULL
in an auto_increment
field and also
uses LAST_INSERT_ID()
.
ORDER BY constant_expression
.
mysqladmin --relative
.
show status
reported a strange number for
Open_files
and Open_streams
.
EXPLAIN
on empty table.
LEFT JOIN
that caused zero rows to be returned in
the case the WHERE
condition was evaluated as FALSE
after
reading const tables. (Unlikely condition).
FLUSH PRIVILEGES
didn't correctly flush table/column privileges
when mysql.tables_priv
is empty.
LOAD DATA INFILE
one a file
that updated and auto_increment field with NULL
or 0
. This
bug only affected MySQL 4.0 masters (not slaves or MySQL 3.23 masters).
NOTE: If you have a slave that has replicated a file with
generated auto_increment fields then the slave data is corrupted and you
should reinitialise the affected tables from the master.
NOT NULL
field to an
expression that returned NULL
.
str LIKE "%other_str%"
where str
or
other_str
contained characters >= 128.
LOAD DATA
and InnoDB failed
with table full
error the binary log was corrupted.
Functionality added or changed:
OPTIMIZE TABLE
will for MyISAM tables treat all NULL
values as different when calculating cardinality. This helps in
optimising joins between tables where one of the tables has a lot of
NULL
values in a indexed column:
SELECT * from t1,t2 where t1.a=t2.key_with_a_lot_of_null;
FORCE INDEX (key_list)
. This acts likes
USE INDEX (key_list)
but with the addition that a table scan is
assumed to be VERY expensive. One bad thing with this is that it makes
FORCE
a reserved word.
Bugs fixed:
LOAD DATA INFILE
statement that
caused log rotation.
Functionality added or changed:
max_packet_length
for libmysqld.c is now 1024*1024*1024.
max_allowed_packet
in a file ready by
mysql_options(MYSQL_READ_DEFAULT_FILE)
.
for clients.
ON UPDATE CASCADE
in
FOREIGN KEY
constraints. See the InnoDB section in the manual
for the InnoDB changelog.
Bugs fixed:
ALTER TABLE
with BDB tables.
QUOTE()
function.
GROUP BY
when used on BLOB column with NULL
values.
NULL
s in CASE
... WHEN ...
Functionality added or changed:
mysqlbug
now also reports the compiler version used for building
the binaries (if the compiler supports the option --version
).
Bugs fixed:
-DBIG_TABLES
on a 32 bit system.
mysql_drop_db()
didn't check permissions properly so anyone could
drop another users database. DROP DATABASE
is checked properly.
Functionality added or changed:
CHARACTER SET xxx
and CHARSET=xxx
table options (to be able to read table dumps from 4.1).
IFNULL(A,B)
is now set to be the
more 'general' of the types of A
and B
. (The order is
STRING
, REAL
or INTEGER
).
Qcache_lowmem_prunes
status variable (number of queries that were
deleted from cache because of low memory).
mysqlcheck
so it can deal with table names containing dashes.
SHOW VARIABLES
)
is no longer used when inserting small (less than 100) number of rows.
SELECT ... FROM merge_table WHERE indexed_column=constant_expr
.
LOCALTIME
and LOCALTIMESTAMP
as synonyms for
NOW()
.
CEIL
is now an alias for CEILING
.
CURRENT_USER()
function can be used to get a user@host
value as it was matched in the GRANT
system.
See section その他の関数.
CHECK
constraints to be compatible with ANSI SQL. This made
CHECK
a reserved word. (Checking of CHECK
constraints is
still not implemented).
CAST(... as CHAR)
.
LIMIT
syntax:
SELECT ... LIMIT # OFFSET #
mysql_change_user()
will now reset the connection to the state
of a fresh connect (Ie, ROLLBACK
any active transaction, close
all temporary tables, reset all user variables etc..)
Bugs fixed:
multi table updates
--lower-case-table-names
default on Mac OS X as the file system
is case sensitive.
AUTOCOMMIT=0
mode didn't rotate binary log.
SELECT
with joined tables with
ORDER BY
and LIMIT
clause when filesort had to be used.
In that case LIMIT
was applied to filesort of one of the tables,
although it could not be.
This fix solved problems with LEFT JOIN
too.
mysql_server_init()
now makes a copy of all arguments. This fixes
a problem when using the embedded server in C# program.
libmysqlclient
library
that allowed a malicious MySQL
server to crash the client
application.
mysql_change_user()
handling.
All users are strongly recommended to upgrade to version 4.0.6.
--chroot
command-line option of
mysqld
from working.
"..."
in boolean full-text search.
OPTIMIZE TABLE
to corrupt the table
under some rare circumstances.
LOCK TABLES
now works together with multi-table-update and
multi-table-delete.
--replicate-do=xxx
didn't work for UPDATE
commands.
(Bug introduced in 4.0.0)
REPLACE, AUTO_INCREMENT,
INSERT INTO ... SELECT ...
were fixed. See the InnoDB changelog
in the InnoDB section of the manual.
Functionality added or changed:
SHOW PROCESSLIST
command
WEEK()
so that one can get
week number according to the ISO 8601 specification.
(Old code should still work).
INSERT DELAYED
threads doesn't hang on Waiting for
INSERT
when one sends a SIGHUP
to mysqld.
AND
works according to SQL ANSI99 when it comes to
NULL
handling. In practice, this only affects queries where you
do something like WHERE ... NOT (NULL AND 0)
.
mysqld
will now resolve basedir
to its full path (with
realpath()
). This enables one to use relative symlinks to the
MySQL installation directory. This will however cause show
variables
to report different directories on systems where there is
a symbolic link in the path.
IGNORE INDEX
or USE INDEX
.
to be ignored.
--use-frm
option to mysqlcheck
. When used with
REPAIR
, it gets the table structure from the .frm
file, so the
table can be repaired even if the .MYI
header is corrupted.
MAX()
optimisation when used with JOIN
and
ON
expressions.
BETWEEN
behaviour changed (see section 比較演算子).
Now datetime_col BETWEEN timestamp AND timestamp
should work
as expected.
TEMPORARY
MERGE
tables now.
DELETE FROM myisam_table
now shrinks not only the `.MYD' file but
also the `.MYI' file.
--open-files-limit=#
option to mysqld_safe
it's now passed on to mysqld
.
EXPLAIN
from 'where used'
to
'Using where'
to make it more in line with other output.
safe_show_database
as it was not used anymore.
automake 1.5
and
libtool 1.4
.
--ignore-space
) back to the
original --ignore-spaces
in mysqlclient
. (Both syntaxes will
work).
UPDATE
privilege when using REPLACE
.
DROP TEMPORARY TABLE ...
, to be used to make
replication safer.
BEGIN/COMMIT
are now stored in the binary log on
COMMIT
and not stored if one does ROLLBACK
. This fixes
some problems with non-transactional temporary tables used inside
transactions.
SELECT * FROM (t2 LEFT JOIN t3 USING (a)), t1
worked, but
not SELECT * FROM t1, (t2 LEFT JOIN t3 USING (a))
. Note that
braces are simply removed, they do not change the way the join is
executed.
READ UNCOMMITTED
and READ COMMITTED
.
For a detailed InnoDB changelog, see section InnoDB Change History
in this manual.
Bugs fixed:
MAX()
optimisation when used with JOIN
and
ON
expressions.
INSERT DELAY
threads don't hang on Waiting for
INSERT
when one sends a SIGHUP
to mysqld
.
IGNORE INDEX
or USE INDEX
.
root
user in mysqld_safe
.
CHECK
or REPAIR
.
GROUP BY
queries that
didn't return any result.
mysqlshow
to work properly with wildcarded database names and
with database names that contain underscores.
MyISAM
crash when using dynamic-row tables with huge numbers of
packed fields.
BDB
transactions.
MATCH
relevance calculations.
IN BOOLEAN MODE
that made MATCH
to return incorrect relevance value in some complex joins.
MyISAM
key length to a value
slightly less that 500. It is exactly 500 now.
GROUP BY
on columns that may have a NULL
value
doesn't always use disk based temporary tables.
--des-key-file
argument to mysqld
is interpreted relative to the data directory if given as a relative pathname.
NULL
has to be MyISAM
. This was okay for 3.23, but not
needed in 4.*. This resulted in slowdown in many queries since 4.0.2.
ORDER BY ... LIMIT #
to not return all rows.
REPAIR TABLE
and myisamchk
to corrupt FULLTEXT
indexes.
mysql
grant table database. Now queries
in this database are not cached in the query cache.
mysqld_safe
for some shells.
MyISAM
MERGE
table has more than 2 ^ 32 rows and
MySQL was not compiled with -DBIG_TABLES
.
ORDER BY ... DESC
problems with InnoDB
tables.
GRANT
/REVOKE
failed if hostname was given in
non-matching case.
LOAD DATA INFILE
when setting a
timestamp
to a string value of '0'
.
myisamchk -R
mode.
mysqld
to crash on REVOKE
.
ORDER BY
when there is a constant in the SELECT
statement.
mysqld
couldn't open the
privilege tables.
SET PASSWORD FOR ...
closed the connection in case of errors (bug
from 4.0.3).
max_allowed_packet
in mysqld
to 1GB.
INSERT
on a table with an
AUTO_INCREMENT
key which was not in the first part of the key.
LOAD DATA INFILE
to not recreate index if the table had
rows from before.
AES_DECRYPT()
with incorrect arguments.
--skip-ssl
can now be used to disable SSL in the MySQL clients,
even if one is using other SSL options in an option file or previously
on the command line.
MATCH ... AGAINST( ... IN BOOLEAN MODE)
used with ORDER BY
.
LOCK TABLES
and CREATE TEMPORARY TABLES
privilege on
the database level. One must run the mysql_fix_privilege_tables
script on old installations to activate these.
SHOW TABLE ... STATUS
, compressed tables sometimes showed up as
dynamic
.
SELECT @@[global|session].var_name
didn't report
global | session
in the result column name.
FLUSH LOGS
in a circular
replication setup created an infinite number of binary log files.
Now a rotate-binary-log
command in the binary log will not cause slaves
to rotate logs.
STOP EVENT
from binary log when doing FLUSH LOGS
.
SHOW NEW MASTER FOR SLAVE
as this needs to be
completely changed in 4.1.
UNIQUE
key) appeared in ORDER BY
part of SELECT DISTINCT
.
--log-binary=a.b.c
now properly strips off .b.c
.
FLUSH LOGS
removed numerical extension for all future update logs.
GRANT ... REQUIRE
didn't store the SSL information in the
mysql.user
table if SSL was not enabled in the server.
GRANT ... REQUIRE NONE
can now be used to remove SSL information.
AND
is now optional between REQUIRE
options.
REQUIRE
option was not properly saved, which could cause strange
output in SHOW GRANTS
.
mysqld --help
reports correct values for --datadir
and --bind-address
.
mysqld
was started.
SHOW VARIABLES
on some 64 bit systems
(like Solaris sparc).
--set-variable
syntax didn't work for
those options that didn't have a valid variable in my_option struct.
This affected at least default-table-type
option.
REPAIR TABLE
and
myisamchk --recover
to fail on tables with duplicates in a unique
key.
CREATE TABLE table_name
SELECT expression(),...
SELECT * FROM table-list GROUP BY ...
and
SELECT DISTINCT * FROM ...
.
--slow-log
when logging an administrator command
(like FLUSH TABLES
).
OPTIMIZE
of locked and modified table,
reported table corruption.
--skip-
,
--enable-
). --skip-external-locking
didn't work and the bug
may have affected other similar options.
tee
option.
SELECT ... FROM many_tables .. ORDER BY key limit #
SHOW OPEN TABLES
when a user didn't have access
permissions to one of the opened tables.
configure ... --localstatedir=...
.
mysql.server
script.
mysqladmin shutdown
when pid file was modified
while mysqladmin
was still waiting for the previous one to
disappear. This could happen during a very quick restart and caused
mysqladmin
to hang until shutdown_timeout
seconds had
passed.
AUTO_INCREMENT
columns to
NULL
in LOAD DATA INFILE
.
SHOW MASTER STATUS
now returns an empty set if binary log is not
enabled.
SHOW SLAVE STATUS
now returns an empty set if slave is not initialised.
SELECT DISTINCT ... FROM many_tables ORDER BY
not-used-column
.
BIGINT
s and quoted strings.
QUOTE()
function that performs SQL quoting to produce values
that can be used as data values in queries.
DELAY_KEY_WRITE
to an enum to allow one set
DELAY_KEY_WRITE
for all tables without taking down the server.
IF(condition,column,NULL)
so that it returns
the value of the column type.
safe_mysqld
a symlink to mysqld_safe
in binary distribution.
user.db
table.
CREATE TABLE ... SELECT function()
.
mysqld
now has the option --temp-pool
enabled by default as this
gives better performance with some operating systems.
CHANGE MASTER TO
if the slave thread died very quickly.
--code-file
option is specified, the server calls
setrlimit()
to set the maximum allowed core file size to unlimited,
so core files can be generated.
--count=N
(-c
) option to mysqladmin
, to make the
program do only N
iterations. To be used with --sleep
(-i
).
Useful in scripts.
UPDATE
: when updating a table,
do_select()
became confused about reading records from a cache.
UPDATE
when several fields were referenced
from a single table
REVOKE
that caused user resources to be randomly set.
GRANT
for the new CREATE TEMPORARY TABLE
privilege.
DELETE
when tables are re-ordered in the
table initialisation method and ref_lengths are of different sizes.
SELECT DISTINCT
with large tables.
DEFAULT
with INSERT
statement.
myisam_max_sort_file_size
and
myisam_max_extra_sort_file_size
are now given in bytes, not megabytes.
MyISAM
/ISAM
files is now turned
off by default. One can turn this on with --external-locking
.
(For most users this is never needed).
INSERT ... SET db_name.table_name.colname=''
.
DROP DATABASE
SET [GLOBAL | SESSION]
syntax to change thread-specific and global
server variables at runtime.
slave_compressed_protocol
.
query_cache_startup_type
to query_cache_type
,
myisam_bulk_insert_tree_size
to bulk_insert_buffer_size
,
record_buffer
to read_buffer_size
and
record_rnd_buffer
to record_rnd_buffer_size
.
--skip-locking
to --skip-external-locking
.
query_buffer_size
.
mysql
client
non-functional.
AUTO_INCREMENT
support to MERGE
tables.
LOG()
function to accept an optional arbitrary base
parameter.
See section 数学関数.
LOG2()
function (useful for finding out how many bits
a number would require for storage).
LN()
natural logarithm function for compatibility with
other databases. It is synonymous with LOG(X)
.
NULL
handling for default values in DESCRIBE
table_name
.
truncate()
to round up negative values to the nearest integer.
--chroot=path
option to execute chroot()
immediately
after all options have been parsed.
lower_case_table_names
now also affects database names.
XOR
operator (logical and bitwise XOR
) with ^
as a synonym for bitwise XOR
.
IS_FREE_LOCK("lock_name")
.
Based on code contributed by Hartmut Holzgraefe hartmut@six.de.
mysql_ssl_clear()
from C API, as it was not needed.
DECIMAL
and NUMERIC
types can now read exponential numbers.
SHA1()
function to calculate 160 bit hash value as described
in RFC 3174 (Secure Hash Algorithm). This function can be considered a
cryptographically more secure equivalent of MD5()
.
See section その他の関数.
AES_ENCRYPT()
and AES_DECRYPT()
functions to perform
encryption according to AES standard (Rijndael).
See section その他の関数.
--single-transaction
option to mysqldump
, allowing a
consistent dump of InnoDB
tables.
See section mysqldump
, データベースとテーブルから、構造とデータをダンプ.
innodb_log_group_home_dir
in SHOW VARIABLES
.
FULLTEXT
index is present and no tables are used.
CREATE TEMPORARY TABLES
, EXECUTE
,
LOCK TABLES
, REPLICATION CLIENT
, REPLICATION SLAVE
,
SHOW DATABASES
and SUPER
. To use these, you must have
run the mysql_fix_privilege_tables
script after upgrading.
TRUNCATE TABLE
; This fixes some core
dump/hangup problems when using TRUNCATE TABLE
.
DELETE
when optimiser uses only indices.
ALTER TABLE table_name RENAME new_table_name
is as fast
as RENAME TABLE
.
GROUP BY
with two or more fields, where at least one
field can contain NULL
values.
Turbo Boyer-Moore
algorithm to speed up LIKE "%keyword%"
searches.
DROP DATABASE
with symlink.
REPAIR ... USE_FRM
.
EXPLAIN
with LIMIT offset != 0
.
"..."
in boolean full-text search.
*
in boolean full-text search.
+word*
s in the query).
MATCH
expression that did not use an index appeared twice.
mysqldump
.
ft_min_word_len
characters.
--without-query-cache
.
INET_NTOA()
now returns NULL
if you give it an argument that
is too large (greater than the value corresponding to 255.255.255.255
).
SQL_CALC_FOUND_ROWS
to work with UNION
s. It will work only
if the first SELECT
has this option and if there is global LIMIT
for the entire statement. For the moment, this requires using parentheses for
individual SELECT
queries within the statement.
SQL_CALC_FOUND_ROWS
and LIMIT
.
CREATE TABLE ...(... VARCHAR(0))
.
SIGINT
and SIGQUIT
problems in `mysql.cc' on Linux
with some glibc
versions.
net_store_length()
linked in the CONVERT::store()
method.
DOUBLE
and FLOAT
columns now honor the UNSIGNED
flag
on storage.
InnoDB
now retains foreign key constraints through ALTER TABLE
and CREATE/DROP INDEX
.
InnoDB
now allows foreign key constraints to be added through the
ALTER TABLE
syntax.
InnoDB
tables can now be set to automatically grow in size (autoextend).
--ignore-lines=n
option to mysqlimport
. This has the
same effect as the IGNORE n LINES
clause for LOAD DATA
.
UNION
with last offset being transposed to total result
set.
REPAIR ... USE_FRM
added.
DEFAULT_SELECT_LIMIT
is always imposed on UNION
result set.
SELECT
options can appear only in the first
SELECT
.
LIMIT
with UNION
, where last select is in
the braces.
UNION
operations.
SELECT
with an empty
HEAP
table.
ORDER BY column DESC
now sorts NULL
values first.
(In other words, NULL
values sort first in all cases, whether or
not DESC
is specified.). This is changed back in 4.0.10.
WHERE key_name='constant' ORDER BY key_name DESC
.
SELECT DISTINCT ... ORDER BY DESC
optimisation.
... HAVING 'GROUP_FUNCTION'(xxx) IS [NOT] NULL
.
--user=#
option for mysqld
to be specified
as a numeric user ID.
SQL_CALC_ROWS
returned an incorrect value when used
with one table and ORDER BY
and with InnoDB
tables.
SELECT 0 LIMIT 0
doesn't hang thread.
USE/IGNORE INDEX
when using
many keys with the same start column.
BerkeleyDB
and InnoDB
tables when
we can use an index that covers the whole row.
InnoDB
sort-buffer handling to take less memory.
DELETE
and InnoDB
tables.
TRUNCATE
and InnoDB
tables that produced the
error Can't execute the given command because you have active locked
tables or an active transaction
.
NO_UNSIGNED_SUBTRACTION
to the set of flags that may be
specified with the --sql-mode
option for mysqld
. It disables
unsigned arithmetic rules when it comes to subtraction. (This will make
MySQL 4.0 behave more closely to 3.23 with UNSIGNED
columns).
|
, <<
, ...) is now of
type unsigned integer
.
nan
values in MyISAM
to make it possible to
repair tables with nan
in float or double columns.
myisamchk
where it didn't correctly update number of
``parts'' in the MyISAM
index file.
autoconf
2.52 (from autoconf
2.13).
const
tables. This fix also
improves performance a bit when referring to another table from a
const
table.
UPDATE
statement.
DELETE
.
SELECT CONCAT(argument_list) ... GROUP BY 1
.
INSERT ... SELECT
did a full rollback in case of an error. Fixed
so that we only roll back the last statement in the current transaction.
NULL
.
BIT_LENGTH()
function.
GROUP BY BINARY column
.
NULL
keys in HEAP
tables.
ORDER BY
in queries of type:
SELECT * FROM t WHERE key_part1=1 ORDER BY key_part1 DESC,key_part2 DESC
FLUSH QUERY CACHE
.
CAST()
and CONVERT()
functions. The CAST
and
CONVERT
functions are nearly identical and mainly useful when you
want to create a column with a specific type in a CREATE ... SELECT
statement. For more information, read section Cast Functions.
CREATE ... SELECT
on DATE
and TIME
functions now
create columns of the expected type.
Null
and Index_type
to SHOW INDEX
output.
--no-beep
and --prompt
options to mysql
command-line client.
GRANT ... WITH MAX_QUERIES_PER_HOUR N1 MAX_UPDATES_PER_HOUR N2 MAX_CONNECTIONS_PER_HOUR N3;See section Limiting user resources.
mysql_secure_installation
to the `scripts/' directory.
HANDLER
was used with some unsupported table type.
mysqldump
now puts ALTER TABLE tbl_name DISABLE KEYS
and
ALTER TABLE tbl_name ENABLE KEYS
in the sql dump.
mysql_fix_extensions
script.
LOAD DATA FROM MASTER
on OSF/1.
DES_ENCRYPT()
and DES_DECRYPT()
functions.
FLUSH DES_KEY_FILE
statement.
--des-key-file
option to mysqld
.
HEX(string)
now returns the characters in string
converted to
hexadecimal.
GRANT
when using lower_case_table_names=1
.
SELECT ... IN SHARE MODE
to
SELECT ... LOCK IN SHARE MODE
(as in MySQL 3.23).
SELECT
queries.
MATCH ... AGAINST(... IN BOOLEAN MODE)
can now work
without FULLTEXT
index.
FULLTEXT
indexes.
DELETE ... WHERE ... MATCH ...
.
MATCH ... AGAINST(... IN BOOLEAN MODE)
.
Note: you must rebuild your tables with
ALTER TABLE tablename TYPE=MyISAM
to be
able to use boolean full-text search.
LOCATE()
and INSTR()
are now case-sensitive if either
argument is a binary string.
RAND()
initialisation so that RAND(N)
and
RAND(N+1)
are more distinct.
UPDATE ... ORDER BY
.
INSERT INTO ... SELECT
to stop on errors by default.
DATA DIRECTORY
and INDEX DIRECTORY
directives on Windows.
MODIFY
and CHANGE
in ALTER TABLE
to accept
the FIRST
and AFTER
keywords.
ORDER BY
on a whole InnoDB
table.
--xml
option to mysql
for producing XML output.
ft_min_word_len
, ft_max_word_len
, and
ft_max_word_len_for_sort
.
libmysqld
, the embedded MySQL server
library. Also added example programs (a mysql
client and
mysqltest
test program) which use libmysqld
.
my_thread_init()
and my_thread_end()
from `mysql_com.h', and added mysql_thread_init()
and
mysql_thread_end()
to `mysql.h'.
MyISAM
to be able to handle these.
BIGINT
constants now work. MIN()
and MAX()
now handle signed and unsigned BIGINT
numbers correctly.
latin1_de
which provides correct German sorting.
STRCMP()
now uses the current character set when doing comparisons,
which means that the default comparison behaviour now is case-insensitive.
TRUNCATE TABLE
and DELETE FROM tbl_name
are now separate
functions. One bonus is that DELETE FROM tbl_name
now returns
the number of deleted rows, rather than zero.
DROP DATABASE
now executes a DROP TABLE
on all tables in
the database, which fixes a problem with InnoDB
tables.
UNION
.
DELETE
operations.
HANDLER
interface to MyISAM
tables.
INSERT
on MERGE
tables. Patch from
Benjamin Pflugmann.
WEEK(#,0)
to match the calendar in the USA.
COUNT(DISTINCT)
is about 30% faster.
IS NULL
, ISNULL()
and some other internal primitives.
myisam_bulk_insert_tree_size
variable.
CHAR
/VARCHAR
) keys is now much faster.
SELECT DISTINCT * from tbl_name ORDER by key_part1 LIMIT #
.
SHOW CREATE TABLE
now shows all table attributes.
ORDER BY ... DESC
can now use keys.
LOAD DATA FROM MASTER
``automatically'' sets up a slave.
safe_mysqld
to mysqld_safe
to make this name more
in line with other MySQL scripts/commands.
MyISAM
tables. Symlink handling is
now enabled by default for Windows.
SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
. This makes it
possible to know how many rows a query would have returned
without a LIMIT
clause.
SHOW OPEN TABLES
.
SELECT expression LIMIT ...
.
IDENTITY
as a synonym for AUTO_INCREMENT
(like Sybase).
ORDER BY
syntax to UPDATE
and DELETE
.
SHOW INDEXES
is now a synonym for SHOW INDEX
.
ALTER TABLE tbl_name DISABLE KEYS
and
ALTER TABLE tbl_name ENABLE KEYS
commands.
IN
as a synonym for FROM
in SHOW
commands.
FULLTEXT
indexes.
REPAIR TABLE
, ALTER TABLE
, and OPTIMIZE TABLE
for tables with FULLTEXT
indexes are now up to 100 times faster.
X'hexadecimal-number'
.
FLUSH TABLES WITH READ LOCK
.
DATETIME = constant
in WHERE
optimisation.
--master-data
and --no-autocommit
options to
mysqldump
. (Thanks to Brian Aker for this.)
mysql_explain_log.sh
to distribution.
(Thanks to mobile.de).
The 3.23 release has several major features that are not present in previous versions. We have added three new table types:
MyISAM
InnoDB
BerkeleyDB
or BDB
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.
PROCEDURE ANALYSE()
to report DATE
instead of
NEWDATE
.
PROCEDURE ANALYSE(#)
to restrict number of values in
enum to #
also for string values.
sort_buffer
variable.
GRANT UPDATE
on column level.
HAVING
with GROUP BY
.
WHERE
clause (Bug #142).
.MYI
files.
--user
option specified on the command line. (Normally this comes from
`/etc/my.cnf')
BACKUP TABLE
to overwrite existing files.
LOCK TABLE
and
another thread did a DROP TABLE
. In this case one could do
a KILL
on one of the threads to resolve the deadlock.
LOAD DATA INFILE
was not replicated by slave if
replicate_*_table
was set on the slave.
CHAR(0)
columns that could cause wrong
results from the query.
SHOW VARIABLES
on 64-bit platforms. The bug was
caused by wrong declaration of variable server_id
.
SHOW TABLE STATUS
now reports that it can
contain NULL
values (which is the case for a crashed `.frm' file).
rpl_rotate_logs
test to not fail on certain platforms (e.g.
Mac OS X) due to a too long file name (changed slave-master-info.opt
to .slave-mi
).
BLOB NOT NULL
columns used with IS NULL
.
MAX()
optimization in MERGE
tables.
RAND()
initialization for new connections.
poll()
system call, which resulted in timeout the value specified as
it was executed in both select()
and poll()
.
SELECT * FROM table WHERE datetime1 IS NULL OR datetime2 IS NULL
.
INTERVAL
,
CASE
, FIELD
, CONCAT_WS
, ELT
and
MAKE_SET
functions.
--lower-case-table-names
(default on windows)
and you had tables or databases with mixed case on disk, then
executing SHOW TABLE STATUS
followed with DROP DATABASE
or DROP TABLE
could fail with Errcode 13
.
NULL
in an auto_increment
field and also
uses LAST_INSERT_ID()
.
mysqladmin --relative
.
show status
reported a strange number for
Open_files
and Open_streams
.
free
'd pointer bug in mysql_change_user()
handling, that enabled a specially hacked version of MySQL client
to crash mysqld
. Note, that one needs to login to the server
by using a valid user account to be able to exploit this bug.
--slow-log
when logging an administrator command
(like FLUSH TABLES
).
GROUP BY
when used on BLOB column with NULL
values.
NULL
s in CASE ... WHEN ...
.
--chroot
(see section Changes in release 3.23.54 (2002-12-05))
is reverted. Unfortunately, there is no way to make it to work, without
introducing backward-incompatible changes in `my.cnf'.
Those who need --chroot
functionality, should upgrade to MySQL 4.0.
(The fix in the 4.0 branch did not break backward-compatibility).
--lower-case-table-names
default on Mac OS X as the file system
is case insensitive.
NOHUP_NICENESS
testing.
AUTOCOMMIT=0
mode didn't rotate binary log.
scripts/make_binary_distribution
that resulted in
a remaining @HOSTNAME@
variable instead of replacing it with the
correct path to the hostname
binary.
SHOW PROCESSLIST
to core
dump in pthread_mutex_unlock() if a new thread was connecting.
SLAVE STOP
if the thread executing the query has locked
tables. This removes a possible deadlock situation.
mysqld
with a specially crafted packet.
free
'd pointer) when altering a
temporary table.
libmysqlclient
library
that allowed malicious MySQL server to crash the client
application.
mysql_change_user()
handling.
All users are strongly recommended to upgrade to the version 3.23.54.
--chroot
command-line option of mysqld
from working.
OPTIMIZE TABLE
to corrupt the table
under some rare circumstances.
mysqlcheck
so it can deal with table names containing dashes.
NULL
field with <=> NULL
.
IGNORE INDEX
and USE INDEX
sometimes
to be ignored.
GROUP BY
queries that
didn't return any result.
MATCH ... AGAINST () >=0
was treated as if it was
>
.
SHOW PROCESSLIST
when running with an
active slave (unlikely timing bug).
TEMPORARY
MERGE
tables now.
--core-file
works on Linux (at least on kernel 2.4.18).
BDB
and ALTER TABLE
.
GROUP BY
... ORDER BY
queries. Symptom was that mysqld
died in function
send_fields
.
BLOB
values in internal
temporary tables used for some (unlikely) GROUP BY
queries.
WHERE column_name = key_column_name
was calculated as true
for NULL
values.
LEFT JOIN ... WHERE key_column=NULL
.
MyISAM
crash when using dynamic-row tables with huge numbers of
packed fields.
automake 1.5
and
libtool 1.4
.
SHOW INNODB STATUS
was used and skip-innodb
was defined.
LOCK TABLES
on windows when one connects to a
database that contains upper case letters.
--skip-show-databases
doesn't reset the --port
option.
safe_mysqld
for some shells.
FLUSH STATUS
doesn't reset Delayed_insert_threads
.
BINARY
cast on a NULL
value.
GRANT
at the same time a new
user logged in or did a USE DATABASE
.
ALTER TABLE
and RENAME TABLE
when running with
-O lower_case_table_names=1
(typically on windows) when giving the
table name in uppercase.
-O lower_case_table_names=1
also converts database
names to lower case.
SELECT ... ORDER BY ... LIMIT
.
AND/OR
to report that they can return NULL. This fixes a
bug in GROUP BY
on AND/OR
expressions that return
NULL
.
OPTIMIZE
of locked and modified MyISAM table,
reported table corruption.
BDB
-related ALTER TABLE
bug with dropping a column
and shutting down immediately thereafter.
configure ... --localstatedir=...
.
UNSIGNED BIGINT
on AIX (again).
BEGIN
/COMMIT
around transaction in the binary log.
This makes replication honour transactions.
user.db
table.
RND()
to make it less predicatable.
GROUP BY
on result with expression that created a
BLOB
field.
GROUP BY
on columns that have NULL
values.
To solve this we now create an MyISAM
temporary table when doing a
GROUP BY
on a possible NULL
item.
From MySQL 4.0.5 we can use in memory HEAP
tables for this case.
SLAVE START
, SLAVE STOP
and automatic repair
of MyISAM tables that could cause table cache to be corrupted.
OPTIMIZE TABLE
and REPAIR TABLE
.
UNIQUE()
key where first part could contain NULL values.
MERGE
tables and MAX()
function.
ALTER TABLE
with BDB
tables.
LOAD DATA INFILE
to binary log with no
active database.
DROP DATABASE
on a
database with InnoDB
tables.
mysql_info()
returns 0 for 'Duplicates' when using
INSERT DELAYED IGNORE
.
-DHAVE_BROKEN_REALPATH
to the Mac OS X (darwin) compile
options in `configure.in' to fix a failure under high load.
mysqldump
XML output.
ENUM
values. (This fixed a problem with
SHOW CREATE TABLE
.)
CONCAT_WS()
that cut the result.
Com_show_master_stat
to
Com_show_master_status
and Com_show_slave_stat
to
Com_show_slave_status
.
gethostbyname()
to make the client library
thread-safe even if gethostbyname_r
doesn't exist.
GRANT
.
DROP DATABASE
with symlinked directory.
DATETIME
and value outside
DATETIME
range.
BDB
doc files from the source tree, as they're not
needed (MySQL covers BDB
in its own documentation).
glibc
2.2 (needed for
make dist
).
FLOAT(X+1,X)
is not converted to FLOAT(X+2,X)
.
(This also affected DECIMAL
, DOUBLE
and REAL
types)
IF()
is case in-sensitive if the second and
third arguments are case sensitive.
gethostbyname_r
.
'+11111'
for
DECIMAL(5,0) UNSIGNED
columns, we will just drop the sign.
ISNULL(expression_which_cannot_be_null)
and
ISNULL(constant_expression)
.
glibc
library that we used with the 3.23.50
Linux-x86 binaries.
<row>
tags for mysqldump
XML output.
crash-me
and gcc
3.0.4.
@@unknown_variable
doesn't hang server.
@@VERSION
as a synonym for VERSION()
.
SHOW VARIABLES LIKE 'xxx'
is now case-insensitive.
GET_LOCK()
on HP-UX with DCE threads.
SIGINT
and SIGQUIT
problems in mysql
.
InnoDB
now retains foreign key constraints through ALTER TABLE
and CREATE/DROP INDEX
.
InnoDB
now allows foreign key constraints to be added through the
ALTER TABLE
syntax.
InnoDB
tables can now be set to automatically grow in size (autoextend).
gcc
3.0.4, which
should make them a bit faster.
--enable-named-pipe
.
WHERE key_column = 'J' or key_column='j'
.
--log-bin
with LOAD DATA
INFILE
without an active database.
RENAME TABLE
when used with
lower_case_table_names=1
(default on Windows).
DROP TABLE
on a table
that was in use by a thread that also used queries on only temporary tables.
SHOW CREATE TABLE
and PRIMARY KEY
when using
32 indexes.
SET PASSWORD
for the anonymous user.
mysql_options()
.
--enable-local-infile
.
bison
.
DATE_FORMAT()
returned empty string when used
with GROUP BY
.
mysqldump --disable-keys
to work.
NULL
.
LOAD DATA LOCAL INFILE
more secure.
glibc
library,
which has serious problems under high load and RedHat 7.2. The 3.23.49 binary
release doesn't have this problem.
--xml
option to mysqldump
for producing XML output.
autoconf
2.52 (from autoconf
2.13)
const
tables.
InnoDB
.
InnoDB
variables were always shown in SHOW VARIABLES
as
OFF
on high-byte-first systems (like SPARC).
InnoDB
table and another
thread doing an ALTER TABLE
on the same table. Before that,
mysqld
could crash with an assertion failure in `row0row.c',
line 474.
InnoDB
SQL optimiser to favor index searches more often
over table scans.
InnoDB
tables when several large
SELECT
queries are run concurrently on a multiprocessor Linux
computer. Large CPU-bound SELECT
queries will now also generally
run faster on all platforms.
InnoDB
now prints after crash recovery the
latest MySQL binlog name and the offset InnoDB
was able to recover
to. This is useful, for example, when resynchronising a master and a
slave database in replication.
InnoDB
tables.
InnoDB
tablespace.
InnoDB
now prevents a FOREIGN KEY
declaration where the
signedness is not the same in the referencing and referenced integer columns.
SHOW CREATE TABLE
or SHOW TABLE STATUS
could cause
memory corruption and make mysqld
crash. Especially at risk was
mysqldump
, because it frequently calls SHOW CREATE TABLE
.
AUTO_INCREMENT
column were
wrapped inside one LOCK TABLES
, InnoDB
asserted in
`lock0lock.c'.
NULL
values in a UNIQUE
secondary
index for an InnoDB
table. But CHECK TABLE
was not relaxed: it
reports the table as corrupt. CHECK TABLE
no longer complains in
this situation.
SHOW GRANTS
now shows REFERENCES
instead of REFERENCE
.
SELECT ... WHERE key=@var_name OR key=@var_name2
InnoDB
keys to 500 bytes.
InnoDB
now supports NULL
in keys.
SELECT RELEASE_LOCK()
.
DO expression,[expression]
slave-skip-errors
option.
SHOW STATUS
is
now much longer.)
InnoDB
tables.
GROUP BY expr DESC
works.
t1 LEFT JOIN t2 ON t2.key=constant
.
mysql_config
now also works with binary (relocated) distributions.
InnoDB
and BDB
tables will now use index when doing an
ORDER BY
on the whole table.
BDB
tables.
ANALYZE
, REPAIR
, and OPTIMIZE TABLE
when
the thread is waiting to get a lock on the table.
ANALYZE TABLE
.
INSERT DELAYED
which could cause the binary log to have rows that were not yet written
to MyISAM
tables.
(UPDATE|DELETE) ...WHERE MATCH
bugfix.
MyISAM
files.
--core-file
now works on Solaris.
InnoDB
to complain if it cannot find
free blocks from the buffer cache during recovery.
InnoDB
insert buffer B-tree handling that could cause
crashes.
InnoDB
lock timeout handling.
ALTER TABLE
on a TEMPORARY
InnoDB
table.
OPTIMIZE TABLE
that reset index cardinality if it
was up to date.
t1 LEFT_JOIN t2 ... WHERE t2.date_column IS NULL
when
date_column was declared as NOT NULL
.
BLOB
's.
MERGE
tables on OS with 32 bit file pointers.
TIME_TO_SEC()
when using negative values.
Rows_examined
count in slow query log.
AVG()
column in HAVING
.
DAYOFYEAR(column)
, will return NULL
for 0000-00-00
dates.
SELECT * FROM date_col="2001-01-01" and date_col=time_col
)
Can't write, because of unique
constraint
with some GROUP BY
queries.
CREATE ... FULLTEXT
keys with other
storage engines than MyISAM
.
InnoDB
variables to SHOW VARIABLES
.
InnoDB
tables.
signal()
on Windows because this appears to not be
100% reliable.
WHERE col_name=NULL
on an indexed column
that had NULL
values.
LEFT JOIN ... ON (column_name = constant) WHERE column_name = constant
.
%
could cause
a core dump.
TCP_NODELAY
がいくつかのシステムで使用されていなかったのを修正(TCP 通信時の速度低下の問題).
The following changes are for InnoDB
tables:
InnoDB
variables to SHOW VARIABLES
.
InnoDB
tables.
DROP DATABASE
now works also for InnoDB
tables.
InnoDB
now supports datafiles and raw disk partitions bigger
than 4 GB on those operating systems that have big files.
InnoDB
calculates better table cardinality estimates for the
MySQL optimiser.
latin1
are ordered
according to the MySQL ordering.
Note: if you are using latin1
and have inserted characters whose
code is greater than 127 into an indexed CHAR
column, you should
run CHECK TABLE
on your table when you upgrade to 3.23.44, and
drop and reimport the table if CHECK TABLE
reports an error!
innodb_thread_concurrency
, helps in
performance tuning in heavily concurrent environments.
innodb_fast_shutdown
, speeds up
server shutdown.
innodb_force_recovery
, helps to save
your data in case the disk image of the database becomes corrupt.
innodb_monitor
has been improved and a new
innodb_table_monitor
added.
AUTO_INCREMENT
columns with
multiple-line inserts.
MAX(col)
is selected from an empty table, and
col
is not the first column in a multi-column index.
INSERT DELAYED
and FLUSH TABLES
introduced
in 3.23.42.
SELECT
with
many tables and multi-column indexes and 'range' type.
EXPLAIN SELECT
when using
many tables and ORDER BY
.
LOAD DATA FROM MASTER
when using table with
CHECKSUM=1
.
BDB
tables.
BDB
tables and UNIQUE
columns defined
as NULL
.
myisampack
when using pre-space filled CHAR
columns.
--safe-user-create
.
LOCK TABLES
and BDB
tables.
REPAIR TABLE
on MyISAM
tables with row
lengths in the range from 65517 to 65520 bytes.
mysqladmin shutdown
when there was
a lot of activity in other threads.
INSERT DELAYED
where delay thread could be
hanging on upgrading locks
with no apparent reason.
myisampack
and BLOB
.
MERGE
table come from the same
database.
LOAD DATA INFILE
and transactional tables.
INSERT DELAYED
with wrong column definition.
REPAIR
of some particularly broken tables.
InnoDB
and AUTO_INCREMENT
columns.
InnoDB
and RENAME TABLE
columns.
InnoDB
and BLOB
columns. If you have
used BLOB
columns larger than 8000 bytes in an InnoDB
table, it is necessary to dump the table with mysqldump
, drop it and
restore it from the dump.
InnoDB
when one could get the error Can't
execute the given command...
even when no transaction was active.
ALTER TABLE
). Now --lower_case_names
also works on Unix.
--sql-mode=option[,option[,option]]
option to mysqld
.
See section mysqld
コマンド行オプション.
shutdown
on Solaris where the
`.pid' file wasn't deleted.
InnoDB
now supports < 4 GB rows. The former limit was 8000 bytes.
doublewrite
file flush method is used in InnoDB
.
It reduces the need for Unix fsync()
calls to a fraction and
improves performance on most Unix flavors.
InnoDB
Monitor to print a lot of InnoDB
state
information, including locks, to the standard output. This is useful in
performance tuning.
InnoDB
have been fixed.
record_buffer
to record_buffer
and
record_rnd_buffer
. To make things compatible to previous MySQL
versions, if record_rnd_buffer
is not set, then it takes the
value of record_buffer
.
ORDER BY
where some ORDER BY
parts
where wrongly removed.
ALTER TABLE
and MERGE
tables.
my_thread_init()
and my_thread_end()
to
`mysql_com.h'
--safe-user-create
option to mysqld
.
SELECT DISTINCT ... HAVING
that caused error message
Can't find record in #...
--low-priority-updates
and INSERT
statements.
slave_net_timeout
for replication.
UPDATE
and BDB
tables.
BDB
tables when using key parts.
GRANT FILE ON database.* ...
; previously
we added the DROP
privilege for the database.
DELETE FROM tbl_name ... LIMIT 0
and
UPDATE FROM tbl_name ... LIMIT 0
, which acted as though the
LIMIT
clause was not present (they deleted or updated all selected
rows).
CHECK TABLE
now checks if an AUTO_INCREMENT
column contains
the value 0.
SIGHUP
to mysqld
will now only flush the logs,
not reset the replication.
1.0e1
(no sign after e
).
--force
to myisamchk
now also updates states.
--warnings
to mysqld
. Now mysqld
prints the error Aborted connection
only if this option is used.
SHOW CREATE TABLE
when you didn't have a
PRIMARY KEY
.
innodb_unix_file_flush_method
variable to
innodb_flush_method
.
BIGINT UNSIGNED
to DOUBLE
. This caused
a problem when doing comparisons with BIGINT
values outside of the
signed range.
BDB
tables when querying empty tables.
COUNT(DISTINCT)
with LEFT JOIN
and
there weren't any matching rows.
GEMINI
table
type. GEMINI
is not released under an Open Source
license.
AUTO_INCREMENT
sequence wasn't reset when dropping
and adding an AUTO_INCREMENT
column.
CREATE ... SELECT
now creates non-unique indexes delayed.
LOCK TABLES tbl_name READ
followed by
FLUSH TABLES
put an exclusive lock on the table.
REAL @variable
values were represented with only 2 digits when
converted to strings.
LOAD TABLE FROM MASTER
failed.
myisamchk --fast --force
will no longer repair tables
that only had the open count wrong.
-lcma
thread library on HP-UX 10.20 so
that MySQL will be more stable on HP-UX.
IF()
and number of decimals in the result.
INSERT DELAYED
was waiting for
a LOCK TABLE
.
InnoDB
when tablespace was full.
MERGE
tables and big tables (> 4G) when using
ORDER BY
.
SELECT
from MERGE
table
sometimes results in incorrectly ordered rows.
REPLACE()
when using the ujis
character set.
BDB
patches 3.2.9.1 and 3.2.9.2.
--skip-stack-trace
option to mysqld
.
CREATE TEMPORARY
now works with InnoDB
tables.
InnoDB
now promotes sub keys to whole keys.
CONCURRENT
to LOAD DATA
.
max_allowed_packet
is too low to
read a very long log event from the master.
SELECT DISTINCT ... HAVING
.
SHOW CREATE TABLE
now returns TEMPORARY
for temporary tables.
Rows_examined
to slow query log.
WHERE
that didn't match any rows.
mysqlcheck
.
CHECK
,
REPAIR
, OPTIMIZE
.
InnoDB
.
SELECT * FROM tbl_name,tbl_name2 ... ORDER BY key_part1 LIMIT #
will use index on key_part1
instead of filesort
.
LOCK TABLE to_table WRITE,...; INSERT INTO to_table... SELECT ...
when to_table
was empty.
LOCK TABLE
and BDB
tables.
MATCH()
in HAVING
clause.
HEAP
tables with LIKE
.
--mysql-version
option to safe_mysqld
INNOBASE
to InnoDB
(because the INNOBASE
name was already used). All configure
options and mysqld
start options now use innodb
instead of innobase
. This
means that before upgrading to this version, you have to change any
configuration files where you have used innobase
options!
CHAR(255) NULL
columns.
master-host
is not set, as
long as server-id
is set and valid `master.info' is present.
SET SQL_SLAVE_SKIP_COUNTER=1; SLAVE START
after a manual sanity
check/correction of data integrity.
REGEXP
on 64-bit machines.
UPDATE
and DELETE
with WHERE unique_key_part IS NULL
didn't update/delete all rows.
INSERT DELAYED
for tables that support transactions.
TEXT
/BLOB
column
with wrong date format.
ALTER TABLE
and LOAD DATA INFILE
that disabled
key-sorting. These commands should now be faster in most cases.
FLUSH
or REPAIR
) would not use indexes for the
next query.
ALTER TABLE
to InnoDB
tables on FreeBSD.
mysqld
variables myisam_max_sort_file_size
and
myisam_max_extra_sort_file_size
.
InnoDB
.
tis620
character set to make comparisons
case-independent and to fix a bug in LIKE
for this character set.
Note: All tables that uses the tis620
character set must be
fixed with myisamchk -r
or REPAIR TABLE
!
--skip-safemalloc
option to mysqld
.
mysqld
is run
as root.
FLUSH TABLES
and TEMPORARY
tables.
(Problem with freeing the key cache and error Can't reopen table...
.)
InnoDB
with other character sets than latin1
and another problem when using many columns.
DISTINCT
and summary functions.
SET TRANSACTION ISOLATION LEVEL ...
SELECT ... FOR UPDATE
.
UPDATE
where keys weren't always used to find the
rows to be updated.
CONCAT_WS()
where it returned incorrect results.
CREATE ... SELECT
and INSERT ... SELECT
to not
allow concurrent inserts as this could make the binary log hard to repeat.
(Concurrent inserts are enabled if you are not using the binary or update log.)
glibc
2.2.
ORDER BY
.
CLIENT_TRANSACTIONS
.
SHOW VARIABLES
when using INNOBASE
tables.
SELECT DISTINCT
didn't work.
SHOW ANALYZE
for small tables.
run-all-tests
.
INNOBASE
support
to be compiled.
INNOBASE
storage engine and the BDB
storage engine
to the MySQL source distribution.
GEMINI
tables.
INSERT DELAYED
that caused threads to hang when
inserting NULL
into an AUTO_INCREMENT
column.
CHECK TABLE
/ REPAIR TABLE
that could cause
a thread to hang.
REPLACE
will not replace a row that conflicts with an
AUTO_INCREMENT
generated key.
mysqld
now only sets CLIENT_TRANSACTIONS
in
mysql->server_capabilities
if the server supports a
transaction-safe storage engine.
LOAD DATA INFILE
to allow numeric values to be read into
ENUM
and SET
columns.
ALTER TABLE ... ORDER BY
.
max_user_connections
variable to mysqld
.
max_allowed_packet
, not the
arbitrary limit of 4 MB.
=
in argument to --set-variable
.
Waiting for table
.
SHOW CREATE TABLE
now displays the UNION()
for MERGE
tables.
ALTER TABLE
now remembers the old UNION()
definition.
BDB
storage engine that occurred when using an index
on multi-part key where a key part may be NULL
.
MAX()
optimization on sub-key for BDB
tables.
BDB
tables and BLOB
or TEXT
fields when joining many tables.
BDB
tables and TEXT
columns.
BLOB
key where a const row wasn't found.
mysqlbinlog
writes the timestamp value for each query.
This ensures that one gets same values for date functions like NOW()
when using mysqlbinlog
to pipe the queries to another server.
--skip-gemini
, --skip-bdb
, and --skip-innodb
options to be specified when invoking mysqld
, even if these storage
engines are not compiled in to mysqld
.
GROUP BY ... DESC
.
SET
code, when one ran SET @foo=bar
,
where bar
is a column reference, an error was not properly generated.
--character-sets-dir
option to myisampack
.
REPAIR TABLE ... EXTENDED
.
GROUP BY
on an alias,
where the alias was the same as an existing column name.
SEQUENCE()
as an example UDF function.
mysql_install_db
to use BINARY
for CHAR
columns in the privilege tables.
TRUNCATE tbl_name
to TRUNCATE TABLE tbl_name
to use the same syntax as Oracle. Until 4.0 we will also allow
TRUNCATE tbl_name
to not crash old code.
MyISAM
tables when a BLOB
was
first part of a multi-part key.
CASE
didn't work with GROUP BY
.
--sort-recover
option to myisamchk
.
myisamchk -S
and OPTIMIZE TABLE
now work on Windows.
DISTINCT
on results from functions that referred
to a group function, like:
SELECT a, DISTINCT SEC_TO_TIME(SUM(a)) FROM tbl_name GROUP BY a, b;
libmysqlclient
library.
Fixed bug in handling STOP
event after ROTATE
event in
replication.
DROP DATABASE
.
Table_locks_immediate
and Table_locks_waited
status
variables.
SET SQL_SLAVE_SKIP_COUNTER=n
command to recover from
replication glitches without a full database copy.
max_binlog_size
variable; the binary log will be rotated
automatically when the size crosses the limit.
Last_error
, Last_errno
, and Slave_skip_counter
variables to SHOW SLAVE STATUS
.
MASTER_POS_WAIT()
function.
SIGILL
, and SIGBUS
in addition to
SIGSEGV
.
mysqltest
to take care of the timing issues in the test
suite.
ALTER TABLE
can now be used to change the definition for a
MERGE
table.
MERGE
tables on Windows.
--temp-pool
option to mysqld
. 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.
BACKUP
, RESTORE
, CHECK
, REPAIR
, and
ANALYZE TABLE
.
FULL
to SHOW COLUMNS
. Now we show the
privilege list for the columns only if this option is given.
SHOW LOGS
when there weren't any BDB
logs.
mysql_list_fields()
. This is
to keep this code compatible with SHOW FIELDS
.
MERGE
tables didn't work on Windows.
SET PASSWORD=...
on Windows.
TRIM("foo" from "foo")
didn't return an empty string.
--with-version-suffix
option to configure
.
mysql_close()
.
RESTORE TABLE
when trying to restore from a non-existent
directory.
SET PASSWORD
.
MASTER_POS_WAIT()
.
BDB
interface code. During
testing we found and fixed many errors in the interface code.
HAVING
on an empty table could produce one result row when
it shouldn't.
HEAP
tables on Windows.
SHOW TABLE STATUS
didn't show correct average row length for tables
larger than 4G.
CHECK TABLE ... EXTENDED
didn't check row links for fixed size tables.
MEDIUM
to CHECK TABLE
.
DECIMAL()
keys on negative numbers.
HOUR()
(and some other TIME
functions) on a CHAR
column
always returned NULL
.
setrlimit()
on Linux to get
-O --open-files-limit=#
to work on Linux.
bdb_version
variable to mysqld
.
SELECT ... FROM t1 LEFT JOIN t2 ON (t1.a=t2.a) WHERE t1.a=t2.aIn this case the test in the
WHERE
clause was wrongly optimized away.
MyISAM
when deleting keys with possible NULL
values, but the first key-column was not a prefix-compressed text column.
mysql.server
to read the [mysql.server]
option file group
rather than the [mysql_server]
group.
safe_mysqld
and mysql.server
to also read the
server
option section.
Threads_created
status variable to mysqld
.
SHOW OPEN TABLES
command.
myisamdump
works against old mysqld
servers.
myisamchk -k#
so that it works again.
LOCK TABLES
will now automatically start a new transaction.
BDB
tables to not use internal subtransactions and reuse
open files to get more speed.
--mysqld=#
option to safe_mysqld
.
--fields-*-by
and
--lines-terminated-by
options to mysqldump
and
mysqlimport
. By Paul DuBois.
--safe-show-database
option to mysqld
.
have_bdb
, have_gemini
, have_innobase
,
have_raid
and have_openssl
to SHOW VARIABLES
to make it
easy to test for supported extensions.
--open-files-limit
option to mysqld
.
--open-files
option to --open-files-limit
in
safe_mysqld
.
HEAP
tables
that had many keys.
--bdb-no-sync
works.
--bdb-recover
to --bdb-no-recover
as recover should
be on by default.
BDB
locks to 10000.
BDB
tables.
mysqld_multi.sh
to use configure variables. Patch by
Christopher McCrory.
--skip-networking
on Debian Linux.
UNOPENED
in error messages.
SHOW LOGS
queries.
<=>
operator.
REPLACE
with BDB
tables.
LPAD()
and RPAD()
will shorten the result string if it's longer
than the length argument.
SHOW LOGS
command.
BDB
logs on shutdown.
PRIMARY
keys first, followed by
UNIQUE
keys.
UPDATE
involving multi-part keys where one
specified all key parts both in the update and the WHERE
part. In
this case MySQL could try to update a record that didn't match
the whole WHERE
part.
mysqld
to report the
hostname as ''
in some error messages.
HEAP
type tables; the variable
max_heap_table_size
wasn't used. Now either MAX_ROWS
or
max_heap_table_size
can be used to limit the size of a HEAP
type table.
bdb_lock_max
variable to bdb_max_lock
.
AUTO_INCREMENT
on sub-fields for BDB
tables.
ANALYZE
of BDB
tables.
BDB
tables, we now store the number of rows; this helps to optimise
queries when we need an approximation of the number of rows.
ROLLBACK
when you have updated a non-transactional table
you will get an error as a warning.
--bdb-shared-data
option to mysqld
.
Slave_open_temp_tables
status variable to mysqld
binlog_cache_size
and max_binlog_cache_size
variables to
mysqld
.
DROP TABLE
, RENAME TABLE
, CREATE INDEX
and
DROP INDEX
are now transaction endpoints.
DROP DATABASE
on a symbolically linked database, both
the link and the original database is deleted.
DROP DATABASE
to work on OS/2.
SELECT DISTINCT ... table1 LEFT JOIN
table2 ...
when table2
was empty.
--abort-slave-event-count
and
--disconnect-slave-event-count
options to mysqld
for
debugging and testing of replication.
SHOW KEYS
now shows whether key is FULLTEXT
.
mysqld_multi
. See section mysqld_multi
, 複数の MySQL サーバーを管理するプログラム.
mysql-multi.server.sh
. Thanks to
Tim Bunce Tim.Bunce@ig.co.uk for modifying mysql.server
to
easily handle hosts running many mysqld
processes.
safe_mysqld
, mysql.server
, and mysql_install_db
have
been modified to use mysql_print_defaults
instead of various hacks
to read the `my.cnf' files. In addition, the handling of various
paths has been made more consistent with how mysqld
handles them
by default.
FULLTEXT
indexes in one table.
REPAIR
/OPTIMIZE
.
Yuri Dario
.
FLUSH TABLES tbl_name
didn't always flush the index tree
to disk properly.
--bootstrap
is now run in a separate thread. This fixes a problem
that caused mysql_install_db
to core dump on some Linux machines.
mi_create()
to use less stack space.
MATCH()
when used
with UNIQUE
key.
crash-me
and the MySQL benchmarks to also work
with FrontBase.
RESTRICT
and CASCADE
after DROP TABLE
to make
porting easier.
--slow-log
.
connect_timeout
variable to mysql
and mysqladmin
.
connect-timeout
as an alias for timeout
for option files
read by mysql_options()
.
--pager[=...]
, --no-pager
,
--tee=...
and --no-tee
to the mysql
client. The
new corresponding interactive commands are pager
, nopager
,
tee
and notee
. See section mysql
, コマンドラインツール, mysql --help
and the interactive help for more information.
MyISAM
table failed.
SELECT
, UPDATE
and INSERT
statements running. The symptom was that the UPDATE
and
INSERT
queries were locked for a long time while new SELECT
statements were executed before the updates.
options_files
with mysql_options()
the
return-found-rows
option was ignored.
interactive-timeout
in the option file that
is read by mysql_options()
. This makes it possible to force
programs that run for a long time (like mysqlhotcopy
) to use the
interactive_timeout
time instead of the wait_timeout
time.
--log-long-format
then also queries that
do not use an index are logged, even if the query takes less than
long_query_time
seconds.
LEFT JOIN
which caused all columns in a reference
table to be NULL
.
NATURAL JOIN
without keys.
TEXT
or BLOB
.
DROP
of temporary tables wasn't stored in the update/binary log.
SELECT DISTINCT * ... LIMIT #
only returned one row.
strstr()
for SPARC and cleaned up
the `global.h' header file to avoid a problem with bad aliasing with
the compiler submitted with RedHat 7.0. (Reported by Trond Eivind Glomsrd)
--skip-networking
option now works properly on NT.
ISAM
tables when a row with a length
of more than 65K was shortened by a single byte.
MyISAM
when running multiple updating processes on
the same table.
FLUSH TABLE tbl_name
.
--replicate-ignore-table
, --replicate-do-table
,
--replicate-wild-ignore-table
, and --replicate-wild-do-table
options to mysqld
.
IO_CACHE
mechanism instead of
FILE
to avoid OS problems when there are many files open.
--open-files
and --timezone
options to safe_mysqld
.
CREATE TEMPORARY TABLE ... SELECT ...
.
CREATE TABLE ... SELECT NULL
.
large_file_support
,net_read_timeout
,
net_write_timeout
and query_buffer_size
to SHOW VARIABLES
.
created_tmp_files
and sort_merge_passes
to SHOW STATUS
.
FOREIGN KEY
definition.
TRUNCATE table_name
as a synonym for
DELETE FROM table_name
.
BDB
key compare function when comparing part keys.
bdb_lock_max
variable to mysqld
.
mysql_connect()
now aborts on Linux if the server doesn't answer in
timeout
seconds.
SLAVE START
did not work if you started with
--skip-slave-start
and had not explicitly run CHANGE MASTER TO
.
SHOW MASTER STATUS
to be consistent with
SHOW SLAVE STATUS
. (It now has no directory in the log name.)
PURGE MASTER LOGS TO
.
SHOW MASTER LOGS
.
--safemalloc-mem-limit
option to mysqld
to simulate memory
shortage when compiled with the --with-debug=full
option.
SHOW SLAVE STATUS
was using an uninitialised mutex if the slave had
not been started yet.
ELT()
and MAKE_SET()
when the query used
a temporary table.
CHANGE MASTER TO
without specifying MASTER_LOG_POS
would
set it to 0 instead of 4 and hit the magic number in the master binlog.
ALTER TABLE ... ORDER BY ...
syntax added. This will create the
new table with the rows in a specific order.
MyISAM
tables sometimes failed
when the datafile was corrupt.
SHOW CREATE
when using AUTO_INCREMENT
columns.
BDB
tables to use new compare function in Berkeley DB 3.2.3.
latin5
(turkish) character set.
FLUSH MASTER
and FLUSH SLAVE
to RESET MASTER
and RESET SLAVE
.
<>
to work properly with NULL
.
SUBSTRING_INDEX()
and REPLACE()
.
(Patch by Alexander Igonitchev)
CREATE TEMPORARY TABLE IF NOT EXISTS
not to produce an error
if the table exists.
PRIMARY KEY
in a BDB
table, a hidden
PRIMARY KEY
will be created.
BDB
tables.
LEFT JOIN
in some cases preferred a full table scan when there was
no WHERE
clause.
--log-slow-queries
, don't count the time waiting for a lock.
MyISAM
tables if you start mysqld
with
--myisam-recover
.
TYPE=
keyword from CHECK
and
REPAIR
. Allow CHECK
options to be combined. (You can still
use TYPE=
, but this usage is deprecated.)
--replicate-rewrite-db
option to mysqld
.
--skip-slave-start
option to mysqld
.
INSERT INTO foo(some_key)
values (1),(1)
) erroneously terminated the slave thread.
DISTINCT
is only used on columns
from some of the tables.
1e1
).
SHOW GRANTS
didn't always show all column grants.
--default-extra-file=#
option to all MySQL clients.
INSERT
statements now are initialised properly.
UPDATE
didn't always work when used with a range on a timestamp that
was part of the key that was used to find rows.
FULLTEXT
index when inserting a NULL
column.
mkstemp()
instead of tempnam()
. Based
on a patch from John Jones.
databasename
works as second argument to mysqlhotcopy
.
UMASK
and UMASK_DIR
environment variables
now can be specified in octal by beginning the value with a zero.
RIGHT JOIN
. This makes RIGHT
a reserved word.
@@IDENTITY
as a synonym for LAST_INSERT_ID()
.
(This is for MSSQL compatibility.)
myisamchk
and REPAIR
when using FULLTEXT
index.
LOAD DATA INFILE
now works with FIFOs.
(Patch by Toni L. Harbaugh-Blackford.)
FLUSH LOGS
broke replication if you specified a log name with an
explicit extension as the value of the log-bin
option.
MyISAM
with packed multi-part keys.
CHECK TABLE
on Windows.
FULLTEXT
index always used the koi8_ukr
character set.
CHECK TABLE
.
MyISAM
repair/reindex code didn't use the --tmpdir
option for its temporary files.
BACKUP TABLE
and RESTORE TABLE
.
CHANGE MASTER TO
when the slave did not have
the master to start with.
Time
in the processlist for Connect
of
the slave thread.
FLUSH MASTER
if you didn't specify
a filename argument to --log-bin
.
--memlock
option to mysqld
to lock mysqld
in memory on systems with the mlockall()
call (like in Solaris).
HEAP
tables didn't use keys properly. (Bug from 3.23.23.)
MERGE
tables (keys, mapping, creation,
documentation...). See section MERGE
Tables (3.23.25以上).
mysqldump
from 3.23 which caused some CHAR
columns
not to be quoted.
analyze
, check
, optimize
and repair code.
OPTIMIZE TABLE
is now mapped to REPAIR
with statistics and
sorting of the index tree. This means that for the moment it only
works on MyISAM
tables.
ORDER BY
bug with BDB
tables.
mysqld
couldn't remove the `.pid' file
under Windows.
--log-isam
to log MyISAM
tables instead of isam
tables.
CHECK TABLE
to work on Windows.
pwrite()
safe on Windows.
created_tmp_disk_tables
variable to mysqld
.
TIMESTAMP(X)
columns, MySQL now reports columns with X
other than 14 or 8 to be strings.
latin1
as it was before MySQL Version 3.23.23.
Any table that was created or modified with 3.23.22 must be repaired if it has
CHAR
columns that may contain characters with ASCII values greater than
128!
BDB
tables and reading on a unique (not primary) key.
win1251
character set (it's now only marked deprecated).
REPAIR TABLE
or myisamchk
before use!
--core-file
option to mysqld
to get a core file on
Linux if mysqld
dies on the SIGSEGV
signal.
mysql
は、デフォルトで
--no-named-commands
(-g
) オプションで起動されるようになった。
このオプションは --enable-named-commands
(-G
) で無効にできる。
これはある場合に非互換の問題を引き起こすでしょう。たとえば、セミコロンなしで
named コマンドを使用している SQL スクリプトなど!
Long format commands
still work from the first line.
DROP TABLE
statements at
the same time.
LEFT JOIN
on an
empty table.
mysqld
with incorrect options.
free()
bug in mysqlimport
.
MyISAM
index handling of
DECIMAL
/NUMERIC
keys.
MyISAM
tables. In some contexts,
usage of MIN(key_part)
or MAX(key_part)
returned an empty set.
mysqlhotcopy
to use the new FLUSH TABLES table_list
syntax. Only tables which are being backed up are flushed now.
--enable-thread-safe-client
の振る舞いを変更。
非スレッド (-lmysqlclient
) とスレッド (-lmysqlclient_r
) ライブラリ
の両方が作成されるため。
今までスレッド化された -lmysqlclient
をリンクしていた場合には、
今後、libmysqlclient_r
のリンクが必要となる。
RENAME TABLE
command.
COUNT(DISTINCT ...)
は NULL
のエントリを数えない。
ALTER TABLE
, LOAD DATA INFILE
on empty tables and
INSERT ... SELECT ...
on empty tables to create non-unique indexes
in a separate batch with sorting. This will make the above calls much
faster when you have many indexes.
ALTER TABLE
now logs the first used insert_id correctly.
BLOB
フィールドにデフォルト値を定義した場合にクラッシュしていたのを修正。
DATE_ADD/DATE_SUB
が date でなく datetime を返していたバグを修正。
***DEAD***
in SHOW PROCESSLIST
.
pthread_rwlock_rdlock
code.
HEAP
table, all rows
weren't always deleted.
HEAP
tables for searches on a part
index.
SELECT
on part keys to work with BDB
tables.
INSERT INTO bdb_table ... SELECT
to work with BDB
tables.
CHECK TABLE
now updates key statistics for the table.
ANALYZE TABLE
will now only update tables that have been changed
since the last ANALYZE
. Note that this is a new feature and tables
will not be marked to be analysed until they are updated in any way with
3.23.23 or newer. For older tables, you have to do CHECK TABLE
to update the key distribution.
CHECK
, ANALYZE
,
REPAIR
and SHOW CREATE
commands.
CHANGE MASTER TO
コマンドの追加。
FAST
, QUICK
EXTENDED
check types to
CHECK TABLES
.
myisamchk
so that --fast
and
--check-only-changed
are also honored with --sort-index
and
--analyze
.
LOAD TABLE FROM MASTER
がインデックスを再構築している間にテーブルを
ロックしなかったバグを修正。
LOAD DATA INFILE
を
行うと、レプリケーションを壊していたのを修正。
SHOW SLAVE STATUS
and SHOW MASTER STATUS
.
SLAVE STOP
now will not return until the slave thread actually exits.
MATCH
関数を利用した Full-text search と FULLTEXT
インデックスの追加。
(MyISAM でのみ利用可能)。 これにより FULLTEXT
が予約語になる。
lex_hash.h
is created properly for each MySQL
distribution.
MASTER
and COLLECTION
are not reserved words.
--slow-query-log
didn't contain the whole queries.
BDB
tables are rolled back if the
connection is closed unexpectedly.
gcc
2.96 (intel) and gcc
2.9
(IA64) in gen_lex_hash.c
.
host=
を使用した場合、
クライアントライブラリにメモリリークがあったのを修正した。
DATE_ADD()
/DATE_SUB()
against a number.
-F, --fast
for myisamchk
. Added
-C, --check-only-changed
option to myisamchk
.
ANALYZE tbl_name
to update key statistics for tables.
0x...
to be regarded as integers by default.
SHOW PROCESSLIST
.
auto-rehash
on reconnect for the mysql
client.
MyISAM
の インデックスファイルが 64M bytes を超えれないバグを修正した。
3.23.21 でエンバグした。
SHOW MASTER STATUS
と SHOW SLAVE STATUS
の追加。
mysql_character_set_name()
関数を追加。
mysql_config
スクリプトの追加。
<
or >
with a char column that was only
partly indexed.
mysqladmin
を、API コールしていたかわりに、
CREATE DATABASE
/DROP DATABASE
コマンドを
使用するように変更した。
chown
warning in safe_mysqld
.
ORDER BY
のバグを修正。 3.23.19 でエンバグした。
DELETE FROM tbl_name
to do a drop+create of
the table if we are in AUTOCOMMIT
mode (needed for BDB
tables).
ISAM
/MyISAM
index files get full during an INSERT
/UPDATE
.
myisamchk
didn't correctly update row checksum when used with
-ro
(this only gave a warning in subsequent runs).
REPAIR TABLE
so that it works with tables without indexes.
DROP DATABASE
.
LOAD TABLE FROM MASTER
is sufficiently bug-free to announce it as
a feature.
MATCH
と AGAINST
が予約語になった。
DELETE FROM tbl_name
が `.frm' ファイルを消してしまっていた。
SHOW CREATE TABLE
.
MyISAM
table
when doing update based on key on a table with many keys and some key changed
values.
ORDER BY
can now use REF
keys to find subsets of the rows
that need to be sorted.
print_defaults
の名前を my_print_defaults
に変更。
名前の衝突をさけるため。
NULLIF()
to work according to ANSI SQL99.
net_read_timeout
と net_write_timeout
を
mysqld
の起動時のパラメタとして追加。
myisamchk --sort-records
on a table with prefix compressed index.
pack_isam
と myisampack
を MySQL の標準配布に追加。
BEGIN WORK
(the same as BEGIN
).
ORDER BY
on a CONV()
expression.
LOAD TABLE FROM MASTER
FLUSH MASTER
and FLUSH SLAVE
FLUSH TABLES WITH READ LOCK
to make a global lock suitable for
making a copy of MySQL datafiles.
CREATE TABLE ... SELECT ... PROCEDURE
now works.
GROUP BY
on VARCHAR/CHAR
columns.
READ
and a
WRITE
lock.
myisamchk
and RAID
tables.
FIND_IN_SET()
when the first argument was NULL
.
LEFT JOIN
and ORDER BY
where the first
table had only one matching row.
duplicated key
problem when doing big GROUP BY
operations.
(This bug was probably introduced in 3.23.15.)
INNER JOIN
の文法を ANSI SQL にマッチさせた.
NATURAL JOIN
構文を追加.
BDB
interface.
--no-defaults
and --defaults-file
to
safe_mysqld.sh
and mysql_install_db.sh
.
USE INDEX
works with PRIMARY
keys.
BEGIN
statement to start a transaction in AUTOCOMMIT
mode.
AUTOCOMMIT
mode
and if there is a pending transaction. If there is a pending transaction,
the client library will give an error before reconnecting to the server to
let the client know that the server did a rollback.
The protocol is still backward-compatible with old clients.
KILL
now works on a thread that is locked on a 'write' to a dead client.
log-slave-updates
option to mysqld
, to allow
daisy-chaining the slaves.
pthread_t
is not the same as int
.
INSERT DELAYED
code when doing
ALTER TABLE
.
INSERT DELAYED
.
SLAVE START
and SLAVE STOP
statements.
TYPE=QUICK
オプションを CHECK
と REPAIR
に追加。
REPAIR TABLE
when the table was in use by other threads.
gdb
when one does a lot of reconnects. This will also improve
systems where you can't use persistent connections.
UPDATE IGNORE
will not abort if an update results in a
DUPLICATE_KEY
error.
CREATE TEMPORARY TABLE
commands in the update log.
delay_key_write
tables and CHECK TABLE
.
replicate-do-db
and replicate-ignore-db
options to
mysqld
, to restrict which databases get replicated.
SQL_LOG_BIN
オプションを追加。
mysqld
as root
one must now use the --user=root
option.
FLUSH TABLES
command.
slow_launch_time
variable and the Slow_launch_threads
status variable to mysqld
. These can be examined with
mysqladmin variables
and mysqladmin extended-status
.
INET_NTOA()
and INET_ATON()
.
IF()
now depends on the second and
third arguments and not only on the second argument.
myisamchk
could go into a loop when trying to
repair a crashed table.
INSERT DELAYED
to update log if SQL_LOG_UPDATE=0
.
REPLACE
on HEAP
tables.
SHOW VARIABLES
output.
DELETE
of many rows on a table with
compressed keys where MySQL scanned the index to find the rows.
CHECK
on table with deleted keyblocks.
LAST_INSERT_ID()
to update
a table with an AUTO_INCREMENT
key.
NULLIF()
function.
LOAD DATA INFILE
on a table with
BLOB/TEXT
columns.
MyISAM
to be faster when inserting keys in sorted order.
EXPLAIN SELECT ...
now also prints out whether MySQL needs to
create a temporary table or use file sorting when resolving the SELECT
.
ORDER BY
parts where the part is a
constant expression in the WHERE
part. Indexes can now 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 ORDER BY
columns are constants in the WHERE
clause. See section MySQL はどのようにインデックスを使用するか?.
UPDATE
and DELETE
on a whole unique key in the WHERE
part
are now faster than before.
RAID_CHUNKSIZE
to be in 1024-byte increments.
LOAD_FILE(NULL)
.
mysql_real_escape_string()
function to the MySQL C API.
CONCAT()
where one of the arguments was a function
that returned a modified argument.
myisamchk
の致命的なバグを修正した。 このバグはインデックスファイル中の
ヘッダーを、テーブルをチェックしているだけなのにもかかわらず、更新していた。
This confused the
mysqld
daemon if it updated the same table at the same time. Now
the status in the index file is only updated if one uses
--update-state
. With older myisamchk
versions you shoul
use --read-only
when only checking tables, if there is the
slightest chance that the mysqld
server is working on the table at the
same time!
DROP TABLE
is logged in the update log.
DECIMAL()
key field
where the column data contained leading zeros.
myisamchk
のバグを修正。
DATETIME
in ISO8601 format: 2000-03-12T12:00:00
mysqld
バイナリで、多くの違う
キャラクタセットを扱えるようになった。
(mysqld
スタート時に指定できます).
REPAIR TABLE
コマンドを追加。
mysql_thread_safe()
C API 関数を追加。
UMASK_DIR
環境変数を追加。
CONNECTION_ID()
関数を追加
=
on BLOB
or VARCHAR BINARY
keys, where
only a part of the column was indexed, the whole column of the result
row wasn't compared.
sjis
キャラクターセットの ORDER BY
の問題を修正
GROUP BY
part.
LOCK TABLE
command; this fixed the problem one got when running
the test-ATIS test with --fast
or --check-only-changed
.
SQL_BUFFER_RESULT
オプションを SELECT
に追加
CHECK TABLE
コマンドの追加。
MyISAM
in 3.23.12 that didn't get into the source
distribution because of CVS problems.
mysqladmin shutdown
will wait for the local server
to close down.
print_defaults
program to the `.rpm' files. Removed
mysqlbug
from the client `.rpm' file.
MyISAM
involving REPLACE ... SELECT ...
which could
give a corrupted table.
myisamchk
where it incorrectly reset the
AUTO_INCREMENT
value.
HEAP
一時テーブル上の DISTINCT
を変更した。
This mostly concerns queries of
type SELECT DISTINCT ... GROUP BY ...
. This fixes a problem where
not all duplicates were removed in queries of the above type.
新しく追加したコードは、とても速い。
IF NOT EXISTS
を CREATE DATABASE
に追加.
--all-databases
と --databases
オプションを mysqldump
に追加。
MyISAM
型テーブル中の圧縮した DECIMAL()
インデックスのバグを修正した。
mysqladmin shutdown
を実行した場合に、mysqladmin
は
終了前に pidfile が無くなるまで待つようになった。
COUNT(DISTINCT ...)
クエリでコアを吐いたのを修正した。
myisamchk
works properly with RAID tables.
LEFT JOIN
and key_field IS NULL
.
net_clear()
which could give the error Aborted
connection
in the MySQL clients.
USE INDEX (key_list)
and IGNORE INDEX (key_list)
as
parameters in SELECT
.
DELETE
and RENAME
should now work on RAID
tables.
ALTER TABLEL tbl_name ADD (field_list)
文を許可した。
GRANT/REVOKE ALL PRIVILEGES
が GRANT OPTION
に影響しなかったのを修正。
SHOW GRANTS
.
CREATE
文での UNIQUE INDEX
の使用を許可。
mysqlhotcopy
- ローカルの MySQL データベースをバックアップする
ツール。 By Tim Bunce.
mysqlaccess
. Thanks to Steve Harvey for this.
--i-am-a-dummy
と --safe-updates
オプションを mysql
に追加。
select_limit
と max_join_size
変数を mysql
に追加。
SQL_MAX_JOIN_SIZE
と SQL_SAFE_UPDATES
.
READ LOCAL
lock that doesn't lock the table for concurrent
inserts. (This is used by mysqldump
.)
LOCK TABLES ... READ
doesn't anymore allow concurrent
inserts.
--skip-delay-key-write
を mysqld
に追加。
_rowid
can now be used as an alias for an integer type unique indexed
column.
SIGPIPE
when compiling with --thread-safe-clients
to make things safe for old clients.
LOCK TABLES
.
INSERT DELAYED
.
date_col BETWEEN const_date AND const_date
works.
NULL
in a table with
BLOB/TEXT
columns.
WHERE K1=1 and K3=2 and (K2=2 and K4=4 or K2=3 and K4=5)
source
コマンドを mysql
に追加。 これは mysql
クライアント内
で、バッチファイルを読むことができる。 Original patch by Matthew Vanecek.
WITH GRANT OPTION
オプションの致命的なバグを修正
GRANT
error when using tables from many
databases in the same query.
SELECT
when using many overlapping indexes.
MySQL should now be able to choose keys even better when there
are many keys to choose from.
SELECT * from key_part_1=const and key_part_2 > const2
VARCHAR
columns to CHAR
columns
didn't change row type from dynamic to fixed.
SELECT FLOOR(POW(2,63))
.
mysqld
の起動オプション --delay-key-write
を
--delay-key-write-for-all-tables
に変更
read-next-on-key
to HEAP
tables. This should fix all
problems with HEAP
tables when using non-UNIQUE
keys.
mysqld
に --log-slow-queries
を追加。 これは時間のかかった
全てのクエリを別のログファイルに記録する。どのくらい時間がかかったかが記される
WHERE key_column=RAND(...)
を行ったときコアを吐くバグを修正
SELECT ... LEFT JOIN ... key_col IS NULL
,
when key_col
could contain NULL
values.
LOAD DATA INFILE
.
NISAM
中のパックされたキーの削除時のバグを修正。
ORDER BY ... DESC
クエリを実行した際の ISAM
の問題を修正。
--delay-key-write
が delayed key writing を有効にしていなかったのを修正。
TEXT
column which involved only case changes.
INSERT DELAYED
doesn't update timestamps that are given.
YEARWEEK()
関数の追加と、x
, X
, v
,
V
オプションの DATE_FORMAT()
への追加。
MAX(indexed_column)
and HEAP
tables.
BLOB NULL
keys and LIKE "prefix%"
.
MyISAM
and fixed-length rows < 5 bytes.
GROUP BY
queries.
ENUM
field value
was too big.
pthread_mutex_timedwait
の問題を避けるようにした。
この関数は INSERT DELAYED
で使用されていた。 See section Linux Notes (All Linux Versions).
MyISAM
で、キーが 250 文字を超えた場合のバグを修正。
MyISAM
において、他のスレッドが読んでいるテーブルに対し、
他のスレッドが INSERT
を同時に行うことができるようになった。
max_write_lock_count
variable to mysqld
to force a
READ
lock after a certain number of WRITE
locks.
delay_key_write
on show variables
.
concurrency
変数を thread_concurrency
に改名。
LOCATE(substr,str)
, POSITION(substr IN str)
,
LOCATE(substr,str,pos)
, INSTR(str,substr)
,
LEFT(str,len)
, RIGHT(str,len)
,
SUBSTRING(str,pos,len)
, SUBSTRING(str FROM pos FOR len)
,
MID(str,pos,len)
, SUBSTRING(str,pos)
, SUBSTRING(str
FROM pos)
, SUBSTRING_INDEX(str,delim,count)
, RTRIM(str)
,
TRIM([[BOTH | TRAILING] [remstr] FROM] str)
,
REPLACE(str,from_str,to_str)
, REVERSE(str)
,
INSERT(str,pos,len,newstr)
, LCASE(str)
, LOWER(str)
,
UCASE(str)
and UPPER(str)
; patch by Wei He.
FULL
オプションを SHOW PROCESSLIST
に追加。
--verbose
オプションを mysqladmin
に追加。
HEAP
の MyISAM
への自動変換時のバグを修正。
HEAP
テーブルに対して、insert + delete + insert + scan table を行った際の
バグを修正。
REPLACE()
と LOAD DATA INFILE
のバグを修正。
mysqld
変数に interactive_timeout
を追加.
mysql_data_seek()
の引数を ulong
から ulonglong
に
変更.
mysqld
に -O lower_case_table_names={0|1}
オプションを追加。
これはテーブル名を強制的に小文字にします。
SELECT ... INTO DUMPFILE
追加。
mysqld
に --ansi
オプションを追加。 これはいくつかの関数を
ANSI SQL
互換にします。
#sql
.
`
("
in --ansi
mode).
snprintf()
when printing floats to avoid some buffer
overflows on FreeBSD.
FLOOR()
をオーバーフローセーフにした。
--quote-names
オプションを mysqldump
に追加
PRIMARY KEY NOT NULL
.
encrypt()
to be thread-safe and not reuse buffer.
mysql_odbc_escape_string()
関数が、big5 をサポートした。
FLOAT
and DOUBLE
(without any length modifiers)
no longer are fixed decimal point numbers.
FLOAT(X)
の意味を変更: X
<=24 ならば、これは FLOAT
と同じで、
24 < X
<= 53 であるならば DOUBLE
と同じになります。
DECIMAL(X)
は DECIMAL(X,0)
のエイリアスになりました。
また DECIMAL
は DECIMAL(10,0)
のエイリアスになりました。
The same goes for NUMERIC
.
ROW_FORMAT={default | dynamic | fixed | compressed}
オプションを
CREATE_TABLE
に追加.
DELETE FROM table_name
が一時テーブルで動かなかった。
CHAR_LENGTH()
関数をマルチバイトセーフに変更
ORD(string)
関数の追加.
SELECT DISTINCT ... ORDER BY RAND()
の問題を修正。
MyISAM
のレベルでのテキストサーチのパッチを追加
ALTER TABLE
didn't work.
MyISAM
で auto_increment をサブパートとして使用できるようになった:
CREATE TABLE foo (a INT NOT NULL AUTO_INCREMENT, b CHAR(5), PRIMARY KEY (b,a))
MyISAM
with packed char keys that could be NULL
.
CREATE TABLE table_name SELECT ...
時にとした場合、動かなかった。
NATIONAL
and NCHAR
when defining character columns.
This is the same as not using BINARY
.
NULL
のフィールドを PRIMARY KEY
( UNIQUE
キー) には
許さなくなった。
LAST_INSERT_ID()
if one uses this in ODBC:
WHERE auto_increment_column IS NULL
. This seems to fix some problems
WHERE auto_increment_column IS NULL
を使用して最後にレコードが挿入された後に、
SET SQL_AUTO_IS_NULL=0|1
はサーチのハンドリングの on/off になった。
concurrency
to mysqld
for Solaris.
--relative
オプションを mysqladmin
に追加。
これは extended-status
で変更のモニターをする場合、より便利になった。
COUNT(DISTINCT...)
を使用した際のバグを修正。
GBK
を追加。
LOAD DATA INFILE
を BLOB
フィールドに使用した際の問題を修正。
~
(negation) を追加。
UDF
関数での問題を修正。
DATETIME
型を TIME
フィールドに挿入するとき、'day' を
保存しようと試みなくなった。
SUM()
に影響する.)
NULL
値を持つかもしれないものに LIKE "%"
した際の問題を修正。
REVOKE ALL PRIVILEGES
が全ての権限を取り消していなかったのを修正。
SHOW GRANTS FOR user
(by Sinisa).
date_add
syntax: date/datetime + INTERVAL # interval_type
.
By Joshua Chamas.
LOAD DATA REPLACE
の権限のチェックを修正。
REGEXP
はケース非依存になった。もしバイナリ文字でない場合は。
MyISAM
中の range bug を修正。
ORDER BY
のデフォルトが再び ASC
になった。
LIMIT
を UPDATE
に追加。
mysql_change_user()
.
SHOW VARIABLES
にキャラクターセットを追加。
--[whitespace]
コメントをサポートした。
INSERT into tbl_name VALUES ()
, that is, you may now specify
an empty value list to insert a row in which each column is set to its
default value.
SUBSTRING(text FROM pos)
to conform to ANSI SQL. (Before this
construct returned the rightmost 'pos' characters).
GROUP BY
をともなった SUM()
は 0 を返すようになった。
SHOW TABLE STATUS
の出力を変更。
DELAY_KEY_WRITE
オプションを CREATE TABLE
に追加。
AUTO_INCREMENT
をいかなるキーの部分に使用できるようにした。
YEAR(NOW())
, YEAR(CURDATE())
の問題を修正。
CASE
construct.
COALESCE()
.
SELECT * FROM table_name WHERE
key_part1 >= const AND (key_part2 = const OR key_part2 = const)
. The
bug was that some rows could be duplicated in the result.
myisamchk
without -a
updated the index
distribution incorrectly.
SET SQL_LOW_PRIORITY_UPDATES=1
was causing a parse error.
WHERE
節に使用されているインデックスフィールドを更新できるようになった:
UPDATE tbl_name SET KEY=KEY+1 WHERE KEY > 100
'1999-01-00'
.
SELECT ... WHERE key_part1=const1 AND
key_part_2=const2 AND key_part1=const4 AND key_part2=const4
; indextype
should be range
instead of ref
.
egcs
1.1.2 optimizer のバグ(BLOB
使用時)を修正。
LOCK TABLES
combined with DELETE FROM table
.
MyISAM
テーブルは NULL
値と BLOB/TEXT
フィールドにキーを許すようになった。
SELECT ... FROM t1 LEFT JOIN t2 ON ... WHERE t2.not_null_column IS NULL
.
ORDER BY
and GROUP BY
can be done on functions.
ORDER BY RAND()
.
WHERE key_column = function
でインデックスが使用されるようになった。
WHERE key_column = column_name
でインデックスが使用されるようになった。
WHERE column_name IS NULL
でインデックスが使用されるようになった。
MyISAM
tables)
HEAP
temporary tables to MyISAM
tables in case of
'table is full' errors.
--init-file=file_name
オプションを mysqld
に追加。
COUNT(DISTINCT value, [value, ...])
.
CREATE TEMPORARY TABLE
now creates a temporary table, in its own
namespace, that is automatically deleted if connection is dropped.
CASE
を要求): CASE, THEN, WHEN, ELSE and END
.
EXPORT_SET()
, MD5()
.
MyISAM
)。
See section MyISAM
テーブル (3.23.0以上).
HEAP
テーブルを作成できるようになりました。
これは探索がとても速いです。
LOAD_FILE(filename)
。 これはファイルの中身を文字列値として読みます。
<=>
。 これは、 =
のように振る舞いますが、
もし両辺の引数が NULL
なら、真を返します。
これはテーブル間の変更の比較に役立ちます。
EXTRACT(interval FROM datetime)
関数の追加。
FLOAT(X)
フィールドは、保存した値を丸めません。
これは検索されたときに 科学表記 (1.0 E+10) になるかもしれません。
REPLACE
が前よりも速くなった。
LIKE
文字比較を =
のよに振る舞うように変更;
これは 'e' LIKE ''e'
が真になるということです。
(if the line doesn't display
correctly, the latter 'e' means a French 'e' with a dot above)
SHOW TABLE STATUS
はテーブルについての情報を多く出すようになりました。
LIKE
を SHOW STATUS
コマンドに追加。
SHOW COLUMNS
に Privileges 項目を追加。
SHOW INDEX
に packed
と comment
項目を追加。
CREATE TABLE ... COMMENT "xxx"
).
UNIQUE
を次のように追加:
CREATE TABLE table_name (col int not null UNIQUE)
CREATE TABLE table_name SELECT ...
CREATE TABLE IF NOT EXISTS ...
CHAR(0)
フィールドの作成を許可した。
DATE_FORMAT()
は、フォーマット文字の前に `%' が必要になった。
DELAYED
が予約語になった。 (sorry about that :( ).
analyse
, file: `sql_analyse.c'.
これはクエリのデータについて説明します。 以下の様にしてみてください:
SELECT ... FROM ... WHERE ... PROCEDURE ANALYSE([max elements,[max memory]])この プロセジャーは、テーブルのデータをチェックしたい時に、とても役立ちます!
BINARY
cast to force a string to be compared case sensitively.
--skip-show-database
オプションを mysqld
に追加。
BLOB
/TEXT
フィールドにおいて、 UPDATE
された
レコードをチェックできるようになりました。
INNER JOIN
の追加。 注意: INNER
は予約語になりました!
IP/NETMASK
として、ネットマスクを指定できます。
NOT NULL DATE/DATETIME
column with IS
NULL
, this is changed to a compare against 0
to satisfy some ODBC
applications. (By shreeve@uci.edu).
NULL IN (...)
は 0
ではなく NULL
を返します。 これは
null_column NOT IN (...)
が NULL
値にマッチしないのを確実にします。
TIME
フィールド中に、浮動小数点の値を入れるのを修正。
TIME
strings to be more strict. Now the
fractional second part is detected (and currently skipped). The
following formats are supported:
[[DAYS] [H]H:]MM:]SS[.fraction]
[[[[[H]H]H]H]MM]SS[.fraction]
DATETIME
.
LOW_PRIORITY
属性を LOAD DATA INFILE
に追加。
LOAD DATA INFILE
時に、より大きなバッファを使用するようにした。
DECIMAL(x,y)
は ANSI SQL に従って動作するようになった。
LAST_INSERT_ID()
is now updated for INSERT INTO ... SELECT
.
SELECT DISTINCT
が凄く速くなった;
これは MyISAM
の新しい UNIQUE
を使用します。
MySQL バージョン 3.22 と一つ違う点は、 DISTINCT
の出力が
ソートされないという事です。
mysql_num_fields()
を
MYSQL
ととしてコールできず、この代わりに mysql_field_count()
を
使用しなくてはなりません。
LIBEWRAP
の追加; Patch by Henning P. Schmiedehausen.
AUTO_INCREMENT
for other than numerical columns.
AUTO_INCREMENT
の使用は、フィールドを自動的に
NOT NULL
にします。
NULL
as the default value for AUTO_INCREMENT columns.
SQL_BIG_RESULT
の追加; SQL_SMALL_RESULT
がデフォルトになりました。
--enable-large-files/--disable-large-files
スイッチを configure
に
追加。 See `configure.in' for some systems where this is
automatically turned off because of broken implementations.
readline
4.0 にアップグレード
CREATE TABLE
オプション: PACK_KEYS
と CHECKSUM
.
mysqld
オプションに --default-table-type
を追加。
3.22 は 3.21 より早く、より安全なコードをもち、たくさんの新しい機能が盛り込まれています。 これらの変更を 3.21 に行わないのは、3.21 の安定度を保つためにはとても多くの変更が必要とされるからです。 これらの変更はメジャーバージョンの変更ではないので、簡単に障害もなく 3.22 にアップグレードができます。 See section バージョン 3.21 から バージョン 3.22 へのアップグレード.
3.22 は新しい DBD-mysql
(1.20xx) ドライバーのみを新しい接続プロトコルに対して使用します!
STD()
.
ISAM
library from 3.23.
INSERT DELAYED
.
LEFT JOIN
/STRAIGHT_JOIN
on a table with only one row.
GROUP BY
on TINYBLOB
columns; This
caused bugzilla to not show rows in some queries.
LOCK TABLE
SELECT DISTINCT
queries.
mysqlhotcopy
- ローカルの MySQL データベースをコピーする
ツール. By Tim Bunce.
mysqlaccess
が新しくなった. Thanks to Steve Harvey for this.
GROUP
functions.
ISAM
code when deleting rows on tables with
packed indexes.
SELECT
when using many overlapping indexes.
SELECT FLOOR(POW(2,63))
.
WITH GRANT OPTION
オプションの致命的なバグを修正.
NISAM
中のパックされたキーの削除時のバグを修正。
GROUP BY
queries.
ENUM
field value
was too big.
mysqlshutdown.exe
and mysqlwatch.exe
to the Windows
distribution.
ORDER BY
を行ったときの問題を修正
INSERT DELAYED
doesn't update timestamps that are given.
LEFT JOIN
and COUNT()
on a column which
was declared NULL
+ and it had a DEFAULT
value.
CONCAT()
をある WHERE
節で使用した際にコア・ダンプする問題を修正した。
AVG()
and STD()
with NULL
values.
ROUND()
will now work on Windows.
BLOB/TEXT
フィールドを REVERSE()
した際にコアダンプしたのを修正。
/*! */
バージョン番号 を拡張した
SUBSTRING(text FROM pos)
to conform to ANSI SQL. (Before this
construct returned the rightmost pos
characters.)
LOCK TABLES
combined with DELETE FROM table
INSERT ... SELECT
が SQL_BIG_TABLES
を使用していなかったのを修正。
SET SQL_LOW_PRIORITY_UPDATES=#
が動いてなかった。
GRANT ... IDENTIFIED BY
で変更しても直にパスワードが
反映されなかったのを修正。
SELECT * FROM table_name WHERE key_part1 >= const AND (key_part2 = const OR key_part2 = const)
DATA
は予約語でなくなった。
LOCK TABLES table_name READ; FLUSH TABLES;
を使用した際のバグ修正。
isamchk
が Windows 上で動くようになった。
libtool
1.3.2 を使用するようにアップグレード。
configure
.
--defaults-file=###
to option file handling to force use
of only one specific option file.
MySQL
バージョン 3.23 のキーワードを無視するように
CREATE
構文を拡張した。
LOCK TABLES
でロックされているテーブルに INSERT DELAYED
を
使用した際の、デッドロックの問題を修正。
DROP TABLE
を使用した際の
問題を修正。
GRANT/REVOKE
コマンドを update log に追加。
isamchk
を修正。
NATURAL LEFT JOIN
のバグを修正。
mysql_init()
の後に直接 mysql_close()
を読んだときの問題を修正。
(C API)
delayed_insert_thread
数の表示を修正。
CONCAT()
の引数を多くした場合のバグを修正。
DELETE FROM TABLE
の
問題を修正。
LEFT JOIN
involving empty tables.
mysql.db
フィールドを char(32)
から char(60)
に変更。
MODIFY
と DELAYED
は予約語でなくなった。
TIME
フィールドに日にちを入れようとしたときのバグを修正。
GRANT
コマンドで新しい MySQL ユーザーを登録した後に
Host '...' is not allowed to connect to this MySQL server
となる問題を修正。
TCP_NODELAY
を使用するように変更。 (これは TCP/IP 接続を速くします)
STD()
for big tables when result should be 0.
INSERT DELAYED
had some garbage at end in the update log.
mysql_install_db
のバグ修正。 (from 3.22.17).
BLOB
フィールドで一時テーブルが必要とされるクエリの問題を修正。
shutdown
後、全ての
スレッドが確実に死ななかった。
-O flush_time=#
オプションを mysqld
に追加。 This is mostly
useful on Windows and tells how often MySQL should close all
unused tables and flush all updated tables to disk.
VARCHAR
フィールドと CHAR
を比較した際にキーを効果的に
使用していなかったのを修正。
--log-update
を使用したときとデフォルトのデータベースを指定しないで
接続したときのコアダンプを修正した。
configure
と移植性の問題を修正した。
LEFT JOIN
on tables that had circular dependencies caused
mysqld
to hang forever.
mysqladmin processlist
could kill the server if a new user logged in.
DELETE FROM table_name WHERE key_column=column_name
が
マッチする行を1行も見つけれないのを修正
DATE_ADD(column, ...)
が動かないのを修正
INSERT DELAYED
could deadlock with status 'upgrading lock'
ENCRYPT()
を拡張。
longlong2str
は以前よりかなり速くなった。Intel x86
用に
このコードは最適化されたアセンブラで書き直した
ALTER TABLE
に MODIFY
キーワードを追加
GRANT
を IDENTIFIED BY
と共に使用した際、権限情報がフラッシュされるまで
有効にならない
SHOW STATUS
.
ORDER BY
with 'only index' optimization when there
were multiple key definitions for a used column.
DATE
and DATETIME
columns are now up to 5 times faster than
before.
INSERT DELAYED
can be used to let the client do other things while the
server inserts rows into a table.
LEFT JOIN USING (col1,col2)
が動作しなかった
LOAD DATA LOCAL INFILE
がファイルがないための理由で UNIX では動作しなかった
VARCHAR
/BLOB
での問題の修正;
error 127 がこの行を消去する場合に起きる可能性があった
BLOB/TEXT
through formulas didn't work for short (< 256 char)
strings.
GRANT
を実行した場合、そのホストからの最初のコネクションで
mysqld
が死ぬ可能性があった
ORDER BY
で使用する場合のバグを修正
name as an alias.
BENCHMARK(loop_count,expression)
function to time expressions.
mysqld
の引数がない場合を許可した。
TIMESTAMP
column to NULL
didn't record the timestamp
value in the update log.
INSERT INTO TABLE ... SELECT ... GROUP BY
.
localtime_r()
on Windows so that it will not crash
anymore if your date is > 2039, but instead will return a time of all zero.
^Z
(ASCII 26) to \Z
as ^Z
doesn't
work with pipes on Windows.
mysql_fix_privileges
は、
UDF のサポートのために、新しい項目を mysql.func
に追加する。
( type enum ('function','aggregate') NOT NULL が追加された )
NOW()
, CURDATE()
or CURTIME()
directly in a
column didn't work.
WHERE
節が無い場合、SELECT COUNT(*) ... LEFT JOIN ...
が動かなかった
pthread_cond()
on the Windows version.
get_lock()
now correctly times out on Windows!
WHERE
節で DATE_ADD()
と DATE_SUB()
を使用した際の問題を修正
GRANT ... TO user IDENTIFIED BY 'password'
構文でパスワードをセットできるようにした
SELECT
して GRANT
を確認する際のバグを修正
mysql_fix_privilege_tables
ファイルの追加。
これはクライアントパッケージに含んだため、デフォルトでは起動されない。
SQL_SMALL_RESULT
オプションを SELECT
に追加。
これは強制的に速い一時テーブルを使用する。
結果が小さいとわかっている場合に使用すると有効。
DATE_ADD
/DATE_SUB()
の結果、十分な日数を得られない場合、
日数を月の最大日にするようにした。
GRANT
がカラムをケース非依存で比較していたのを修正
ALTER TABLE
が core をはくバグが
`sql_list.h' にあったのでこれを修正
user@hostname
can now include `.' and `-'
without quotes in the context of the GRANT
, REVOKE
and
SET PASSWORD FOR ...
statements.
isamchk
を修正
mysql_fix_privilege_tables
スクリプトを実行しなくてはなりません!
これは新しい GRANT
システムのために実行します。
もしこれを行わなければ、ALTER TABLE
や CREATE INDEX
, DROP INDEX
を
実行しようとすると Access denied
になります。
USER()
を user@host
を返すように変更
PASSWORD
をセットする構文を変更
FLUSH STATUS
はほとんどのステータス変数をゼロにセットします
aborted_threads
, aborted_connects
.
connection_timeout
SET SQL_WARNINGS=1
to get a warning count also for simple
inserts.
SIGQUIT
のかわりに SIGTERM
を使用します
mysql
に オプション \G
(print vertically) 追加
SELECT HIGH_PRIORITY ...
killed mysqld
.
IS NULL
on a AUTO_INCREMENT
column in a LEFT JOIN
didn't
work as expected.
MAKE_SET()
.
safe_mysqld
で mysqld を開始させる必要があります。
しかし MySQL の RPM パッケージはサーバーをたちあげるようにしています。
--bootstrap
を mysqld
に追加。mysql_install_db
はこれを使用します。
この引数は RPM パッケージで MySQL のインストールを簡略化します。
+, - (sign and minus), *, /, %, ABS() and MOD()
のコードを修正。
BIGINT
で使用した場合の危険性を回避しました(64 bit safe).
ALTER TABLE
が mysqld をクラッシュさせるバグを修正。
INSERT
の時にしかメッセージが出ませんでした)
INSERT INTO table_name SET column=value,column=value, ...
MYSQL_INIT_COMMAND
オプションを mysql_options()
に追加。
(接続要求する場合に使用できる)
MYSQL_READ_DEFAULT_FILE
と MYSQL_READ_DEFAULT_GROUP
を
mysql_options()
に追加。
MySQL オプションファイルから以下のパラメーターを読み取る:
port
,
socket
, compress
, password
, pipe
, timeout
,
user
, init-command
, host
and database
(訳注)オプションファイルのデフォルトは /etc/my.cnf , install_directory/share/mysql/my.cnf
maybe_null
を追加
IGNORE
to INSERT
statements with many rows.
CHAR
や VARCHAR
カラムを
インデックスにしているテーブルに対して、必ず isamchk -rq
を実行すること。
mysql_setpermission
(Luuk de Boer 作)
これは指定されたデータベースに対してアクセスを許可するユーザーを
簡単に登録してくれます。
LOAD DATA INFILE
).
SHOW STATUS
での変数を増やしました。また、SHOW VARIABLES
の
ような出力フォーマットに変更しました。
extended-status
コマンドを mysqladmin
に追加。
これは新しいステイタス変数を表示します
SET SQL_LOG_UPDATE=0
caused a lockup of the server.
FLUSH [ TABLES | HOSTS | LOGS | PRIVILEGES ] [, ...]
KILL
thread_id
.
ALTER TABLE
を使用して INT
からサイズの小さい CHAR()
に
変更する場合におきていた不具合を修正。
SELECT HIGH_PRIORITY
追加。
SELECT
において、たとえ他の SELECT
を待っているスレッドがあったとしても、
WRITE LOCK
することができます。
LIKE
on
BLOB
/TEXT
columns with \0.
ESCAPE
option to LIKE
mysqladmin debug
において、より多くの出力が得られるようにした。
--flush
オプションをつけて mysqld
を起動できるようになりました。
これはアップデートが終わった後ですべてのテーブルをディスクにフラッシュします。
このオプションにより NT/Win98 上ですごく安全に動かすことができますが、
とても 遅くなります。
my_strcoll()
! The patch should always be safe to install (for any
system), but as this patch changes ISAM
internals it's not yet in the
default distribution.
DATE_ADD()
and DATE_SUB()
didn't work with group functions.
mysql
will now also try to reconnect on USE DATABASE
commands.
ORDER BY
and LEFT JOIN
and const
tables.
ORDER BY
if the first ORDER BY
column
was a key and the rest of the ORDER BY
columns wasn't part of the key.
OPTIMIZE TABLE
.
DROP TABLE
and mysqladmin shutdown
on Windows
(a fatal bug from 3.22.6).
TIME columns
and negative strings.
LIMIT
clause for the DELETE
statement.
/*! ... */
syntax to hide MySQL-specific
keywords when you write portable code. MySQL will parse the code
inside the comments as if the surrounding /*!
and */
comment
characters didn't exist.
OPTIMIZE TABLE tbl_name
can now be used to reclaim disk space
after many deletes. Currently, this uses ALTER TABLE
to re-generate
the table, but in the future it will use an integrated isamchk
for more speed.
libtool
to get the configure more portable.
UPDATE
and DELETE
operations when using
DATETIME
or DATE
keys.
mysqladmin proc
to display information about your own
threads. Only users with the PROCESS
privilege can get
information about all threads.
(In 4.0.2 one needs the SUPER
privilege for this.)
YYMMDD
, YYYYMMDD
,
YYMMDDHHMMSS
for numbers when using DATETIME
and
TIMESTAMP
types. (Formerly these formats only worked with strings.)
CLIENT_IGNORE_SPACE
to allow use of spaces
after function names and before `(' (Powerbuilder requires this).
This will make all function names reserved words.
--log-long-format
option to mysqld
to enable timestamps
and INSERT_ID's in the update log.
--where
option to mysqldump
(patch by Jim Faucette).
mysqldump
.
LOAD DATA INFILE
statement, you can now use the new LOCAL
keyword to read the file from the client. mysqlimport
will
automatically use LOCAL
when importing with the TCP/IP protocol.
DROP TABLE
, ALTER TABLE
, DELETE FROM
TABLE
and mysqladmin flush-tables
under heavy usage.
Changed locking code to get better handling of locks of different types.
DBI
to 1.00 and DBD
to 1.2.0.
mysqld
. (To avoid errors if you accidentally
try to use an old error message file.)
affected_rows()
,
insert_id()
, ...) are now of type BIGINT
to allow 64-bit values
to be used.
This required a minor change in the MySQL protocol which should affect
only old clients when using tables with AUTO_INCREMENT
values > 16M.
mysql_fetch_lengths()
has changed from uint *
to ulong *
. This may give a warning for old clients but should work
on most machines.
mysys
and dbug
libraries to allocate all thread variables
in one struct. This makes it easier to make a threaded `libmysql.dll'
library.
gethostname()
(instead of uname()
) when
constructing `.pid' file names.
COUNT()
, STD()
and AVG()
are extended to handle more than
4G rows.
-838:59:59
<= x <=
838:59:59
in a TIME
column.
TIME
column to too short a value, MySQL now
assumes the value is given as: [[[D ]HH:]MM:]SS
instead of
HH[:MM[:SS]]
.
TIME_TO_SEC()
and SEC_TO_TIME()
can now handle negative times
and hours up to 32767.
SET SQL_LOG_UPDATE={0|1}
to allow users with
the PROCESS
privilege to bypass the update log.
(Modified patch from Sergey A Mukhin violet@rosnet.net.)
LPAD()
.
BLOB
reading from
pipes safer.
-O max_connect_errors=#
option to mysqld
.
Connect errors are now reset for each correct connection.
max_allowed_packet
to 1M
in
mysqld
.
--low-priority-updates
option to mysqld
, to give
table-modifying operations (INSERT
, REPLACE
, UPDATE
,
DELETE
) lower priority than retrievals. You can now use
{INSERT | REPLACE | UPDATE | DELETE} LOW_PRIORITY ...
You can
also use SET SQL_LOW_PRIORITY_UPDATES={0|1}
to change
the priority for one thread. One side effect is that LOW_PRIORITY
is now a reserved word. :(
INSERT INTO table ... VALUES(...),(...),(...)
,
to allow inserting multiple rows with a single statement.
INSERT INTO tbl_name
is now also cached when used with LOCK TABLES
.
(Previously only INSERT ... SELECT
and LOAD DATA INFILE
were
cached.)
GROUP BY
functions with HAVING
:
mysql> SELECT col FROM table GROUP BY col HAVING COUNT(*)>0;
mysqld
will now ignore trailing `;' characters in queries. This
is to make it easier to migrate from some other SQL servers that require the
trailing `;'.
SELECT INTO OUTFILE
.
GREATEST()
and LEAST()
functions. You must now use
these instead of the MAX()
and MIN()
functions to get the
largest/smallest value from a list of values. These can now handle REAL
,
BIGINT
and string (CHAR
or VARCHAR
) values.
DAYOFWEEK()
had offset 0 for Sunday. Changed the offset to 1.
GROUP BY
columns and fields when
there is no GROUP BY
specification.
--vertical
option to mysql
, for printing results in
vertical mode.
--tmpdir
option to mysqld
, for specifying the location
of the temporary file directory.
SELECT ... FROM table WHERE auto_increment_column IS NULLto:
SELECT ... FROM table WHERE auto_increment_column == LAST_INSERT_ID()This allows some ODBC programs (Delphi, Access) to retrieve the newly inserted row to fetch the
AUTO_INCREMENT
id.
DROP TABLE
now waits for all users to free a table before deleting it.
BIN()
, OCT()
, HEX()
and CONV()
for
converting between different number bases.
SUBSTRING()
with 2 arguments.
ORDER BY
and
GROUP BY
.
mysqld
now automatically disables system locking on Linux and Windows,
and for systems that use MIT-pthreads. You can force the use of locking
with the --enable-external-locking
option.
--console
option to mysqld
, to force a console window
(for error messages) when using Windows.
DATE_ADD()
and DATE_SUB()
functions.
mysql_ping()
to the client library.
--compress
option to all MySQL clients.
byte
to char
in `mysql.h' and `mysql_com.h'.
<<
, >>
, RPAD()
and LPAD()
.
ORDER BY
to work when no records are found
when using fields that are not in GROUP BY
(MySQL extension).
--chroot
option to mysqld
, to start mysqld
in
a chroot environment (by Nikki Chumakov nikkic@cityline.ru).
--one-thread
option to mysqld
, for debugging with
LinuxThreads (or glibc
). (This replaces the -T32
flag)
DROP TABLE IF EXISTS
to prevent an error from occurring if the
table doesn't exist.
IF
and EXISTS
are now reserved words (they would have to
be sooner or later).
mysqldump
.
mysql_ping()
.
mysql_init()
and mysql_options()
.
You now MUST call mysql_init()
before you call
mysql_real_connect()
.
You don't have to call mysql_init()
if you only use
mysql_connect()
.
mysql_options(...,MYSQL_OPT_CONNECT_TIMEOUT,...)
so you can set a
timeout for connecting to a server.
--timeout
option to mysqladmin
, as a test of
mysql_options()
.
AFTER column
and FIRST
options to
ALTER TABLE ... ADD columns
.
This makes it possible to add a new column at some specific location
within a row in an existing table.
WEEK()
now takes an optional argument to allow handling of weeks when
the week starts on Monday (some European countries). By default,
WEEK()
assumes the week starts on Sunday.
TIME
columns weren't stored properly (bug in MySQL Version 3.22.0).
UPDATE
now returns information about how many rows were
matched and updated, and how many ``warnings'' occurred when doing the update.
FORMAT(-100,2)
.
ENUM
and SET
columns were compared in binary (case-sensitive)
fashion; changed to be case-insensitive.
mysql_real_connect()
call is changed to:
mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, uint port, const char *unix_socket, uint client_flag)
accept()
thread. This fixes permanently the telnet bug
that was a topic on the mail list some time ago.
mysqld
now has a local hostname
resolver cache so connections should actually be faster than before,
even with this feature.
tbl_name@db_name
or db_name.tbl_name
. This makes it possible to
give a user read access to some tables and write access to others simply by
keeping them in different databases!
--user
option to mysqld
, to allow it to run
as another Unix user (if it is started as the Unix root
user).
mysqladmin password 'new_password'
. This uses encrypted passwords
that are not logged in the normal MySQL log!
SELECT
code to handle some very specific queries
involving group functions (like COUNT(*)
) without a GROUP BY
but
with HAVING
. The following now works:
mysql> SELECT COUNT(*) as C FROM table HAVING C > 1;
malloc()
.
-T32
option to mysqld
, for running all queries under the
main thread. This makes it possible to debug mysqld
under Linux with
gdb
!
not_null_column IS NULL
(needed for some Access
queries).
STRAIGHT_JOIN
to be used between two tables to force the optimizer
to join them in a specific order.
VARCHAR
rather than CHAR
and
the column type is now VARCHAR
for fields saved as VARCHAR
.
This should make the MyODBC driver better, but may break some old
MySQL clients that don't handle FIELD_TYPE_VARCHAR
the same
way as FIELD_TYPE_CHAR
.
CREATE INDEX
and DROP INDEX
are now implemented through
ALTER TABLE
.
CREATE TABLE
is still the recommended (fast) way to create indexes.
--set-variable
option wait_timeout
to mysqld
.
mysqladmin processlist
to show how long a query
has taken or how long a thread has slept.
show variables
and some new to
show status
.
YEAR
. YEAR
is stored in 1 byte with allowable
values of 0, and 1901 to 2155.
DATE
type that is stored in 3 bytes rather than 4 bytes.
All new tables are created with the new date type if you don't use the
--old-protocol
option to mysqld
.
Error from table handler: #
on some operating systems.
--enable-assembler
option to configure
, for x86 machines
(tested on Linux + gcc
). This will enable assembler functions for the
most important string functions for more speed!
Version 3.21 is quite old now, and should be avoided if possible. This information is kept here for historical purposes only.
SIGHUP
to mysqld
;
mysqld
core dumped when starting from boot on some systems.
DELETE FROM tbl_name
without a WHERE
condition is now done the
long way when you use LOCK TABLES
or if the table is in use, to
avoid race conditions.
INSERT INTO TABLE (timestamp_column) VALUES (NULL);
didn't set timestamp.
mysqladmin
refresh
often. This could in some very rare cases corrupt the header of the
index file and cause error 126 or 138.
refresh()
when running with the
--skip-external-locking
option. There was a ``very small'' time gap after
a mysqladmin refresh
when a table could be corrupted if one
thread updated a table while another thread did mysqladmin
refresh
and another thread started a new update ont the same table
before the first thread had finished. A refresh (or
--flush-tables
) will now not return until all used tables are
closed!
SELECT DISTINCT
with a WHERE
clause that didn't match any rows
returned a row in some contexts (bug only in 3.21.31).
GROUP BY
+ ORDER BY
returned one empty row when no rows where
found.
Use_count: Wrong count for ...
in the error log file.
TINYINT
type on Irix.
LEFT("constant_string",function)
.
FIND_IN_SET()
.
LEFT JOIN
core dumped if the second table is used with a constant
WHERE/ON
expression that uniquely identifies one record.
DATE_FORMAT()
and incorrect dates.
DATE_FORMAT()
now ignores '%'
to make it possible to extend
it more easily in the future.
mysql
now returns an exit code > 0 if the query returned an error.
mysql
client.
By Tommy Larsen tommy@mix.hive.no.
safe_mysqld
to redirect startup messages to
'hostname'.err
instead
of 'hostname'.log
to reclaim file space on mysqladmin refresh
.
ENUM
always had the first entry as default value.
ALTER TABLE
wrote two entries to the update log.
sql_acc()
now closes the mysql
grant tables after a reload to
save table space and memory.
LOAD DATA
to use less memory with tables and BLOB
columns.
SELECT
problem with LEFT()
when using the czech
character set.
isamchk
; it couldn't repair a packed table in a very
unusual case.
SELECT
statements with &
or |
(bit functions) failed on
columns with NULL
values.
LOCK TABLES
+ DELETE from tbl_name
never removed locks properly.
OR
function.
umask()
and creating new databases.
SELECT ... INTO OUTFILE ...
MIN(integer)
or MAX(integer)
in
GROUP BY
.
WEEK("XXXX-xx-01")
.
Error from table handler: #
on some operating systems.
GET_LOCK(string,timeout)
,
RELEASE_LOCK(string)
.
Opened_tables
to show status
.
mysqld
through telnet + TCP/IP.
WHERE key_part_1 >= something AND key_part_2 <= something_else
.
configure
for detection of FreeBSD 3.0 9803xx and above
WHERE
with string_col_key = constant_string
didn't always
find all rows if the column had many values differing only with
characters of the same sort value (like e and 'e).
umask()
to make log files non-readable for normal users.
--old-protocol
option to mysqld
.
SELECT
which matched all key fields returned the values in the
case of the matched values, not of the found values. (Minor problem.)
FROM_DAYS(0)
now returns "0000-00-00".
DATE_FORMAT()
, PM and AM were swapped for hours 00 and 12.
BLOB
/TEXT
in GROUP BY
with many
tables.
ENUM
field that is not declared NOT NULL
has NULL
as
the default value.
(Previously, the default value was the first enumeration value.)
INDEX (Organisation,Surname(35),Initials(35))
.
SELECT ... FROM many_tables
much faster.
accept()
to possibly fix some problems on some
Linux machines.
typedef 'string'
to typedef 'my_string'
for better
portability.
isamchk
. Try isamchk --help
.
filesort()
didn't work.
Affects DISTINCT
, ORDER BY
and GROUP BY
on 64-bit
processors.
SELECT
on the
table.
OR
operators on key parts
inside each other.
MIN()
and MAX()
to work properly with strings and
HAVING
.
0664
to 0660
.
LEFT JOIN
and constant expressions in the ON
part.
configure
now works better on OSF/1 (tested on 4.0D).
LIKE
optimization with international character
support.
DBI
to 0.93.
TIME
, DATE
, TIMESTAMP
, TEXT
, BIT
,
ENUM
, NO
, ACTION
, CHECK
, YEAR
,
MONTH
, DAY
, HOUR
, MINUTE
, SECOND
,
STATUS
, VARIABLES
.
TIMESTAMP
to NULL
in LOAD DATA INFILE ...
didn't
set the current time for the TIMESTAMP
.
BETWEEN
to recognise binary strings. Now BETWEEN
is
case-sensitive.
--skip-thread-priority
option to mysqld
, for systems
where mysqld
's thread scheduling doesn't work properly (BSDI 3.1).
DAYNAME()
and MONTHNAME()
.
TIME_FORMAT()
. This works like DATE_FORMAT()
,
but takes a time string ('HH:MM:DD'
) as argument.
OR
s of key parts
inside AND
s.
variables
command to mysqladmin
.
ALTER TABLE
to work with Windows (Windows can't rename
open files). Also fixed a couple of small bugs in the Windows version.
crash-me
and the benchmarks on
the following platforms: SunOS 5.6 sun4u, SunOS 5.5.1 sun4u, SunOS 4.14 sun4c,
SunOS 5.6 i86pc, Irix 6.3 mips5k, HP-UX 10.20 hppa, AIX 4.2.1 ppc,
OSF/1 V4.0 alpha, FreeBSD 2.2.2 i86pc and BSDI 3.1 i386.
COUNT(*)
problems when the WHERE
clause didn't match any
records. (Bug from 3.21.17.)
NULL = NULL
is true. Now you must use IS NULL
or IS NOT NULL
to test whether a value is NULL
.
(This is according to ANSI SQL but may break
old applications that are ported from mSQL
.)
You can get the old behaviour by compiling with -DmSQL_COMPLIANT
.
LEFT OUTER JOIN
clauses.
ORDER BY
on string formula with possible NULL
values.
DAYOFYEAR()
, DAYOFMONTH()
, MONTH()
,
YEAR()
, WEEK()
, QUARTER()
, HOUR()
, MINUTE()
,
SECOND()
and FIND_IN_SET()
.
SHOW VARIABLES
.
mysql> SELECT 'first ' 'second'; -> 'first second'
mysqlaccess
to 2.02.
LIKE
.
WHERE data_field = date_field2 AND date_field2 = constant
.
SHOW STATUS
command.
mysqladmin stat
to return the right number of queries.
AUTO_INCREMENT
attribute or is a TIMESTAMP
. This is needed for
the new Java driver.
configure
bugs and increased maximum table size
from 2G to 4G.
DBD
to 1.1823. This version implements mysql_use_result
in DBD-Mysql
.
REVERSE()
(by Zeev Suraski).
DBI
to 0.91.
LEFT OUTER JOIN
.
CROSS JOIN
syntax. CROSS
is now a reserved word.
yacc
/bison
stack allocation to be even safer and to allow
MySQL to handle even bigger expressions.
ORDER BY
was slow when used with key ranges.
--with-unix-socket-path
to avoid
confusion.
LEFT OUTER JOIN
.
LEFT
, NATURAL
,
USING
.
MYSQL_HOST
as the default host if it's defined.
SELECT col_name, SUM(expr)
now returns NULL
for col_name
when there are matching rows.
BLOB
s with ASCII
characters over 127.
mysqld
restart if one thread was reading data that another thread modified.
LIMIT offset,count
didn't work in INSERT ... SELECT
.
POWER()
, SPACE()
,
COT()
, DEGREES()
, RADIANS()
, ROUND(2 arg)
and TRUNCATE()
.
LOCATE()
parameters were
swapped according to ODBC standard. Fixed.
TIME_TO_SEC()
.
NOT NULL
fields.
UPDATE SET ...
statements.
BLOB
and TEXT
, to
be compatible with mysqldump
.
mysqlperl
is now from
Msql-Mysql-modules. This means that connect()
now takes
host
, database
, user
, password
arguments! The old
version took host
, database
, password
, user
.
DATE '1997-01-01'
, TIME '12:10:10'
and
TIMESTAMP '1997-01-01 12:10:10'
formats required by ANSI SQL.
Warning: Incompatible change! This has the unfortunate
side-effect that you no longer can have columns named DATE
, TIME
or TIMESTAMP
. :( Old columns can still be accessed through
tablename.columnname
!)
make
programs trying to rebuild it.
readline
library upgraded to version 2.1.
DBI
/DBD
is now included in the distribution. DBI
is now the recommended way to connect to MySQL from Perl.
DBD
, with test results from
mSQL
2.0.3, MySQL, PostgreSQL 6.2.1 and Solid server 2.2.
crash-me
is now included with the benchmarks; This is a Perl program
designed to find as many limits as possible in a SQL server. Tested with
mSQL
, PostgreSQL, Solid and MySQL.
mysql
command line tool, by Zeev
Suraski and Andi Gutmans.
REPLACE
that works like INSERT
but
replaces conflicting records with the new record. REPLACE INTO
TABLE ... SELECT ...
works also.
CREATE DATABASE db_name
and DROP
DATABASE db_name
.
RENAME
option to ALTER TABLE
: ALTER TABLE name
RENAME TO new_name
.
make_binary_distribution
now includes `libgcc.a' in
`libmysqlclient.a'. This should make linking work for people who don't
have gcc
.
net_write()
to my_net_write()
because of a name
conflict with Sybase.
DAYOFWEEK()
compatible with ODBC.
bison
memory overrun checking to make MySQL
safer with weird queries.
configure
problems on some platforms.
DATE_FORMAT()
.
NOT IN
.
{fn now() }
DATE
and TIME
values with NULL
.
FLOAT
. Previously, the
values were converted to INT
s before sorting.
key_column=constant
.
DOUBLE
values sorted on integer results instead.
mysql
no longer requires a database argument.
HAVING
should be. According to ANSI, it should
be after GROUP BY
but before ORDER BY
. MySQL Version 3.20
incorrectly had it last.
USE DATABASE
to start using another database.
mysqld
doesn't crash even if you haven't done a
ulimit -n 256
before starting mysqld
.
errno
.
This makes Linux systems much safer!
SELECT
.
LIKE
on number key.
--table
option to mysql
to print in table format.
Moved time and row information after query result.
Added automatic reconnect of lost connections.
!=
as a synonym for <>
.
VERSION()
to make easier logs.
ftruncate()
call in MIT-pthreads. This made isamchk
destroy the `.ISM' files on (Free)BSD 2.x systems.
__P_
patch in MIT-pthreads.
NULL
if the returned string should be longer than max_allowed_packet
bytes.
INTERVAL
type to ENUM
, because
INTERVAL
is used in ANSI SQL.
JOIN
+ GROUP
+ INTO OUTFILE
,
the result wasn't grouped.
LIKE
with '_'
as last character didn't work. Fixed.
TRIM()
function.
CURTIME()
.
ENCRYPT()
function by Zeev Suraski.
FOREIGN KEY
syntax skipping. New reserved words:
MATCH
, FULL
, PARTIAL
.
mysqld
now allows IP number and hostname for the --bind-address
option.
SET CHARACTER SET cp1251_koi8
to enable conversions of
data to and from the cp1251_koi8
character set.
CREATE COLUMN
syntax of NOT NULL
columns to be after
the DEFAULT
value, as specified in the ANSI SQL standard. This will
make mysqldump
with NOT NULL
and default values incompatible with
MySQL Version 3.20.
ALTER TABLE tbl_name ALTER COLUMN col_name SET DEFAULT
NULL
.
CHAR
and BIT
as synonyms for CHAR(1)
.
SELECT
privilege.
INSERT ... SELECT ... GROUP BY
didn't work in some cases. An
Invalid use of group function
error occurred.
LIMIT
, SELECT
now always uses keys instead of record
scan. This will give better performance on SELECT
and a WHERE
that matches many rows.
BIT_OR()
and BIT_AND()
.
CHECK
and REFERENCES
.
CHECK
is now a reserved word.
ALL
option to GRANT
for better compatibility. (GRANT
is still a dummy function.)
ORDER BY
and GROUP BY
with NULL
columns.
LAST_INSERT_ID()
SQL function to retrieve last
AUTO_INCREMENT
value. This is intended for clients to ODBC that can't use the
mysql_insert_id()
API function, but can be used by any client.
--flush-logs
option to mysqladmin
.
STATUS
to mysql
.
ORDER BY
/GROUP BY
because of bug in gcc
.
INSERT ... SELECT ... GROUP BY
.
mysqlaccess
.
CREATE
now supports all ODBC types and the mSQL
TEXT
type.
All ODBC 2.5 functions are also supported (added REPEAT
). This provides
better portability.
TINYTEXT
, TEXT
, MEDIUMTEXT
and
LONGTEXT
. These are actually BLOB
types, but all searching is
done in case-insensitive fashion.
BLOB
fields are now TEXT
fields. This only
changes that all searching on strings is done in case-sensitive fashion.
You must do an ALTER TABLE
and change the field type to BLOB
if you want to have tests done in case-sensitive fashion.
configure
issues.
test-select
works.
--enable-unix-socket=pathname
option to configure
.
SUM()
functions.
For example, you can now use SUM(column)/COUNT(column)
.
PI()
, ACOS()
, ASIN()
, ATAN()
, COS()
,
SIN()
and TAN()
.
net_print()
in `procedure.cc'.
SELECT ... INTO OUTFILE
syntax.
GROUP BY
and SELECT
on key with many values.
mysql_fetch_lengths()
sometimes returned incorrect lengths when you used
mysql_use_result()
. This affected at least some cases of
mysqldump --quick
.
WHERE const op field
.
NULL
fields.
--pid-file=#
option to mysqld
.
FROM_UNIXTIME()
, originally by Zeev Suraski.
BETWEEN
in range optimizer (did only test = of the first
argument).
mysql_errno()
, to get the error number of
the error message. This makes error checking in the client much easier.
This makes the new server incompatible with the 3.20.x server when running
without --old-protocol
. The client code is backward-compatible.
More information can be found in the `README' file!
sigwait
and sigset
defines).
configure
should now be able to detect the last argument to
accept()
.
-O tmp_table_size=#
option to mysqld
.
FROM_UNIXTIME(timestamp)
which returns a date string in
'YYYY-MM-DD HH:MM:DD'
format.
SEC_TO_TIME(seconds)
which returns a string in
'HH:MM:SS'
format.
SUBSTRING_INDEX()
, originally by Zeev Suraski.
mysqld
doesn't work on it yet.
pthread_create
to work.
mysqld
doesn't accept hostnames that start with digits followed by a
'.'
, because the hostname may look like an IP number.
--skip-networking
option to mysqld
, to allow only socket
connections. (This will not work with MIT-pthreads!)
free()
that killed the server on
CREATE DATABASE
or DROP DATABASE
.
mysqld
-O
options to better names.
-O join_cache_size=#
option to mysqld
.
-O max_join_size=#
option to mysqld
, to be able to set a
limit how big queries (in this case big = slow) one should be able to handle
without specifying SET SQL_BIG_SELECTS=1
. A # = is about 10
examined records. The default is ``unlimited''.
TIME
, DATE
, DATETIME
or TIMESTAMP
column to a constant, the constant is converted to a time value before
performing the comparison.
This will make it easier to get ODBC (particularly Access97) to work with
the above types. It should also make dates easier to use and the comparisons
should be quicker than before.
query()
in
mysqlperl
to take a query with \0
in it.
YYMMDD
) didn't work.
UPDATE
clause.
SELECT * INTO OUTFILE
, which didn't correctly if the outfile already
existed.
mysql
now shows the thread ID when starting or doing a reconnect.
--new
, but it crashes core a lot yet...
isam
library should be relatively 64-bit clean.
isamchk
which can detect and fix more problems.
isamlog
.
mysqladmin
: you can now do mysqladmin kill 5,6,7,8
to kill
multiple threads.
-O backlog=#
option to mysqld
.
ALTER TABLE
now returns warnings from field conversions.
ASCII()
.
BETWEEN(a,b,c)
. Use the standard ANSI
syntax instead: expr BETWEEN expr AND expr
.
SUM()
functions.
tbl_name.field_name
in UPDATE
.
SELECT DISTINCT
when using 'hidden group'. For example:
mysql> SELECT DISTINCT MOD(some_field,10) FROM test -> GROUP BY some_field;Note:
some_field
is normally in the SELECT
part. ANSI SQL should
require it.
INTERVAL
, EXPLAIN
, READ
,
WRITE
, BINARY
.
CHAR(num,...)
.
IN
. This uses a binary search to find a match.
LOCK TABLES tbl_name [AS alias] {READ|WRITE} ...
--log-update
option to mysqld
, to get a log suitable for
incremental updates.
EXPLAIN SELECT ...
to get information about how the
optimizer will do the join.
FIELD_TYPE_TINY_BLOB
, FIELD_TYPE_MEDIUM_BLOB
,
FIELD_TYPE_LONG_BLOB
or FIELD_TYPE_VAR_STRING
(as
previously returned by mysql_list_fields
). You should instead only use
FIELD_TYPE_BLOB
or FIELD_TYPE_STRING
. If you want exact
types, you should use the command SHOW FIELDS
.
0x######
which can be used as a string
(default) or a number.
FIELD_TYPE_CHAR
is renamed to FIELD_TYPE_TINY
.
DEFAULT
values no longer need to be NOT NULL
.
ENUM
SET
double
or long long
.
This will provide the full 64-bit range with bit functions and fix some
conversions that previously could result in precision losses. One should
avoid using unsigned long long
columns with full 64-bit range
(numbers bigger than 9223372036854775807) because calculations are done
with signed long long
.
ORDER BY
will now put NULL
field values first. GROUP BY
will also work with NULL
values.
WHERE
with expressions.
mysql> SELECT * FROM tbl_name -> WHERE key_part_1="customer" -> AND key_part_2>=10 AND key_part_2<=10;
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.
-p#
(remove #
directories from path) to isamlog
.
All files are written with a relative path from the database directory
Now mysqld
shouldn't crash on shutdown when using the
--log-isam
option.
mysqlperl
version. It is now compatible with msqlperl-0.63
.
DBD
module available.
STD()
(standard deviation).
mysqld
server is now compiled by default without debugging
information. This will make the daemon smaller and faster.
--basedir
option to
mysqld
. All other paths are relative in a normal installation.
BLOB
columns sometimes contained garbage when used with a SELECT
on more than one table and ORDER BY
.
GROUP BY
work as expected
(ANSI SQL extension).
Example:
mysql> SELECT id,id+1 FROM table GROUP BY id;
MYSQL_PWD
was reversed. Now MYSQL_PWD
is
enabled as default in the default release.
mysqld
to core dump with
Arithmetic error on SPARC-386.
--unbuffered
option to mysql
, for new mysqlaccess
.
BLOB
columns and the functions IS NULL
and
IS NOT NULL
in the WHERE
clause.
max_allowed_packet
is now 64K for
the server and 512K for the client. This is mainly used to catch
incorrect packets that could trash all memory. The server limit may be
changed when it is started.
safe_mysqld
to check for running daemon.
ELT()
function is renamed to FIELD()
. The new
ELT()
function returns a value based on an index: FIELD()
is the inverse of ELT()
Example: ELT(2,"A","B","C")
returns
"B"
. FIELD("B","A","B","C")
returns 2
.
COUNT(field)
, where field
could have a NULL
value, now
works.
SELECT ... GROUP BY
.
WHERE
with many unoptimizable brace levels.
get_hostname
, only the IP is checked.
Previously, you got Access denied
.
INSERT INTO ... SELECT ... WHERE
could give the error
Duplicated field
.
safe_mysqld
to make it ``safer''.
LIKE
was case-sensitive in some places and case-insensitive in others.
Now LIKE
is always case-insensitive.
'#'
anywhere on the line.
SET SQL_SELECT_LIMIT=#
. See the FAQ for more details.
mysqlaccess
script.
FROM_DAYS()
and WEEKDAY()
to also take a full
TIMESTAMP
or DATETIME
as argument. Before they only took a
number of type YYYYMMDD
or YYMMDD
.
UNIX_TIMESTAMP(timestamp_column)
.
mysqld
to work around a bug in MIT-pthreads. This makes multiple
small SELECT
operations 20 times faster. Now lock_test.pl
should
work.
mysql_FetchHash(handle)
to mysqlperl
.
mysqlbug
script is now distributed built to allow for reporting
bugs that appear during the build with it.
getpwuid()
instead of
cuserid()
.
SELECT
optimizer when using many tables with the same
column used as key to different tables.
latin2
and Russian KOI8
character tables.
GRANT
command to satisfy Powerbuilder.
packets out of order
when using MIT-pthreads.
fcntl()
fails. Thanks to Mike Bretz for finding this bug.
termbits
from `mysql.cc'. This conflicted with
glibc
2.0.
SELECT
as superuser without a database.
SELECT
with group calculation to outfile.
-p
or --password
option to mysql
without
an argument, the user is solicited for the password from the tty.
MYSQL_PWD
(by Elmar Haneke).
kill
to mysqladmin
to kill a specific
MySQL thread.
AUTO_INCREMENT
key with ALTER_TABLE
.
AVG()
gave too small value on some SELECT
s with
GROUP BY
and ORDER BY
.
DATETIME
type (by Giovanni Maruzzelli
maruzz@matrice.it).
DONT_USE_DEFAULT_FIELDS
works.
CREATE INDEX
.
DATE
, TIME
and
TIMESTAMP
.
OR
of multiple tables (gave empty set).
DATE
and TIME
types.
SELECT
with AND
-OR
levels.
LIMIT
and ORDER BY
.
ORDER BY
and GROUP BY
on items that aren't in the
SELECT
list.
(Thanks to Wim Bonis bonis@kiss.de, for pointing this out.)
INSERT
.
SELECT ... WHERE ... = NULL
.
glibc
2.0. To get glibc
to work, you should
add the `gibc-2.0-sigwait-patch' before compiling glibc
.
ALTER TABLE
when changing a NOT NULL
field to
allow NULL
values.
CREATE TABLE
.
CREATE TABLE
now allows FLOAT(4)
and FLOAT(8)
to mean
FLOAT
and DOUBLE
.
mysqlaccess
by Yves.Carlier@rug.ac.be.
This program shows the access rights for a specific user and the grant
rows that determine this grant.
WHERE const op field
(by bonis@kiss.de).
SELECT ... INTO OUTFILE
, all temporary tables are ISAM
instead of HEAP to allow big dumps.
ALTER TABLE
according to SQL92.
--port
and --socket
options to all utility programs and
mysqld
.
readdir_r()
. Now mysqladmin create database
and mysqladmin drop database
should work.
tempnam()
. This should fix the ``sort
aborted'' bug.
sql_update
. This fixed slow updates
on first connection. (Thanks to Vaclav Bittner for the test.)
INSERT INTO ... SELECT ...
MEDIUMBLOB
fixed.
ALTER TABLE
and BLOB
s.
SELECT ... INTO OUTFILE
now creates the file in the current
database directory.
DROP TABLE
now can take a list of tables.
DESCRIBE
(DESC
).
make_binary_distribution
.
configure
's
C++ link test.
--without-perl
option to configure
.
ALTER TABLE
didn't copy null bit. As a result, fields that were allowed
to have NULL
values were always NULL
.
CREATE
didn't take numbers as DEFAULT
.
ALTER TABLE
and multi-part keys.
ALTER TABLE
, SELECT ... INTO OUTFILE
and
LOAD DATA INFILE
.
NOW()
.
File_priv
to mysql/user
table.
add_file_priv
which adds the new field File_priv
to the user
table. This script must be executed if you want to
use the new SELECT ... INTO
and LOAD DATA INFILE ...
commands
with a version of MySQL earlier than 3.20.7.
lock_test.pl
test fail.
status
command to mysqladmin
for short logging.
-k
option to mysqlshow
, to get key information for a table.
mysqldump
.
configure
cannot find a -lpthreads
library.
program --help
.
RAND([init])
.
sql_lex
to handle \0
unquoted, but the client can't send
the query through the C API, because it takes a str pointer.
You must use mysql_real_query()
to send the query.
mysql_get_client_info()
.
mysqld
now uses the N_MAX_KEY_LENGTH
from `nisam.h' as
the maximum allowable key length.
mysql> SELECT filter_nr,filter_nr FROM filter ORDER BY filter_nr;Previously, this resulted in the error:
Column: 'filter_nr' in order clause is ambiguous
.
mysql
now outputs '\0'
, '\t'
, '\n'
and '\\'
when encountering ASCII 0, tab, newline or '\'
while writing
tab-separated output.
This is to allow printing of binary data in a portable format.
To get the old behaviour, use -r
(or --raw
).
mysql_fetch_lengths(MYSQL_RES *)
, which
returns an array of column lengths (of type uint
).
IS NULL
in WHERE
clause.
SELECT
option STRAIGHT_JOIN
to tell the optimizer that
it should join tables in the given order.
'--'
in `mysql.cc'
(Postgres syntax).
SELECT
expressions and table columns in a SELECT
which are not used in the group part. This makes it efficient to implement
lookups. The column that is used should be a constant for each group because
the value is calculated only once for the first row that is found for a group.
mysql> SELECT id,lookup.text,SUM(*) FROM test,lookup -> WHERE test.id=lookup.id GROUP BY id;
SUM(function)
(could cause a core dump).
AUTO_INCREMENT
placement in the SQL query:
INSERT INTO table (auto_field) VALUES (0);inserted 0, but it should insert an
AUTO_INCREMENT
value.
mysql
now allows doubled ''
or ""
within strings for
embedded '
or "
.
EXP()
, LOG()
, SQRT()
, ROUND()
, CEILING()
.
configure
source now compiles a thread-free client library
-lmysqlclient
. This is the only library that needs to be linked
with client applications. When using the binary releases, you must
link with -lmysql -lmysys -ldbug -lmystrings
as before.
readline
library from bash-2.0
.
configure
and makefiles (and related source).
VPATH
. Tested with GNU Make 3.75.
safe_mysqld
and mysql.server
changed to be more compatible
between the source and the binary releases.
LIMIT
now takes one or two numeric arguments.
If one argument is given, it indicates the maximum number of rows in
a result. If two arguments are given, the first argument indicates the offset
of the first row to return, the second is the maximum number of rows.
With this it's easy to do a poor man's next page/previous page WWW
application.
FIELDS()
to ELT()
.
Changed SQL function INTERVALL()
to INTERVAL()
.
SHOW COLUMNS
a synonym for SHOW FIELDS
.
Added compatibility syntax FRIEND KEY
to CREATE TABLE
. In
MySQL, this creates a non-unique key on the given columns.
CREATE INDEX
and DROP INDEX
as compatibility functions.
In MySQL, CREATE INDEX
only checks if the index exists and
issues an error if it doesn't exist. DROP INDEX
always succeeds.
sql_acl
(core on new connection).
host
, user
and db
tables from database test
in the distribution.
FIELD_TYPE_CHAR
can now be signed (-128 to 127) or unsigned (0 to 255)
Previously, it was always unsigned.
CONCAT()
and WEEKDAY()
.
mysqld
to be compiled with SunPro
compiler.
'('
immediately after the function name
(no intervening space).
For example, 'USER('
is regarded as beginning a function call, and
'USER ('
is regarded as an identifier USER
followed by a
'('
, not as a function call.
configure
and Automake.
It will make porting much easier. The readline
library is included
in the distribution.
DBD
will follow when the new DBD
code
is ported.
mysqld
can now be started with Swedish
or English (default) error messages.
INSERT()
, RTRIM()
, LTRIM()
and
FORMAT()
.
mysqldump
now works correctly for all field types (even
AUTO_INCREMENT
). The format for SHOW FIELDS FROM tbl_name
is changed so the Type
column contains information suitable for
CREATE TABLE
. In previous releases, some CREATE TABLE
information had to be patched when re-creating tables.
BLOB
and TIMESTAMP
) are corrected.
TIMESTAMP
now returns different date information depending on its
create length.
'_'
.
Version 3.19 is quite old now, and should be avoided if possible. This information is kept here for historical purposes only.
DATABASE()
, USER()
, POW()
,
LOG10()
(needed for ODBC).
WHERE
with an ORDER BY
on fields from only one table,
the table is now preferred as first table in a multi-join.
HAVING
and IS NULL
or IS NOT NULL
now works.
SUM()
,
AVG()
...) didn't work together. Fixed.
mysqldump
: Didn't send password to server.
'Locked'
to process list as info if a query is
locked by another query.
IF(arg,syntax_error,syntax_error)
crashed.
CEILING()
, ROUND()
, EXP()
, LOG()
and SQRT()
.
BETWEEN
to handle strings.
SELECT
with grouping on BLOB
columns not to return
incorrect BLOB
info. Grouping, sorting and distinct on BLOB
columns will not yet work as
expected (probably it will group/sort by the first 7 characters in the
BLOB
). Grouping on formulas with a fixed string size (use MID()
on a BLOB
) should work.
BLOB
fields, the BLOB
was garbage on output.
DISTINCT
with calculated columns.
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.2
と autoconf-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_alarm
とmysys/thr_clock
が動くかどうかチェックしてください。これにより貴方のインストールしたthread環境の動作可能性が多少でもあるのかどうかを確かめることができます。
もしあなたが 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 TABLE
か
myisamchk
でテーブルを修復し、最適化を試みるべきです。
遅いクエリは、 EXPLAIN
でもチェックできます。
See section データベース管理. You should also
check the slow queries with EXPLAIN
.
このマニュアルの OS 固有の問題 の節も読むべきです。 See section Operating System Specific Notes.
もしあるとても特殊な問題があれば、あなたは、いつも MySQL を
デバッグするよう試みることができます。 これを行うには、 MySQL を
--with-debug
オプションか --with-debug=full
オプション付きで
configure しなくてはなりません。
MySQL がデバッギングを有効にしてコンパイルされているかを
知るには、 mysqld --help
とします。 もし --debug
フラグが
リストされていればデバッグが有効です。 mysqladmin ver
も
mysqld
のバージョンをリストできます。 この場合は
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.
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.
ほとんどのシステムでは、もし 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.
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:
mysqld
server:
nm -n libexec/mysqld > /tmp/mysqld.symNote 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
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 バグや問題を報告する方法.
--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.
もし不正なテーブルをえたり、 mysqld
が常にいくつかの update コマンドで
失敗するなら、以下のようにしてこのバグの再現をテストします:
mysqladmin shutdown
).
myisamchk -s database/*.MYI
で全テーブルをチェック.
myisamchk -r database/table.MYI
で悪いテーブルを修正。
mysqld
with --log-bin
. See section The Binary Update Log バイナリ更新ログ (3.23.15以上).
If you want to find a query that crashes mysqld
, you should use
--log --log-bin
.
mysqld server
を停止。
mysqld
server を --log-bin
なしで 起動。
mysqlbinlog update-log-file | mysql
.
The update log is saved in the MySQL database directory with
the name hostname-bin.#
.
mysqld
to die with the
above command, you have found reproducible bug that should be easy to
fix! FTP the tables and the binary log to
ftp://support.mysql.com/pub/mysql/secret/ and send a mail to
bugs@lists.mysql.com or (if you are a support customer) to
support@mysql.com about the problem and the MySQL team
will fix it as soon as possible.
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.
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 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
.
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 INSERT
s 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:
GROUP
BY
on a large part of the data or if one has to often scan the whole table.
Table locks are superior to page level / row level locks in the following cases:
UPDATE table_name SET column=value WHERE unique_key# DELETE FROM table_name WHERE unique_key=#
SELECT
combined with INSERT
(and very few UPDATE
s
and DELETE
s).
GROUP BY
on the whole table without any writers.
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 最適化に関するその他の助言.
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:
-DHAVE_rts_threads
.
thr_alarm
.
thr_alarm
. If it runs without any ``warning'', ``error'' or aborted
messages, you are on the right track. Here is a successful run on
Solaris:
Main thread: 1 Thread 0 (5) started Thread: 5 Waiting process_alarm Thread 1 (6) started Thread: 6 Waiting process_alarm process_alarm thread_alarm Thread: 6 Slept for 1 (1) sec Thread: 6 Waiting process_alarm process_alarm thread_alarm Thread: 6 Slept for 2 (2) sec Thread: 6 Simulation of no alarm needed Thread: 6 Slept for 0 (3) sec Thread: 6 Waiting process_alarm process_alarm thread_alarm Thread: 6 Slept for 4 (4) sec Thread: 6 Waiting process_alarm thread_alarm Thread: 5 Slept for 10 (10) sec Thread: 5 Waiting process_alarm process_alarm thread_alarm Thread: 6 Slept for 5 (5) sec Thread: 6 Waiting process_alarm process_alarm ... thread_alarm Thread: 5 Slept for 0 (1) sec end
MySQL は使用されるスレッドパッケージに非常に依存しています。 そのため、MySQL に良いプラットフォームを選択する時には、 スレッドパッケージが非常に重要です。
少なくとも3つのタイプのスレッドパッケージがあります:
ps
が異なったスレッドを示します。
もし一つのスレッドがアボートした場合、プロセス全体がアボートします。
多くのシステムコールはスレッド安全で、オーバーヘッドはとても少ないです。
Solaris, HP-UX, AIX そして OSF1 がカーネルスレッドを持っています。
いくつかのシステムでは、カーネルスレッドは、システムライブラリ内で、 ユーザレベルスレッドの統合によって管理されます。 この場合、スレッド切替えはスレッドライブラリによってだけ行なわれ、 カーネルは実際には 'thread aware' ではありません。
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 .
|
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 hello
は hello
と適合し、 他には適合しません。
簡単でない正規表現は、1つの文字列以上に適合できるような、いくつかの
特殊な構成を使用します。例えば、regexp hello|word
は
文字列 hello
と文字列 word
に適合します。
そしてさらに複雑な例 regexp B[an]*s
は、
文字列 Bananas
, Baaaaas
, Bs
のどれか、
そして B
で始まり a
や n
が
任意の数続き、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*
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?
a
。
mysql> SELECT "Bn" REGEXP "^Ba?n"; -> 1 mysql> SELECT "Ban" REGEXP "^Ba?n"; -> 1 mysql> SELECT "Baan" REGEXP "^Ba?n"; -> 0
de|abc
de
か abc
にマッチ。
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}
a*
a{0,}
.
a+
a{1,}
.
a?
a{0,1}
.
i
回の並びに適合します。
整数 i
とコンマを含む修飾が続くアトムは、
アトムに適合する i
回以上の並びに適合します。
整数 i
と j
を含む装飾が続くアトムは、
アトムに適 合する 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.]]
ch
照合要素を含む場合、
正規表現 [[.ch.]]*c
は chchcc
の最初の5文字に適合します。
[=character_class=]
o
と (+)
が同等クラスのメンバである場合、
[[=o=]]
, [[=(+)=]]
, [[=(+)=]]
は全て同義語です。
同等クラスは範囲の終了位置にはなりません。
[:character_class:]
[:
と :]
で括られた文字クラスの名前は、
そのクラスに属する全ての文字のリストを表します。標準文字クラス名は:
Name | Name | Name |
alnum | digit | punct |
alpha | graph | space |
blank | lower | upper |
cntrl | xdigit |
ctype(3)
マニュアルページに記載されている文字クラスを表します。
ロケールが他のを提供することもあります。文字クラスは範囲の終了位置としては使えません。
mysql> SELECT "justalnums" REGEXP "[[:alnum:]]+"; -> 1 mysql> SELECT "!!" REGEXP "[[:alnum:]]+"; -> 0
[[:<:]]
[[:>:]]
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
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.
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.
NO WARRANTY
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.
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.]
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.
NO WARRANTY
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!
CC
environment variable
CXX
environment variable
CC
CXX
HOME
MYSQL_DEBUG
MYSQL_HISTFILE
MYSQL_HOST
MYSQL_PWD
, environment variable, MYSQL_PWD
MYSQL_TCP_PORT
, environment variable, MYSQL_TCP_PORT
MYSQL_UNIX_PORT
, environment variable, MYSQL_UNIX_PORT
USER
HOME
environment variable
my_init()
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()
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_count()
, mysql_field_count()
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_HOST
environment variable
mysql_info()
mysql_init()
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_PWD
environment variable, MYSQL_PWD
environment variable
mysql_query()
, mysql_query()
mysql_real_connect()
mysql_real_escape_string()
mysql_real_query()
mysql_reload()
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_thread_end()
mysql_thread_id()
mysql_thread_init()
mysql_thread_safe()
MYSQL_UNIX_PORT
environment variable, MYSQL_UNIX_PORT
environment variable
mysql_use_result()
USER
environment variable
ACID
GROUP BY
clauses
ORDER BY
clauses
AUTO_INCREMENT
, and NULL
values
batch
, mysql
option
BDB
table type
BDB
tables
BerkeleyDB
table type
Binlog_Dump
BLOB
columns, default values
BLOB
columns, indexing
BLOB
, inserting binary data
BLOB
, size
mysqld
server
gcc
cc1plus
problems
character-sets-dir
, mysql
option
mysql
gcc
compress
, mysql
option
config.cache
file
configure
script
configure
, running after prior invocation
connect_timeout
variable
database
, mysql
option
db
table, sorting
debug-info
, mysql
option
debug
, mysql
option
BLOB
and TEXT
columns
default-character-set
, mysql
option
mysql.sock
SHOW
enable-named-commands
, mysql
option
myisamchk
output
execute
, mysql
option
fatal signal 11
config.cache
tmp
force
, mysql
option
SELECT
and WHERE
clauses
gcc
GROUP BY
, aliases in
GROUP BY
, extensions to ANSI SQL, GROUP BY
, extensions to ANSI SQL
HEAP
table type
help
, mysql
option
host
table
host
table, sorting
host
, mysql
option
html
, mysql
option
ignore-space
, mysql
option
BLOB
columns
IS NULL
LIKE
NULL
values
TEXT
columns
InnoDB
table type
InnoDB
tables
ISAM
table type
mysqlclient
make_binary_distribution
max_allowed_packet
max_join_size
MERGE
table type
msql2mysql
MyISAM
table type
myisamchk
, myisamchk
myisamchk
, example output
myisamchk
, options
myisampack
, myisampack
, myisampack
mysql
mysql
command-line options
mysql.sock
, protection
mysql_fix_privilege_tables
mysql_install_db
mysql_install_db
script
mysqlaccess
mysqladmin
, mysqladmin
, mysqladmin
, mysqladmin
, mysqladmin
, mysqladmin
, mysqladmin
mysqlbinlog
, mysqlbinlog
mysqlbug
mysqlbug
script
mysqlbug
script, location
mysqlclient
library
mysqld
mysqld
options
mysqld
server, buffer sizes
mysqld
, starting
mysqld-max
mysqld_multi
mysqld_safe
mysqldump
, mysqldump
, mysqldump
mysqlimport
, mysqlimport
, mysqlimport
, mysqlimport
mysqlshow
net_buffer_length
mysql.user
table
no-auto-rehash
, mysql
option
no-beep
, mysql
option
no-named-commands
, mysql
option
no-pager
, mysql
option
no-tee
, mysql
option
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
one-database
, mysql
option
Open Source
, defined
mysql
myisamchk
ORDER BY
, aliases in
pack_isam
pager
, mysql
option
password
, mysql
option
port
, mysql
option
DATE
columns
prompt
command
prompt
, mysql
option
protocol
, mysql
option, protocol
, mysql
option
quick
, mysql
option
raw
, mysql
option
reconnect
, mysql
option
replace
configure
after prior invocation
safe-mode
command
safe-updates
, mysql
option
safe_mysqld
mysql_install_db
mysqlbug
SELECT
, Query Cache
select_limit
set-variable
, mysql
option
silent
, mysql
option
skip-column-names
, mysql
option
skip-line-numbers
, mysql
option
socket
, mysql
option
sql_yacc.cc
problems
mysqld
mysql
status
command
SELECT
s
table
, mysql
option
BDB
Berkeley DB
HEAP
host
tee
, mysql
option
TEXT
columns, default values
TEXT
columns, indexing
TEXT
, size
connect_timeout
variable
TIMESTAMP
, and NULL
values
unbuffered
, mysql
option
user
table, sorting
user
, mysql
option
VARCHAR
, size
mysqld
verbose
, mysql
option
version
, mysql
option
vertical
, mysql
option
wait
, mysql
option
LIKE
mysql.columns_priv
table
mysql.db
table
mysql.host
table
mysql.tables_priv
table
mysql.user
table
xml
, mysql
option
This document was generated on 3 August 2004 using the texi2html translator version 1.52 (extended by davida@detron.se).