我想根据属性id从上面的4个表中检索所有数据

时间:2014-10-09 08:38:36

标签: mysql sql

基本上这个属性代理的网站,

我想根据属性id检索以下4个表中的所有列。

简短说明: wp_tm_properties - >将添加我的主要属性名称(id,property_name)

wp_tm_sub_properties - >将根据主要属性添加我的子属性

wp_tm_tenants - >将根据财产和附件添加我的租户名称和其他相关信息。属性

wp_tm_reports - >将根据属性和子属性添加我的租户报告

CREATE TABLE IF NOT EXISTS `wp_tm_properties` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `property_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

CREATE TABLE IF NOT EXISTS `wp_tm_sub_properties` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `prop_id` int(11) NOT NULL,
  `sub_property_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

CREATE TABLE IF NOT EXISTS `wp_tm_tenants` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `prop_id` int(11) NOT NULL,
  `sub_property_id` int(11) NOT NULL,
  `ten_name` varchar(255) DEFAULT NULL,
  `ten_phone` varchar(255) DEFAULT NULL,
  `ten_email` varchar(255) DEFAULT NULL,
  `ten_address` varchar(255) DEFAULT NULL,
  `ten_sdate` date NOT NULL,
  `ten_edate` date NOT NULL,
  `contract_form` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;


CREATE TABLE IF NOT EXISTS `wp_tm_reports` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `prop_id` int(11) NOT NULL,
  `sub_property_id` int(11) NOT NULL,
  `ten_name` varchar(255) NOT NULL,
  `rep_sdate` date NOT NULL,
  `rep_des` varchar(255) NOT NULL,
  `rep_action` varchar(155) NOT NULL,
  `rep_edate` int(11) NOT NULL,
  `rep_status` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4

1 个答案:

答案 0 :(得分:0)

使用连接来连接相关列上的表:

select * 
from `wp_tm_properties` p
join `wp_tm_sub_properties` sp on p.`id` = sp.`prop_id`
join `wp_tm_tenants` t on t.`prop_id` = p.`id` and t.`sub_property_id` = sp.`id`
join `wp_tm_reports` r on r.`prop_id` = p.`id` and r.`sub_property_id` = sp.`id`

这使用INNER JOIN并且只返回所有表中存在匹配数据的行;如果要为没有租户的属性返回行,则应使用LEFT JOIN代替。

此外,列ten_name似乎在租户和报告之间重复;也许后一个表应该有一列tenant_id而不是?