2011-02-10 51 views
0

我試圖從三個不同的表中一次獲取數據,並且我不認爲我完全理解連接正確,因爲我無法快速完成任何操作。
例如,可以說表格是houses,sellersselling_detailshousessellersselling_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`) 

現在,要使事情變得非常複雜,selling_details表中可能會有很多行鏈接houseseller。如果存在這些行中的一個或多個,我只想要最近的那個行date;如果沒有這樣的行,就像上面的例子結果一樣返回房屋和賣方組合。

+0

如果你有一個特定的模式,並張貼,這將有助於使答案直接使用。 – wallyk 2011-02-10 02:29:11

+0

當我發佈時,我有點慌張,但我更新了信息。我簡單地把問題簡單化了一下。 – 2011-02-10 05:54:43

回答

0

CROSS JOIN房子和賣家,然後離開加盟找到的任何細節組合

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