Home > Archives > June 2007 Archive

June 2007 Archive

INFORMATION_SCHEMAを利用して各データベースで消費されているストレージ容量を確認する方法

  • June 29, 2007 5:36 PM
[mt]> select table_schema, sum(data_length+index_length) from information_schema.tables group by table_schema;
+--------------------+-------------------------------+
| table_schema       | sum(data_length+index_length) |
+--------------------+-------------------------------+
| information_schema |                          4096 |
| mt                 |                       3215498 |
| mysql              |                        439168 |
+--------------------+-------------------------------+
3 rows in set (0.28 sec)

こんな感じで。
  • Comments (Close): 0
  • TrackBack (Close): 0

一台のサーバー上に複数のMySQL Serverを起動する際の注意点

  • June 29, 2007 5:20 PM

  • できればそれぞれにData Directoryを指定する。(Windowsでは必須)
    • UnixではMyISAMファイルを読み取り専用にすることで共有できる。
    • UnixでもInnoDBのテーブルスペースは読み取り専用では利用できないので不可。
  • それぞれにネットワークインターフェイスを用意する。
  • それぞれにログファイルを指定する。
  • InnoDBのテーブルスペースは絶対共有不可能。
  • Comments (Close): 0
  • TrackBack (Close): 0

スレッド関連のパラメータ

  • June 29, 2007 5:04 PM
スレッドに関連するパラメータ一覧

  • threads_connected (現在開いている接続)
  • threads_cached (使用可能かつ非アクティブなスレッド数)
  • threads_created (作成されたスレッド数)
  • threads_running (処理実行中のスレッド数)
  • slow_launch_threads (スレッド生成時間 > slow_launch_time)
スレッド キャッシュのヒット率は threads_created/connections を使用して計算する
多くのスレッドが作成されている (またはヒット率が低い) 場合は、thread_cache_size を大きくしてみる

slow_launch_threads は 0 か、0 に近い値でなければならない

[world2]>show status like '%thread%';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| Delayed_insert_threads | 0     |
| Slow_launch_threads    | 0     |
| Threads_cached         | 2     |
| Threads_connected      | 1     |
| Threads_created        | 3     |
| Threads_running        | 1     |
+------------------------+-------+
6 rows in set (0.01 sec)

  • Comments (Close): 0
  • TrackBack (Close): 0

Query Cache

  • June 29, 2007 4:53 PM
クエリ キャッシュは SELECT クエリとその結果を格納して、頻繁に要求されるデータのパフォーマンスを向上する。またテーブルの変更によって、関連するすべてのクエリがキャッシュからフラッシュ されるので、データは常に新しいハズ。

クエリはバイトごとに一致している必要があるので、大文字小文字

query_cache_size
デフォルトは 0 (オフの意味)
キャッシュと結果用に予約するサイズ (バイト) を設定

query_cache_type=OFF|ON|DEMAND (または 0|1|2)
キャッシュの動作を設定
ON の場合は、SELECT SQL_NO_CACHE ... 構文を使用しない限りデフォルトでキャッシュを使用
DEMAND の場合は、SELECT SQL_CACHE ... 構文を使用しない限りデフォルトでキャッシュを使用しない
グローバル値によって接続のデフォルト値が決まるが、個々のクライアントセッションでも設定できる


mysql> SHOW STATUS LIKE 'Qcache%';
+-------------------------+--------+
| Variable_name            | Value |
+-------------------------+--------+
| Qcache_free_blocks      |     36 | 空きブロック数
| Qcache_free_memory      | 138488 | 空きメモリのサイズ (バイト)
| Qcache_hits             |  79570 | クエリのヒット数
| Qcache_inserts          |  27087 | キャッシュに入れられたクエリの数  
| Qcache_lowmem_prunes    |   3114 | メモリが小さいために削除された数
| Qcache_not_cached       |  22989 | キャッシュに入れられなかったクエリの数
| Qcache_queries_in_cache |    415 | キャッシュ内のクエリの数
| Qcache_total_blocks     |    912 | ブロックの領域の合計
+-------------------------+--------+


FLUSH QUERY CACHE は、クエリを削除することなくキャッシュのフラグメント化を解消する
キャッシュは次のコマンドでリセットできる
  • RESET QUERY CACHE
  • FLUSH TABLES
  • mysqld の再起動も使用できる

query_cache_limit 変数を使用して、キャッシュに入れるクエリの最大サイズを設定できる
query_cache_min_res_unit (ブロック サイズ) の設定がクエリ キャッシュのフラグメント化に役立つ
デフォルトは 4 KB
キャッシュに入れられたほとんどのクエリの結果セットが小さい場合は、小さくする必要がある。ほとんどの結果セットが大きい場合は大きくする必要がある
Qcache_free_blocksQcache_lowmem_prunes を使用して、空きブロックが残っているにもかかわらずキャッシュに入れられたクエリが切り捨てられるかどうかを確認する
Qcache_hitsCom_select と比較して、クエリーキャッシュのヒット率を求めることが できる

  • Comments (Close): 0
  • TrackBack (Close): 0

パラメータのチューニング

  • June 29, 2007 4:25 PM

例えばmy.cnfの各種パラメータの値を決めるとき、物理メモリサイズを次の通り配分する。

グローバルバッファのサイズ+(スレッドバッファのサイズ×最大接続数)

グローバルバッファは

key_buffer
innodb_buffer_pool_size
innodb_log_buffer
innodb_additional_mem_pool
net_buffer
など

スレッドバッファ(ローカルバッファ)は

read_buffer: テーブルの順次スキャンで利用される。
read_rnd_buffer: テーブルのランダムスキャンで利用される。?
sort_buffer: ORDER BY, GROUP BY時に利用→超えると、sort_merge_passesがカウントアップされる

join_buffer: JOINで利用される。複雑なJOIN時には増やす

max_allowed_packet

tmp_table_size?

myisam_sort_buffer
など

  • Comments (Close): 0
  • TrackBack (Close): 0

MAX_CONNECTIONS

  • June 29, 2007 3:54 PM
http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html

mysqld actually allows max_connections+1 clients to connect. The extra connection is reserved for use by accounts that have the SUPER privilege.

  • Comments (Close): 0
  • TrackBack (Close): 0

SQLクエリの構文間違い(Syntax Error)やMAX_CONNECTIONSを超えて接続したクライアントの情報をエラーログなどに出力できるか

  • June 29, 2007 3:15 PM
SQLクエリの構文間違い(Syntax Error)やMAX_CONNECTIONSを超えて接続したクライアントの情報をエラーログなどに出力できるか。

仕様上できない。

SQLクエリ自体はGeneral Query Logに出力されるが、構文エラーかどうかという情報は無い。

またMAX_CONNECTIONSを超えた接続要求のエラー有無はログには出力されない。


が、次の値を使って、「現在どれくらいアクティブなセッションがあるか」を確認できる。

show status like 'Threads_connected';
show variables like 'max_connections';

この割合は、MySQL AdministratorのConnection Healthでも確認できる。

http://dev.mysql.com/doc/administrator/en/mysql-administrator-health-connection-health.html
  • Comments (Close): 0
  • TrackBack (Close): 0

defaults-group-suffixオプションがmysqld_safeでは「無効なオプション」と認識される。

  • June 29, 2007 2:10 PM
http://dev.mysql.com/doc/refman/5.0/en/option-files.html

--defaults-group-suffix=str


If this option is given, the program reads not only its usual option groups, but also groups with the usual names and a suffix of str. For example, the mysql client normally reads the [client] and [mysql] groups. If the --default-group-suffix=_other option is given, mysql also reads the [client_other] and [mysql_other] groups. This option was added in MySQL 5.0.10.


このマニュアルを読む限り、設定ファイルのセクション名を拡張するオプションの様子。
_otherと指定すると、mysqld_otherも、合わせて読んでくれる模様。

mysqldでは、もちろん--defaults-group-suffixは有効
[root@h1 mysql]# mysqld --defaults-group-suffix=_test -uroot &
[1] 21682
[root@h1 mysql]# 070629 19:54:22  InnoDB: Started; log sequence number 0 43655
070629 19:54:22 [Note] mysqld: ready for connections.
Version: '5.0.42-enterprise-gpl'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Enterprise Server (GPL)

mysqld_safeでは、起動しない。
[root@h1 mysql]# mysqld_safe --defaults-group-suffix=_test -uroot &
[1] 21724
[root@h1 mysql]# Starting mysqld daemon with databases from /var/lib/mysql
STOPPING server from pid file /var/lib/mysql/h1.pid
070629 19:55:45  mysqld ended


[1]+  Done                    mysqld_safe --defaults-group-suffix=_test -uroot

エラーログを確認すると、何故か--defaults-group-suffixが「無効なオプション」として認識されている様子。

[root@h1 mysql]# tail h1.err
<略>
070629 19:55:45 [ERROR] /usr/sbin/mysqld: unknown variable 'defaults-group-suffix=_test'

070629 19:55:45  mysqld ended

原因:mysqldへオプションを渡すとき、先頭で指定していない場合は、エラーとなるバグのよう。

[root@h1 mysql]# mysqld --max_connections=10 --defaults-group-suffix=_test -uroot & [1] 21792
[root@h1 mysql]# 070629 20:17:24 [ERROR] mysqld: unknown variable 'defaults-group-suffix=_test'


mysqld_safeは、いくつかのオプションをつけてから、mysqldへオプションを渡しているので、毎回エラーとなったよう。
  • Comments (Close): 0
  • TrackBack (Close): 0

Statement Based Binary Logに出力されるもの(Stored Procedure, Stored Function, Trigger)

  • June 29, 2007 2:04 PM
Stored Procedure / Stored Function: CALL文では無く、展開されたSQLクエリ
Trigger: そのまま。なので、レプリケーション構築時にはスレーブでも同じく定義しておきましょう。
  • Comments (Close): 0
  • TrackBack (Close): 0

created_tmp_disk_tablesで確認できる、ディスク上の一時テーブルは、どんなタイミングで削除されるのか

  • June 29, 2007 1:36 PM
tmp_table_size

The maximum size of in-memory temporary tables. (The actual limit is determined as the smaller of max_heap_table_size and tmp_table_size.) If an in-memory temporary table exceeds the limit, MySQL automatically converts it to an on-disk MyISAM table. Increase the value of tmp_table_size (and max_heap_table_size if necessary) if you do many advanced GROUP BY queries and you have lots of memory.



http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html

  • Comments (Close): 0
  • TrackBack (Close): 0

USING FILESORTを消すにはインデックス作成だけでは足りない場合があるのでFORCE INDEXで強制する

  • June 29, 2007 11:35 AM
[world]>explain select * from city where countrycode='JPN' o
rder by name\G
*************************** 1. row *************************
**
           id: 1
  select_type: SIMPLE
        table: city
         type: ref
possible_keys: CountryCode
          key: CountryCode
      key_len: 3
          ref: const
         rows: 248
        Extra: Using where; Using filesort
1 row in set (0.00 sec)

[world]>create index idx1 on city(name);
Query OK, 4079 rows affected (0.26 sec)
Records: 4079  Duplicates: 0  Warnings: 0

[world]>explain select * from city where countrycode='JPN' o
rder by name\G
*************************** 1. row *************************
**
           id: 1
  select_type: SIMPLE
        table: city
         type: ref
possible_keys: CountryCode
          key: CountryCode
      key_len: 3
          ref: const
         rows: 248
        Extra: Using where; Using filesort
1 row in set (0.00 sec)

[world]>show create table city;
+-------+---------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
-----+
| Table | Create Table





     |
+-------+---------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
-----+
| city  | CREATE TABLE `city` (
  `ID` int(11) NOT NULL auto_increment,
  `Name` char(35) NOT NULL default '',
  `CountryCode` char(3) NOT NULL default '',
  `District` char(20) NOT NULL default '',
  `Population` int(11) NOT NULL default '0',
  PRIMARY KEY  (`ID`),
  KEY `CountryCode` (`CountryCode`),
  KEY `idx1` (`Name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+---------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
-----+
1 row in set (0.00 sec)

と思ったら、FORCE INDEXでUSING FILESORTが消えた

[world]>explain select * from city force index(idx1) where c
ountrycode='JPN' order by name\G
*************************** 1. row *************************
**
           id: 1
  select_type: SIMPLE
        table: city
         type: index
possible_keys: NULL
          key: idx1
      key_len: 35
          ref: NULL
         rows: 4070
        Extra: Using where
1 row in set (0.00 sec)


  • Comments (Close): 0
  • TrackBack (Close): 0

SLOW QUERY LOGの例

  • June 29, 2007 10:49 AM
SLOW QUERY LOGの例

macbook:~/data/data1 hirohama$ more 1slow.log
/usr/local/mysql/bin/mysqld, Version: 5.0.42-enterprise-gpl-log (MySQL Enterprise Server (GPL)). started with:
Tcp port: 3306  Unix socket: /tmp/mysql.sock
Time                 Id Command    Argument
# Time: 070629 10:51:21
# User@Host: root[root] @ localhost []
# Query_time: 13  Lock_time: 0  Rows_sent: 0  Rows_examined: 4194304
use test;
SET insert_id=2097153;
insert into t2(b) select b from t2;
# Time: 070629 10:52:14
# User@Host: root[root] @ localhost []
# Query_time: 27  Lock_time: 0  Rows_sent: 0  Rows_examined: 8388608
SET insert_id=4194305;
insert into t2(b) select b from t2;
# Time: 070629 10:53:59
# User@Host: root[root] @ localhost []
# Query_time: 60  Lock_time: 0  Rows_sent: 0  Rows_examined: 16979416
SET insert_id=8489709;
insert into t2(b) select b+rand()*100 from t2 limit 10000000;
MYSQLDUMPSLOWの例

macbook:~/data/data1 hirohama$ /usr/local/mysql/bin/mysqldumpslow ./1slow.log

Reading mysql slow query log from ./1slow.log
Count: 1  Time=60.00s (60s)  Lock=0.00s (0s)  Rows=0.0 (0), root[root]@localhost
  SET insert_id=N;
  insert into t2(b) select b+rand()*N from t2 limit N

Count: 2  Time=20.00s (40s)  Lock=0.00s (0s)  Rows=0.0 (0), root[root]@localhost
  SET insert_id=N;
  insert into t2(b) select b from t2

  • Comments (Close): 0
  • TrackBack (Close): 0

MyISAMのインデックスキャッシュの設定, KEY_BUFFER_SIZE

  • June 29, 2007 10:12 AM
KEY_BUFFER_SIZEを設定しておくと、MyISAMのインデックス(MYIファイル)をキャッシュしてくれる。
ただし、まとめて、では無くて、使われたインデックスをその都度入れていく。


5.0ではあらかじめインデックス全体をまとめてロードできる。

[world]>set global city_cache.key_buffer_size=4*1024*1024;
Query OK, 0 rows affected (0.00 sec)

[world]>cache index world.city in city_cache;
+------------+--------------------+----------+---------------------------------------------------------------------+
| Table      | Op                 | Msg_type | Msg_text                                                       |
+------------+--------------------+----------+---------------------------------------------------------------------+
| world.city | assign_to_keycache | note     | The storage engine for the table doesn't support assign_to_keycache |
+------------+--------------------+----------+---------------------------------------------------------------------+
1 row in set (0.03 sec)

[world]>load index into cache world.city;
+------------+--------------+----------+--------------------
-------------------------------------------+
| Table      | Op           | Msg_type | Msg_text
                                           |
+------------+--------------+----------+--------------------
-------------------------------------------+
| world.city | preload_keys | note     | The storage engine
for the table doesn't support preload_keys |
+------------+--------------+----------+--------------------
-------------------------------------------+
1 row in set (0.00 sec)

疑問1:ここで作成するcity_cacheは、key_buffer内部に作成されるものだよね?
key_buffer_size以上のサイズも設定できてしまうのだけど。

疑問2:オンラインマニュアルには、hot, warm, coldというキーワードが使われているけど、これらのキーワードを利用すると、期待する動作となるのか?


  • Comments (Close): 0
  • TrackBack (Close): 0

テーブルメンテナンス系コマンドの一覧

  • June 28, 2007 4:35 PM
コマンドMyISAMInnoDBロックの有無
CHECK TABLE整合性のチェック、インデックス統計情報の更新整合性のチェック
REPAIR TABLEテーブルの修復N/A
ANALYSE TABLEインデックス統計情報の更新インデックス統計情報の更新MyISAM: READ LOCK
InnoDB: WRITE LOCK
OPTIMIZE TABLEインデックス統計情報の更新、デフラグの解消、インデックスページの並べ替えALTER TABLEREAD LOCKとWRITE LOCK


インデックス統計情報の更新はエンジンによって挙動が異なる。

MyISAM:全行からCardinalityを計算する。
InnoDB:ランダムに10個選択してCardinalityを予測する。

Cardinalityは、INFORMATION_SCHEMA.STATISTICSとかSHOW INDEX FROM ...;で確認できる。
  • Comments (Close): 0
  • TrackBack (Close): 0

BIT

  • June 28, 2007 3:04 PM
create table bits(a bit(10));

insert into bits values(b'1010');

select bin(a) from bits;

select a+0 from bits;

BinaryでSELECT、ダミーの0を足して10進数に変換
  • Comments (Close): 0
  • TrackBack (Close): 0

0624-log

  • June 28, 2007 9:51 AM

せっかくなので、そのままコピペ

Continue reading

  • Comments (Close): 0
  • TrackBack (Close): 0

Stored Routinesの実体

  • June 27, 2007 5:28 PM
Trigger
TRNファイルとTRGファイルが作成される

Stored Function/Stored Procedure
mysql.procに作成される
mysqldump --routinesでダンプできる
  • Comments (Close): 0
  • TrackBack (Close): 0

TRUNCATE

  • June 27, 2007 4:43 PM
CREATE TRIGGER Capital_bi
  BEFORE INSERT
  ON Capital
  FOR EACH ROW
    SET NEW.Population =
      IF(NEW.Population < 0, 0, TRUNCATE(NEW.Population,-3));

このTRUNCATEは?
  • Comments (Close): 0
  • TrackBack (Close): 0

CREATE FUNCTIONでエラー

  • June 27, 2007 3:05 PM
log-binをオフにすると、なぜかエラー
なぜ???

root@localhost[test]>create function hello1(input char(20))
returns char(50) return concat('Hello, ', input, '!');
ERROR 1418 (HY000): This function has none of DETERMINISTIC,
 NO SQL, or READS SQL DATA in its declaration and binary log
ging is enabled (you *might* want to use the less safe log_b
in_trust_function_creators variable)

log-binをオフにすると、エラーなし


答え:

ファンクション作成時には、明示的にDETERMINISTIC, NO SQL, READS SQL DATAなどを指定して、「そのままバイナリログに出力しても問題ないよ」と教えてやる必要がある。

または、上記のオプション無しでもエラーを返さないように、まとめて設定してしまう。
log_bin_trust_function_creators = 1;

なんでStored Functionでだけ?

メモ
As you know stored procedures are invoked with:

CALL proc(...);

MySQL does not log the CALL statement into binary log. If procedure contains
"writing" statements (INSERT, UPDATE etc.) MySQL logs these statements in binary
log.

When it comes to Replication for example if you call such procedure on the
Master the Slave server will get and apply changes even if it does not have such
procedure at all. In other words CALL will not be replicated, but the underlying
statements will be replicated.


Functions at the other hand are always invoked within regular statement like:

SELECT x, my_stored_func() FROM my_table;
UPDATE my_table SET y = my_stored_func();


Now when my_stored_func() modifies table data MySQL must log each statement
where this function is called. Even if it is SELECT like above it will go to the
binary log because it modifies some data implicitly.

But the actual statements executed within the body of my_stored_func() will not
be logged. If both the function calling statement *and* the underlying
statements are logged same change will be applied twice.


This implies that upon replaying the binary log the server must have stored
functions defined unlike with stored procedures.

As you see this is fundamental difference between logging stored procedures and
functions.

To repeat it in brief:
* Procedure invocation is not logged, underlying statements are logged.
* Function invocation is logged, underlying statements are not.
  • Comments (Close): 0
  • TrackBack (Close): 0

Federated Engineの利用方法

  • June 27, 2007 2:25 PM
CREATE TABLEでふつうにテーブルを作成して、最後に追加

CONNECTION='mysql://root:root@localhost:3306/test/fed'
InnoDBでは、ファイルのパスを指定してもだめっぽい。(分割してくれない)
MyISAMならば、OK
  • Comments (Close): 0
  • TrackBack (Close): 0

PARTITIONING TABLEでパーティションをさくっと削除

  • June 27, 2007 2:17 PM
mysql> alter table t1 drop partition p1;
ERROR 1500 (HY000): DROP PARTITION can only be used on RANGE
/LIST partitions
ということらしい。
  • Comments (Close): 0
  • TrackBack (Close): 0

SELECT INTO OUTFILEでダンプする際に文字コードはどれくらい注意すべきか

  • June 27, 2007 11:55 AM
Windows上なので文字コードを確認

root@localhost[test]>select hex(convert(_cp932 "あ" using ut
f8));
+--------------------------------------+
| hex(convert(_cp932 "あ" using utf8))   |
+--------------------------------------+
| E38182                               |
+--------------------------------------+
1 row in set (0.00 sec)

16進でデータを入れる

root@localhost[test]>insert into t6 values(1,0xE38182);
Query OK, 1 row affected (0.01 sec)


キャラクタセットを全てCP932へ変えても、

root@localhost[test]>show variables like '%char%';
+--------------------------+--------------------------------
-------------------------+
| Variable_name            | Value
                         |
+--------------------------+--------------------------------
-------------------------+
| character_set_client     | cp932
                         |
| character_set_connection | cp932
                         |
| character_set_database   | cp932
                         |
| character_set_filesystem | binary
                         |
| character_set_results    | cp932
                         |
| character_set_server     | cp932
                         |
| character_set_system     | utf8
                         |
| character_sets_dir       | C:\Program Files\MySQL\MySQL Se
rver 5.0\share\charsets\ |
+--------------------------+--------------------------------
-------------------------+
8 rows in set (0.00 sec)

root@localhost[test]>select * from t6 into outfile 'dump_cp9
32.txt';
Query OK, 2 rows affected (0.00 sec)


select into outfileしたファイルは、UTF8のまま

ファイルは/data/test/ディレクトリ直下に保存されるので、おそらくクライアントにはデータ送信されないので、処理はサーバ側で完結しているのでしょう。

  • Comments (Close): 0
  • TrackBack (Close): 0

PARTITIONING TABLEでテーブル分割する際のKEYとHASHの違い

  • June 27, 2007 9:47 AM
KEY: 実際の値で分割?

HASH:ハッシュ化した値で分割?

といいつつ、未だに違いがよく分からない。

→回答

KEY:
1) 構文
... PARTITION BY KEY() PARTITIONS n;
2) 指定できるカラムは、キー、カラム、カラムのリストなど

HASH:

1) 構文
... PARTITION BY HASH(<expression>) PARTITIONS n.
<expression>には式が必要

2) <expression>はINT型を返す必要がある。

ソースコード:
/sql/ha_partition.h
/sql/ha_partition.cc
  • Comments (Close): 0
  • TrackBack (Close): 0

ロックの確認

  • June 26, 2007 5:45 PM
どのテーブルがロックされているかを確認する方法

方法1:SHOW OPEN TABLESで確認

参考:http://d.hatena.ne.jp/mir/20070626/p2

方法2:

mysqldへdebugオプションを発行して、エラーログを確認する。

client 1
mysqladmin -uroot debug

client 2
mysql> lock tables t1 write;
Query OK, 0 rows affected (0.00 sec)

mysql> show open tables;
+----------+--------------+--------+-------------+
| Database | Table        | In_use | Name_locked |
+----------+--------------+--------+-------------+
| mysql    | procs_priv   |      0 |           0 |
| mysql    | db           |      0 |           0 |
| mysql    | host         |      0 |           0 |
| mysql    | tables_priv  |      0 |           0 |
| mysql    | user         |      0 |           0 |
| mysql    | columns_priv |      0 |           0 |
| test     | t1           |      1 |           0 |
+----------+--------------+--------+-------------+
7 rows in set (0.00 sec)

client 1
[root@h1 mysql]# more h1.err
070619 16:58:33  mysqld started
InnoDB: The first specified data file ./ibdata1 did not exist:
InnoDB: a new database to be created!
070619 16:58:33  InnoDB: Setting file ./ibdata1 size to 10 MB
InnoDB: Database physically writes the file full: wait...
070619 16:58:33  InnoDB: Log file ./ib_logfile0 did not exist: new to be created
InnoDB: Setting log file ./ib_logfile0 size to 5 MB
InnoDB: Database physically writes the file full: wait...
070619 16:58:33  InnoDB: Log file ./ib_logfile1 did not exist: new to be created
InnoDB: Setting log file ./ib_logfile1 size to 5 MB
InnoDB: Database physically writes the file full: wait...
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
070619 16:58:34  InnoDB: Started; log sequence number 0 0
070619 16:58:34 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.0.42-enterprise-gpl'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Enterprise Server (GPL)

Status information:

Current dir: /var/lib/mysql/
Running threads: 1  Stack size: 262144
Current locks:
lock: 0x1151fa0:

lock: 0x114c4a0:

lock: 0x11474f0:

lock: 0x1138cd0:

lock: 0x1134cf0:

lock: 0x112eca0:


Key caches:
default
Buffer_size:       8388600
Block_size:           1024
Division_limit:        100
Age_limit:             300
blocks used:             0
not flushed:             0
w_requests:              0
writes:                  0
r_requests:              0
reads:                   0


handler status:
read_key:            0
read_next:           0
read_rnd             0
read_first:          3
write:               0
delete               0
update:              0

Table status:
Opened tables:         12
Open tables:            6
Open files:            12
Open streams:           0

Alarm status:
Active alarms:   0
Max used alarms: 1
Next alarm time: 0

Memory status:
Non-mmapped space allocated from system: 6029312
Number of free chunks:                   4
Number of fastbin blocks:                0
Number of mmapped regions:               12
Space in mmapped regions:                23711744
Maximum total allocated space:           0
Space available in freed fastbin blocks: 0
Total allocated space:                   5934032
Total free space:                        95280
Top-most, releasable space:              91328
Estimated memory (with thread stack):    30003200


Status information:

Current dir: /var/lib/mysql/
Running threads: 2  Stack size: 262144
Current locks:
lock: 0x1169e00: write
write     : 0x113cda8 (1147701600:10);

lock: 0x1151fa0:

lock: 0x114c4a0:

lock: 0x11474f0:

lock: 0x1138cd0:

lock: 0x1134cf0:

lock: 0x112eca0:


Key caches:
default
Buffer_size:       8388600
Block_size:           1024
Division_limit:        100
Age_limit:             300
blocks used:             0
not flushed:             0
w_requests:              0
writes:                  0
r_requests:              0
reads:                   0


handler status:
read_key:            0
read_next:           0
read_rnd             0
read_first:          3
write:              14
delete               0
update:              0

Table status:
Opened tables:         14
Open tables:            7
Open files:            14
Open streams:           0

Alarm status:
Active alarms:   1
Max used alarms: 2
Next alarm time: 28752

Thread database.table_name          Locked/Waiting        Lock_type

5       test.t1                     Locked - write        High priority write lock

方法3:INFORMATION_SCHEMAで実装予定の機能を使う。

MySQL Bugs: #23076: No way of viewing locks from within the server


方法2の補足:
ソース上は、こんな感じらしい。
./sql/sql_test.cc fileのmysql_print_status().

void mysql_print_status()
{
char current_dir[FN_REFLEN];
STATUS_VAR tmp;

calc_sum_of_all_status(&tmp);
printf("\nStatus information:\n\n");
VOID(my_getwd(current_dir, sizeof(current_dir),MYF(0)));
printf("Current dir: %s\n", current_dir);
printf("Running threads: %d Stack size: %ld\n", thread_count,
(long) thread_stack);
thr_print_locks(); // Write some debug info
#ifndef DBUG_OFF
print_cached_tables();
#endif
/* Print key cache status */
puts("\nKey caches:");
process_key_caches(print_key_cache_status);
pthread_mutex_lock(&LOCK_status);
printf("\nhandler status:\n\
read_key: %10lu\n\
read_next: %10lu\n\
read_rnd %10lu\n\
read_first: %10lu\n\
write: %10lu\n\
delete %10lu\n\
update: %10lu\n",
tmp.ha_read_key_count,
tmp.ha_read_next_count,
tmp.ha_read_rnd_count,
tmp.ha_read_first_count,
tmp.ha_write_count,
tmp.ha_delete_count,
tmp.ha_update_count);
pthread_mutex_unlock(&LOCK_status);
printf("\nTable status:\n\
Opened tables: %10lu\n\
Open tables: %10lu\n\
Open files: %10lu\n\
Open streams: %10lu\n",
tmp.opened_tables,
(ulong) cached_tables(),
(ulong) my_file_opened,
(ulong) my_stream_opened);

ALARM_INFO alarm_info;
#ifndef DONT_USE_THR_ALARM
thr_alarm_info(&alarm_info);
printf("\nAlarm status:\n\
Active alarms: %u\n\
Max used alarms: %u\n\
Next alarm time: %lu\n",
alarm_info.active_alarms,
alarm_info.max_used_alarms,
alarm_info.next_alarm_time);
#endif
display_table_locks();
fflush(stdout);
my_checkmalloc();
TERMINATE(stdout); // Write malloc information

#ifdef HAVE_MALLINFO
struct mallinfo info= mallinfo();
printf("\nMemory status:\n\
Non-mmapped space allocated from system: %d\n\
Number of free chunks: %d\n\
Number of fastbin blocks: %d\n\
Number of mmapped regions: %d\n\
Space in mmapped regions: %d\n\
Maximum total allocated space: %d\n\
Space available in freed fastbin blocks: %d\n\
Total allocated space: %d\n\
Total free space: %d\n\
Top-most, releasable space: %d\n\
Estimated memory (with thread stack): %ld\n",
(int) info.arena ,
(int) info.ordblks,
(int) info.smblks,
(int) info.hblks,
(int) info.hblkhd,
(int) info.usmblks,
(int) info.fsmblks,
(int) info.uordblks,
(int) info.fordblks,
(int) info.keepcost,
(long) (thread_count * thread_stack + info.hblkhd + info.arena));
#endif
puts("");
}
  • Comments (Close): 0
  • TrackBack (Close): 0

MySQL Instance Manager の設定方法 (mysqlmanager)

  • June 26, 2007 11:40 AM
Instance Managerは、結構便利。っていうか、猛烈にオススメ。

複数のMySQL Serverの起動、停止が簡単にできる。

1。パスワードファイルの設定

デフォルトでは/etc/mysqlmanager.passwdファイルを見にいくので、ここにInstance Manager用のパスワードファイルを作成する。

shell> /usr/local/mysql/bin/mysqlmanager --passwd >> /etc/mysqlmanager.passwd

ユーザ名とパスワードを指定する。ここではユーザ名:manager、パスワード:managerを指定した。

2。設定ファイルの準備

/etc/my.cnfファイルへ、Instance Manager用のエントリを追記する。 こんな感じで。

[manager]
default-mysqld-path=/usr/local/mysql/bin/mysqld
password-file=/etc/mysqlmanager.passwd
log=/Users/hirohama/data/manager.log
run-as-service

socket=/tmp/manager.sock
pid-file=/tmp/manager.pid
port=1999

user=mysql

[mysql]
user=root
prompt=¥u@¥h[¥d]>¥_
port=3306
socket=/tmp/mysql.sock

[mysqld1]
nonguarded
socket=/tmp/mysql1.sock
pid-file=/tmp/mysql1.pid
datadir=/Users/hirohama/data/data1


port=3306
server-id=11
log-bin
log

[mysqld2]
nonguarded
socket=/tmp/mysql2.sock
pid-file=/tmp/mysql2.pid
datadir=/Users/hirohama/data/data2

port=3307
server-id=12
log-bin
log

3。Instance Managerの起動

/usr/local/mysql/bin/mysqlmanager

4。Instance Managerへ接続して各mysqldを起動する

/usr/local/mysql hirohama$ ./bin/mysql --user=manager --password=manager --socket=/tmp/manager.sock 
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 0.2-alpha

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

manager@localhost[(none)]> show instances;
+---------------+---------+
| instance_name | status |
+---------------+---------+
| mysqld1 | offline |
| mysqld2 | offline |
+---------------+---------+
2 rows in set (0.00 sec)

manager@localhost[(none)]> start instance mysqld1;
Query OK, 0 rows affected (0.00 sec)
Instance started

manager@localhost[(none)]> start instance mysqld2;
Query OK, 0 rows affected (0.00 sec)
Instance started

manager@localhost[(none)]> show instances;
+---------------+--------+
| instance_name | status |
+---------------+--------+
| mysqld1 | online |
| mysqld2 | online |
+---------------+--------+
2 rows in set (0.00 sec)

5。別のバージョンも混ぜるとき

[mysqld3]
nonguarded
socket=/tmp/mysql3.sock
pid-file=/tmp/mysql3.pid
datadir=/Users/hirohama/data/data3
basedir=/usr/local/mysql-5.1.14-beta-osx10.4-i686
mysqld-path=/usr/local/mysql-5.1.14-beta-osx10.4-i686/bin/mysqld


port=3308
log-bin
log

basedirもあわせて指定すること

  • Comments (Close): 0
  • TrackBack (Close): 0

ビックリマーク(exclamation point(!))をパスワードで使っている場合はLinux環境ではエスケープが必要

  • June 25, 2007 5:38 PM
ビックリマーク(exclamation point(!))をパスワードで使っている場合には、
  • Windows環境ではそのままでOK
  • Unix/Linux環境ではエスケープが必要
理由はBash環境でビックリマークが特別な意味を持つから。

エスケープをすると、こんな感じ

 shell> mysql -uroot -ppass\!word

シングルクォートで括ってもOK

 shell> mysql -uroot -p'pass!word'
  • Comments (Close): 0
  • TrackBack (Close): 0

MySQLのSQL_MODEとストリクトモード

  • June 22, 2007 10:51 AM

  1. ストリクトモード

    STRICT_ALL_TABLESまたはSTRICT_TRANS_TABLESのどちらかがオンになっている状態を「ストリクトモード」と呼ぶ。

    ストリクトモード時は、無効なデータなどの挿入、更新時にエラーを出力する。 

    ストリクトモードでは、2006-04-31などの存在しない日付を挿入することが出来ないが、2006-06-00や、00などの日付は挿入できてしまう。これらを禁止したい場合は、後述するNO_ZERO_IN_DATEやNO_ZERO_DATEなども合わせてオンにする。 

    もしストリクトモードが有効になっていない場合は、MySQLは無効な値の挿入に対して、適切と判断した値を挿入して、警告を出力する。

    ストリクトモード時に無効なデータを入れたい場合は、INSERT IGNOREまたはUPDATE IGNOREを指定する。

    1. STRICT_ALL_TABLES

    全てのエンジンでストリクトモードとする

    1. STRICT_TRANS_TABLES

    トランザクションをサポートするエンジン(InnoDB, BDBなど)のみストリクトモードとする。 

      mysql> set @@session.sql_mode='';

      Query OK, 0 rows affected (0.01 sec) 

      mysql> select @@session.sql_mode;

      +--------------------+

      | @@session.sql_mode |

      +--------------------+

      |                    |

      +--------------------+

      1 row in set (0.00 sec) 

      mysql> show create table ttran\G

      *************************** 1. row ***************************

             Table: ttran

      Create Table: CREATE TABLE `ttran` (

        `c1` int(11) NOT NULL

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

      1 row in set (0.00 sec) 

      mysql> insert into ttran values(NULL);

      ERROR 1048 (23000): Column 'c1' cannot be null

      mysql> insert into ttran values();

      Query OK, 1 row affected, 1 warning (0.02 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning

         Code: 1364

      Message: Field 'c1' doesn't have a default value

      1 row in set (0.00 sec) 

      mysql> select * from ttran;

      +----+

      | c1 |

      +----+

      |  0 |

      +----+

      1 row in set (0.04 sec) 

      mysql> set @@session.sql_mode='STRICT_TRANS_TABLES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into ttran values();

      ERROR 1364 (HY000): Field 'c1' doesn't have a default value 


 

 

  1. 日付
    1. ALLOW_INVALID_DATES

    日付チェックを厳密に行わない。

    月が1~12、日が1~31であることだけをチェックする。 

    DATE('1000­01­01' ~ '9999­12­31')とDATETIME('1000­01­01 00:00:00' ~ '9999­12­31 23:59:59')にて使うことができる。

    TIMESTAMPは常に厳密なチェックを行うので、ALLOW_INVALID_DATESオプションは有効とならない。 

    INSERT IGNORE及びUPDATE IGNOREで無効化できる。 

1. 無効な日付データ挿入時の挙動

      ALLOW_INVALID_DATES 無し
    STRICT_TRANS_TABLES 挿入されてしまう エラー発生

    挿入されない

    無し 挿入されてしまう 警告発生

    デフォルト値が挿入

 
 
      mysql> show create table tdate¥G

      *************************** 1. row ***************************

             Table: tdate

      Create Table: CREATE TABLE `tdate` (

        `c1` date default NULL

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

      1 row in set (0.01 sec) 

      mysql> set @@session.sql_mode='ALLOW_INVALID_DATES';

      Query OK, 0 rows affected (0.13 sec) 

      mysql> insert into tdate values('2004-04-31');

      Query OK, 1 row affected (0.12 sec) 

      mysql> select * from tdate;

      +------------+

      | c1         |

      +------------+

      | 2004-04-31 |

      +------------+

      1 row in set (0.03 sec) 

      mysql> set @@session.sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2004-04-31');

      Query OK, 1 row affected, 1 warning (0.04 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning

         Code: 1265

      Message: Data truncated for column 'c1' at row 1

      1 row in set (0.02 sec) 

      mysql> select * from tdate;

      +------------+

      | c1         |

      +------------+

      | 2004-04-31 |

      | 0000-00-00 |

      +------------+

      2 rows in set (0.00 sec) 

      mysql> set @@session.sql_mode='STRICT_TRANS_TABLES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2004-04-31');

      ERROR 1292 (22007): Incorrect date value: '2004-04-31' for column 'c1' at row 1 

      mysql> set @@session.sql_mode='STRICT_TRANS_TABLES,ALLOW_INVALID_DATES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2004-04-31');

      Query OK, 1 row affected (0.02 sec)

    1. NO_ZERO_DATE
 

    「0000-00-00」という日付を受け付けない。 

    INSERT IGNOE及びUPDATE IGNOREで無効化できる。 

2.0000-00-00」日付データ挿入時の挙動

      NO_ZERO_DATE 無し
    STRICT_TRANS_TABLES エラー発生

    挿入されない

    挿入されてしまう
    無し 警告発生

    挿入されてしまう

    挿入されてしまう
 
 
      mysql> show create table tdate¥G

      *************************** 1. row ***************************

             Table: tdate

      Create Table: CREATE TABLE `tdate` (

        `c1` date default NULL

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

      1 row in set (0.00 sec) 

      mysql> insert into tdate values('0000-00-00');

      Query OK, 1 row affected (0.03 sec) 

      mysql> set @@session.sql_mode='NO_ZERO_DATE';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('0000-00-00');

      Query OK, 1 row affected, 1 warning (0.02 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning

         Code: 1265

      Message: Data truncated for column 'c1' at row 1

      1 row in set (0.01 sec) 

      mysql> select * from tdate;

      +------------+

      | c1         |

      +------------+

      | 0000-00-00 |

      | 0000-00-00 |

      +------------+

      2 rows in set (0.00 sec) 

      mysql> set @@session.sql_mode='STRICT_TRANS_TABLES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('0000-00-00');

      Query OK, 1 row affected (0.02 sec) 

      mysql> set @@session.sql_mode='NO_ZERO_DATE,STRICT_TRANS_TABLES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('0000-00-00');

      ERROR 1292 (22007): Incorrect date value: '0000-00-00' for column 'c1' at row 1 

      mysql> insert ignore into tdate values('0000-00-00');

      Query OK, 1 row affected, 1 warning (0.05 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning

         Code: 1265

      Message: Data truncated for column 'c1' at row 1

      1 row in set (0.01 sec)

    1. NO_ZERO_IN_DATE

    ストリクトモード時に、「月」、又は「日」が「0」のデータを挿入しない。 

    INSERT IGNORE及びUPDATE IGNOREで無効化できる。 

3. 月または日が「0」の日付データ挿入時の挙動

      NO_ZERO_IN_DATE 無し
    STRICT_TRANS_TABLES エラー発生

    挿入されない

    挿入されてしまう
    無し 警告発生

    挿入されてしまう

    挿入されてしまう
 
 
      (NO_ZERO_DATEからの続き) 

      mysql> delete from tdate;

      Query OK, 4 rows affected (0.04 sec) 

      mysql> set @@session.sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2006-12-00');

      Query OK, 1 row affected (0.02 sec) 

      mysql> insert into tdate values('2006-00-21');

      Query OK, 1 row affected (0.02 sec) 

      mysql> select * from tdate;

      +------------+

      | c1         |

      +------------+

      | 2006-12-00 |

      | 2006-00-21 |

      +------------+

      2 rows in set (0.01 sec) 

      mysql> set @@session.sql_mode='NO_ZERO_IN_DATE';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2006-12-00');

      Query OK, 1 row affected, 1 warning (0.03 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning

         Code: 1265

      Message: Data truncated for column 'c1' at row 1

      1 row in set (0.01 sec) 

      mysql> select * from tdate;

      +------------+

      | c1         |

      +------------+

      | 2006-12-00 |

      | 2006-00-21 |

      | 0000-00-00 |

      +------------+

      3 rows in set (0.00 sec) 

      mysql> set @@session.sql_mode='NO_ZERO_IN_DATE,STRICT_TRANS_TABLES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2006-12-00');

      ERROR 1292 (22007): Incorrect date value: '2006-12-00' for column 'c1' at row 1

      mysql> insert IGNORE into tdate values('2006-12-00');

      Query OK, 1 row affected, 1 warning (0.03 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning

         Code: 1265

      Message: Data truncated for column 'c1' at row 1

      1 row in set (0.00 sec) 

      mysql> select * from tdate;

      +------------+

      | c1         |

      +------------+

      | 2006-12-00 |

      | 2006-00-21 |

      | 0000-00-00 |

      | 0000-00-00 |

      +------------+

      4 rows in set (0.01 sec) 

      mysql> set @@session.sql_mode='strict_trans_tables';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tdate values('2006-00-00');

      Query OK, 1 row affected (0.11 sec) 

 
 

 

  1. 算術操作(Mathematical Operations)
    1. ERROR_FOR_DIVISION_BY_ZERO

    0で割り算したとき、STRICTモード時にエラーを返す。 

4.0」で割った値

      ERROR_FOR_DIVISION_BY_ZERO 無し
    STRICT_TRANS_TABLES エラー発生

    (挿入できず)

    NULL
    無し 警告発生

    NULL

    NULL
 

    INSERT IGNORE及びUPDATE IGNOREでは警告を発生して、NULLとなる。 

      mysql> set @@session.sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> show create table tq1¥G

      *************************** 1. row ***************************

             Table: tq1

      Create Table: CREATE TABLE `tq1` (

        `c1` int(11) default NULL

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

      1 row in set (0.00 sec) 

      mysql> select c1/0 from tq1;

      +------+

      | c1/0 |

      +------+

      | NULL |

      | NULL |

      +------+

      2 rows in set (0.07 sec) 

      mysql> set @@session.sql_mode='ERROR_FOR_DIVISION_BY_ZERO';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> select c1/0 from tq1;

      +------+

      | c1/0 |

      +------+

      | NULL |

      | NULL |

      +------+

      2 rows in set, 2 warnings (0.00 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Error

         Code: 1365

      Message: Division by 0

      *************************** 2. row ***************************

        Level: Error

         Code: 1365

      Message: Division by 0

      2 rows in set (0.01 sec) 

      mysql> insert into tq1 values(1/0);

      Query OK, 1 row affected, 1 warning (0.02 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Error

         Code: 1365

      Message: Division by 0

      1 row in set (0.00 sec) 

      mysql> select * from tq1;

      +------+

      | c1   |

      +------+

      |  123 |

      |  123 |

      | NULL |

      +------+

      3 rows in set (0.00 sec) 

      mysql> set @@session.sql_mode='ERROR_FOR_DIVISION_BY_ZERO,STRICT_TRANS_TABLES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tq1 values(1/0);

      ERROR 1365 (22012): Division by 0 

      mysql> select c1/0 from tq1;

      +------+

      | c1/0 |

      +------+

      | NULL |

      | NULL |

      | NULL |

      +------+

      3 rows in set, 2 warnings (0.01 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Error

         Code: 1365

      Message: Division by 0

      *************************** 2. row ***************************

        Level: Error

         Code: 1365

      Message: Division by 0

      2 rows in set (0.00 sec) 

      mysql> set @@session.sql_mode='strict_trans_tables';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> select 1/0;

      +------+

      | 1/0  |

      +------+

      | NULL |

      +------+

      1 row in set (0.02 sec)

    1. NO_UNSIGNED_SUBTRACTION
 

    UNSIGNEDで無いINT型数値の引き算の結果を、UNSIGNEDとしない。 

      mysql> set sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table test(c1 bigint unsigned not null);

      Query OK, 0 rows affected (0.13 sec) 

      mysql> create table t1 select c1-1 as c2 from test;

      Query OK, 0 rows affected (0.13 sec)

      Records: 0  Duplicates: 0  Warnings: 0 

      mysql> desc t1;

      +-------+---------------------+------+-----+---------+-------+

      | Field | Type                | Null | Key | Default | Extra |

      +-------+---------------------+------+-----+---------+-------+

      | c2    | bigint(21) unsigned | NO   |     | 0       |       |

      +-------+---------------------+------+-----+---------+-------+

      1 row in set (0.03 sec) 

      mysql> set sql_mode='no_unsigned_subtraction';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table t2 select c1-1 as c2 from test;

      Query OK, 0 rows affected (0.09 sec)

      Records: 0  Duplicates: 0  Warnings: 0 

      mysql> desc t2;

      +-------+------------+------+-----+---------+-------+

      | Field | Type       | Null | Key | Default | Extra |

      +-------+------------+------+-----+---------+-------+

      | c2    | bigint(21) | NO   |     | 0       |       |

      +-------+------------+------+-----+---------+-------+

      1 row in set (0.00 sec)

    1. REAL_AS_FLOAT
 

    REAL型をFLOAT型として扱う。

    デフォルトでは、MySQLはREAL型をDOUBLE型として扱う。 

      mysql> set sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table tr(c1 real);

      Query OK, 0 rows affected (0.12 sec) 

      mysql> show create table tr¥G

      *************************** 1. row ***************************

             Table: tr

      Create Table: CREATE TABLE `tr` (

        `c1` double default NULL

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

      1 row in set (0.00 sec) 

      mysql> set sql_mode='REAL_AS_FLOAT';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table tr2(c1 real);

      Query OK, 0 rows affected (0.10 sec) 

      mysql> show create table tr2\G

      *************************** 1. row ***************************

             Table: tr2

      Create Table: CREATE TABLE `tr2` (

        `c1` float default NULL

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

      1 row in set (0.00 sec)

 

 

  1. SQLクエリ
    1. ANSI_QUOTES

    識別子が予約語である場合や、識別子に特殊文字が含まれている場合は、引用符として使用したバッククォート(「`」)でその識別子(データベース名、テーブル名、カラム名)を必ず囲む必要がある。 

    ANSI_QUOTESを有効にすることで、バッククォートに加えて、ダブルクォートも使えるようにする。 

      mysql> set sql_mode="";

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table "test"(a int);

      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that

      corresponds to your MySQL server version for the right syntax to use near '"test

      "(a int)' at line 1 

      mysql> set sql_mode="ansi_quotes";

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table "test"(a int);

      Query OK, 0 rows affected (0.08 sec)

    1. IGNORE_SPACE

    関数名と(の間にスペースを許可する。

    この場合、予約後などをテーブル名などに利用するときはバッククォートなどでくくる必要がある。

      mysql> CREATE TABLE abs (i INT);

      ERROR 1064 (42000): You have an error in your SQL syntax 

      mysql> CREATE TABLE `abs` (i INT);

      Query OK, 0 rows affected (0.00 sec)

    1. NO_BACKSLASH_ESCAPES

    このオプションによって、バックスラッシュでエスケープせずに、通常の文字として扱う。 

      mysql> set @@session.sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table tbsl(c1 varchar(20));

      Query OK, 0 rows affected (0.20 sec) 

      mysql> insert into tbsl values ('¥¥'), ('¥a');

      Query OK, 2 rows affected (0.02 sec)

      Records: 2  Duplicates: 0  Warnings: 0 

      mysql> select * from tbsl;

      +------+

      | c1   |

      +------+

      | \    |

      | a    |

      +------+

      2 rows in set (0.00 sec) 

      mysql> set @@session.sql_mode='NO_BACKSLASH_ESCAPES';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> insert into tbsl values ('\\'), ('\a');

      Query OK, 2 rows affected (0.02 sec)

      Records: 2  Duplicates: 0  Warnings: 0 

      mysql> select * from tbsl;

      +------+

      | c1   |

      +------+

      | \    |

      | a    |

      | \\   |

      | \a   |

      +------+

      4 rows in set (0.00 sec)

    1. ONLY_FULL_GROUP_BY

    集合関数とGROUP BYの組み合わせで、SELECTする出力カラムのうち、集合関数以外のカラム全てをGROUP BYで指定することを強要する。 

      mysql> set @@session.sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> create table tgroup(c1 int, c2 int, c3 int);

      Query OK, 0 rows affected (0.11 sec) 

      mysql> insert into tgroup values (1,1,2), (1,2,3), (1,3,1), (2,1,3),

      mysql> (2,1,4);

      Query OK, 5 rows affected (0.03 sec)

      Records: 5  Duplicates: 0  Warnings: 0 

      mysql> select c1, c2, max(c3) from tgroup group by c1, c2;

      +------+------+---------+

      | c1   | c2   | max(c3) |

      +------+------+---------+

      |    1 |    1 |       2 |

      |    1 |    2 |       3 |

      |    1 |    3 |       1 |

      |    2 |    1 |       4 |

      +------+------+---------+

      4 rows in set (0.00 sec) 

      mysql> select c1, c2, max(c3) from tgroup group by c1;

      +------+------+---------+

      | c1   | c2   | max(c3) |

      +------+------+---------+

      |    1 |    1 |       3 |

      |    2 |    1 |       4 |

      +------+------+---------+

      2 rows in set (0.00 sec) 

      mysql> select c1, c2, max(c3) from tgroup group by c1 having c2=3;

      Empty set (0.00 sec) 

      mysql> set sql_mode='ONLY_FULL_GROUP_BY';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> select c1, c2, max(c3) from tgroup group by c1, c2;

      +------+------+---------+

      | c1   | c2   | max(c3) |

      +------+------+---------+

      |    1 |    1 |       2 |

      |    1 |    2 |       3 |

      |    1 |    3 |       1 |

      |    2 |    1 |       4 |

      +------+------+---------+

      4 rows in set (0.00 sec) 

      mysql> select c1, c2, max(c3) from tgroup group by c1;

      ERROR 1055 (42000): 'test.tgroup.c2' isn't in GROUP BY 

      mysql> select c1, c2, max(c3) from tgroup group by c1 having c2=3;

      ERROR 1055 (42000): 'test.tgroup.c2' isn't in GROUP BY

    1. PIPES_AS_CONCAT

    CONCAT()関数と同様に「||」を扱う。 
     

      mysql> set sql_mode='';

      Query OK, 0 rows affected (0.00 sec) 

      mysql> select '1' || '0';

      +------------+

      | '1' || '0' |

      +------------+

      |          1 |

      +------------+

      1 row in set (0.00 sec) 

      mysql> select 'abc' || 'def';

      +----------------+

      | 'abc' || 'def' |

      +----------------+

      |              0 |

      +----------------+

      1 row in set, 2 warnings (0.00 sec) 

      mysql> show warnings\G

      *************************** 1. row ***************************

        Level: Warning