2011-02-10 50 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