1
我有三個表:你如何獲得相關表中的字段的總數?
區表:
+--------------------------+---------------------+------+-----+---------+----------------+
| 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
表中有一個名爲impressions_count
的字段。我想要做的是選擇Retailers
表中的所有記錄,同時加入Locations
表和Zones
表。
從本質上講,我覺得我需要在Retailers
返回Locations
每個匹配記錄的SUM(Zones.impressions_count),然後的一個總和爲每個記錄。我一直在頭撞牆,並感謝任何指導!
最後:我的結果集應該是這樣的:
**from retailers**
id,
account_rep_id,
lead_source_id,
industry_id,
impressions_count, // <- sum of related records in `Zones`
這非常接近!唯一的問題是,它不會返回零展示次數的零售商。但是,這可能會用不同的連接修復。 –
很容易將內部改爲左邊。我們可能需要合併...(更新) – xQbert
像冠軍一樣工作。乾杯! –