【发布时间】:2016-03-07 16:38:54
【问题描述】:
我有三张桌子:
区域表:
+--------------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| location_id | bigint(20) unsigned | NO | MUL | NULL | |
| impressions_count | bigint(20) unsigned | YES | | 0 | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+--------------------------+---------------------+------+-----+---------+----------------+
位置表:
+----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| retailer_id | bigint(20) unsigned | NO | MUL | NULL | |
| zones_count | int(10) unsigned | YES | | 0 | |
| contacts_count | int(10) unsigned | YES | | 0 | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+----------------+---------------------+------+-----+---------+----------------+
零售商表:
+---------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| account_rep_id | bigint(20) unsigned | YES | MUL | NULL | |
| leadsource_id | bigint(20) unsigned | YES | MUL | NULL | |
| industry_id | bigint(20) | NO | MUL | NULL | |
| name | varchar(100) | NO | | NULL | |
| locations_count | int(10) unsigned | YES | | 0 | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+---------------------+---------------------+------+-----+---------+----------------+
我想做的事:
我正在从Retailers 表中选择所有记录。 Retailers 表在Locations 中有很多记录,而Zones 又在Zones 中有很多记录。
Zones 表有一个名为impressions_count 的字段。我想要做的是从Retailers 表中选择所有记录,同时加入Locations 表和Zones 表。
基本上,我认为我需要为Locations 中的每个匹配记录返回一个 SUM(Zones.impressions_count),然后为Retailers 中的每个记录返回一个总和。我已经把头撞在墙上一段时间了 - 感谢任何指导!
最终:我的结果集应该如下所示:
**from retailers**
id,
account_rep_id,
lead_source_id,
industry_id,
impressions_count, // <- sum of related records in `Zones`
【问题讨论】: