2011-02-10 11 views
0

私は一度に3つの異なるテーブルからデータを取得しようとしています。
たとえば、テーブルがhouses,sellers、およびselling_detailsであるとします。 housesおよびsellersは、selling_detailsでリンクされています。seller_idhouse_idとさらに価格やユーザーへのリンクなどの情報があります。MySQLの結合 - 3つのテーブルからすべてのデータを取得する

システム内のすべての住宅を返すクエリを作成し、すべての売り手にマッチさせ、存在する場合は売り上げの詳細をリストしたいと考えています。例:

+------------+-------------+-------------------------+----------------------+-----------+ 
| house.name | seller.name | selling_details.details | selling_details.date | user.name | 
+------------+-------------+-------------------------+----------------------+-----------+ 
| One  | One   | details     | 2011-02-18   | bobby  | 
| One  | Two   | details     | 2011-02-24   | frank  | 
| One  | Three  | NULL     | NULL     | NULL  | 
| One  | Four  | NULL     | NULL     | NULL  | 
| Two  | One   | details     | 2011-01-16   | ned  | 
| Two  | Two   | NULL     | NULL     | NULL  | 
| Two  | Three  | details     | 2011-02-12   | will  | 
| Two  | Four  | NULL     | NULL     | NULL  | 
+------------+-------------+-------------------------+----------------------+-----------+ 

これについては、最も簡単な方法はありますか。

編集:だけに、今

create table `house` (`id` int not null auto_increment, `name` varchar(255) null, primary key (`id`)) 
create table `seller` (`id` int not null auto_increment, `name` varchar(255) null, primary key (`id`)) 
create table `user` (`id` int not null auto_increment, `name` varchar(255) null, primary key (`id`)) 
create table `selling_details` (`id` int not null auto_increment, `details` varchar(255) not null, date datetime not null, `house_id` int null, `seller_id` int null, `user_id` int not null, primary key (`id`)) 

alter table `selling_details` add index `FK_selling_details_user` (`user_id`), add constraint `FK_selling_details_user` foreign key (`user_id`) references `user` (`id`) 
alter table `selling_details` add index `FK_selling_details_house` (`house_id`), add constraint `FK_selling_details_house` foreign key (`house_id`) references `house` (`id`) 
alter table `selling_details` add index `FK_selling_details_seller` (`seller_id`), add constraint `FK_selling_details_seller` foreign key (`seller_id`) references `seller` (`id`) 

:私がここにいくつかの詳細だ問題をoversimplifyしようとしているようだ:ここで

は、私が使用しているスキーマの一部です実際には複雑になりますが、housesellerをリンクするselling_detailsテーブルには多くの行があります。これらの行が1つまたは複数存在する場合は、最新のdateの行のみが必要です。そのような行がない場合でも、上の例の結果と同じように、家と売り手の組み合わせを返します。

+0

のための任意の詳細を見つけるために参加し、左。 – wallyk

+0

私はこれを投稿したときに急いでいましたが、情報を更新しました。私はまず問題を少し単純化していました。 –

答えて

0

クロス家と売り手への参加は、その後、あなたが特定のスキーマを持っていると答えが直接使用できるよう助けること、それを投稿した場合の組み合わせ

select h.house_id, s.seller_id, sd.details 
from houses h 
cross join sellers s 
left join selling_details sd 
    on sd.seller_id = s.seller_id 
    and sd.house_id = h.house_id 
order by h.house_id, s.seller_id 
+0

私は物事を自分で簡単にするために複数のクエリを使用することになりましたが、クロスジョインを指摘すると私はそれを見て、将来的には便利になるでしょう。 –

関連する問題