性格いい人が優勝

Mysqlで複数テーブルの参照

お世話になります。Mysqlについて質問させてください。
現在、それぞれnameとdateとflagの3フィールドをもつテーブルが、2つあります。
もともと別の用途で準備したものなのですが、
2つのテーブルのflagを参照して、1のものだけdate順に並べることが出来るでしょうか?


■テーブル1
-----------------------------
 name |  date  |flag|
-----------------------------
 田中 | 2010-06-01 | 1
-----------------------------
 山田 | 2010-09-01 | 1
-----------------------------
 田辺 | 2010-10-01 | 2
-----------------------------
 田所 | 2010-11-01 | 2
-----------------------------

■テーブル2
-----------------------------
 name |  date  |flag|
-----------------------------
 加藤 | 2010-10-01 | 1
-----------------------------
 佐藤 | 2010-07-01 | 1
-----------------------------
 織田 | 2010-12-01 | 2
-----------------------------
 斎藤 | 2010-01-01 | 2
-----------------------------

■求める結果
-----------------------------
 name |  date  |flag|
-----------------------------
 田中 | 2010-06-01 | 1
-----------------------------
 佐藤 | 2010-07-01 | 1
-----------------------------
 山田 | 2010-09-01 | 1
-----------------------------
 加藤 | 2010-10-01 | 1
-----------------------------

具体的なSQL文でなくとも構いません。参考になるような情報、サイトをご存じでしたら、教えてください。
よろしくお願いします。

A 回答 (2件)

union で2つのテーブルを連結。


t1は、テーブル1、t2はテーブル2です。

select name, date, flg
from
(select * from t1 union select * from t2) a
where flg=1 order by date;

(select * from t1 where flg=1)
union
(select * from t2 where flg=1)
order by date;

上記のどちらでもOKですが、
下記は、順番が狂う可能性があるのでダメです。
(select * from t1 where flg=1 order by date)
union
(select * from t2 where flg=1 order by date);
    • good
    • 0
この回答へのお礼

ありがとうございます!
無事に解決できました!大変助かりました。ありがとうございました。

お礼日時:2010/08/26 22:32

Oracleだったら



select name, date, flag from テーブル1 where flag = 1
union
select name, date, flag from テーブル2 where flag = 1

なんですけど、どうなります?
    • good
    • 0
この回答へのお礼

ありがとうございますm(__)m
unionで解決できました。助かりました。

お礼日時:2010/08/26 22:33

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!