简体   繁体   English

MYSQL 复杂连接一对多

[英]MYSQL Complex Join one-to-many

I have the following tables:我有以下表格:

clients:客户:

| id | name     | code | zone  |
--------------------------------
| 1  | client 1 | a1b1  | zone1|
| 2  | client 2 | a2b2  | zone2|

contacts:联系人:

| id_contact | first_name  | last_name |
----------------------------------------
| 11         | first1      | last1     |
| 22         | first2      | last2     |
| 33         | first3      | last3     | 
| 44         | first4      | last4     |

client_contacts:客户联系人:

| id_client | id_contact |
--------------------------
| 1         | 11         |
| 1         | 22         |
| 1         | 33         |
| 2         | 11         |
| 2         | 44         |

offers:优惠:

| id_offer | id_client | value |
--------------------------
| 111      | 1         |   100 |
| 222      | 1         |   200 |
| 333      | 1         |   300 |
| 444      | 2         |   400 |

I would like through a optimal select to obtain:我想通过一个最优选择来获得:

| id_client | name     | code | zone  | contacts_pers | total_offer_value |
----------------------------------------------------------------------------
| 1         | client 1 | a1b1 | zone1 | first1 last1; | 600               |
                                        first2 last2;
                                        first3 last3;
| 2         | client 2 | a2b2 | zone2 | first1 last1; | 400               |
                                        first4 last4;

I know how to get the desired result with "group_concat" and stored procedures for "total_offer_value".我知道如何使用“group_concat”和“total_offer_value”的存储过程获得所需的结果。 But how to get the desired result from a single efficient select?但是如何从一个有效的选择中得到想要的结果呢?

SELECT c.id, c.name, c.code, c.zone, GROUP_CONCAT(DISTINCT CONCAT(co.first_name, " ", c.last_name) SEPARATOR ";") AS contact_pers, func_total_offer_value(c.id) AS total_offer_value SELECT c.id, c.name, c.code, c.zone, GROUP_CONCAT(DISTINCT CONCAT(co.first_name, " ", c.last_name) SEPARATOR ";") AS contact_pers, func_total_offer_value(c.id) AS total_offer_value

FROM clients c来自客户 c

LEFT OUTER JOIN (client_contacts cc, contacts co) ON ( c.id = cc.id_client AND cc.id_contact = co.id_contact ) GROUP BY c.id LEFT OUTER JOIN (client_contacts cc, contacts co) ON ( c.id = cc.id_client AND cc.id_contact = co.id_contact ) GROUP BY c.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM