セッションの話はもうちょっとあとで。

***

たとえば、

mysql> show columns from bbs_message;
+-------------+------------------+------+-----+-------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+-------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| union_id | int(10) unsigned | NO | | 0 | |
| user | varchar(16) | NO | | dummy | |
| title | varchar(100) | NO | | dummy_title | |
| message | text | YES | | NULL | |
| create_date | datetime | YES | | NULL | |
+-------------+------------------+------+-----+-------------+----------------+
6 rows in set (0.12 sec)

mysql> show columns from bbs_reply;
+-------------+------------------+------+-----+-------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+-------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| parent_id | int(10) unsigned | NO | | 1 | |
| union_id | int(10) unsigned | NO | | 0 | |
| user | varchar(16) | NO | | dummy | |
| title | varchar(100) | NO | | dummy_reply | |
| message | text | YES | | NULL | |
| create_date | datetime | YES | | NULL | |
+-------------+------------------+------+-----+-------------+----------------+
7 rows in set (0.05 sec)


みたいなテーブル二つで「親記事-返信」みたいなのを考えた。

このやりかただと一応「親記事返信関係なしで通しで表示」もできる。そのために union_id というフィールドを用意した。

mysql> select union_id, user, title, message, "MESSAGE" AS "whitch?"
-> from bbs_message
-> UNION
-> select union_id, user, title, message, "REPLY" AS "whitch?"
-> from bbs_reply
-> order by union_id desc
-> limit 0, 10;

例えばこんなのが出てくる。
+----------+--------+-------------+------------------+---------+
| union_id | user | title | message | whitch? |
+----------+--------+-------------+------------------+---------+
| 26 | udzura | test_title! | テストです。。。 | REPLY |
| 25 | poyo | test_title! | テストです。。。 | REPLY |
| 24 | udzura | test_title! | テストです。。。 | REPLY |
| 23 | poyo | test_title! | テストです。。。 | REPLY |
| 22 | udzura | test_title! | テストです。。。 | MESSAGE |
| 21 | hoge | test_title! | テストです。。。 | MESSAGE |
| 20 | udzura | test_title! | テストです。。。 | REPLY |
| 19 | hoge | test_title! | テストです。。。 | REPLY |
| 18 | udzura | test_title! | テストです。。。 | MESSAGE |
| 17 | udzura | test_title! | テストです。。。 | REPLY |
+----------+--------+-------------+------------------+---------+
10 rows in set (0.00 sec)


UNION 構文ですね。

UNION なんて便利なものがあるなんて最近知ったわけで、もっと SQL に定評のある人になりたいと思いました。池上の守備並みに。