2014-10-30 107 views
0

我有三個對我很重要的表:customer,client_assignment和customer_products。最後兩個是多對多關係的分配表。MySQL與多對多關係的多重聯接

在client_assignment中,client類型的客戶與另一個客戶(其中customer_id是父項,client_id子項)關聯。
在customer_product中,我將顧客與產品聯繫起來。

客戶不能與產品關聯,他從他的父母客戶那裏繼承。在下面的例子中,這意味着,那個Foo-1也有產品3,因爲他的父親(Foo)有它。

customer (Customers): 
+-------------+-------+----------+ 
| customer_id | name | type  | 
+-------------+-------+----------+ 
|   1 | Foo | customer | 
|   2 | Foo-1 | client | 
|   3 | Foo-2 | client | 
|   4 | Bar | customer | 
|   5 | Foob | customer | 
+-------------+-------+----------+ 

client_assignment (Customer/Client-Assignment): 
+-------------+-----------+ 
| customer_id | client_id | 
+-------------+-----------+ 
|   1 |   2 | 
|   1 |   3 | 
+-------------+-----------+ 

customer_product (Customer/Product-Assignment): 
+-------------+------------+ 
| customer_id | product_id | 
+-------------+------------+ 
|   1 |   3 | 
|   1 |   4 | 
|   1 |   5 | 
|   4 |   3 | 
|   5 |   7 | 
+-------------+------------+ 

我要做到以下幾點:選擇所有客戶了與產品X相關聯各自的客戶

我的產品3期望的結果是這樣的:

+-------------+-------+--------+ 
| customer_id | name | parent | 
+-------------+-------+--------+ 
|   1 | Foo | null | 
|   2 | Foo-1 | 1  | 
|   3 | Foo-2 | 1  | 
|   4 | Bar | null | 
+-------------+-------+--------+ 

我一直在想這個問題,看起來相當複雜。我試着像下面這樣加入他們:

SELECT c2.customer_id, c2.name, c1.customer_id as parent 
    FROM customer_product p, customer c1, customer c2, client_assignment a 
WHERE 
      c1.customer_id = p.customer_id 
     AND c2.customer_id = a.client_id 
     AND a.customer_id = c1.customer_id 
     AND p.product_id = 3 

我知道,這個查詢將不會給我確切想要的結果,但我已經創造了它下手。關於它的主要問題是,它只會選擇客戶,而不是客戶自己。因此,我只得到Foo-1Foo-2因此,而不是BarFoo

問題是:這是相當容易實現的,以及如何?

回答

2

你可以再寫SELECT是獲取客戶本身,而將兩者結合起來使用UNION

SELECT c.customer_id, c.name, NULL AS parent 
    FROM customer AS c 
    JOIN customer_product AS p ON c.customer_id = p.customer_id 
WHERE c.type = 'customer' 
    AND p.product_id = 3 

UNION 

SELECT c2.customer_id, c2.name, c1.customer_id AS parent 
FROM customer_product AS p 
JOIN customer AS c1 ON c1.customer_id = p.customer_id 
JOIN client_assignment AS a ON a.customer_id = c1.customer_id 
JOIN customer AS c2 ON c2.customer_id = a.client_id 
WHERE c2.type = 'client' 
    AND p.product_id = 3 
+0

我甚至沒有想過使用'UNION'。這工作正如我想要的,謝謝! :) – Padarom 2014-10-30 09:27:27

0

因爲你必須讓客戶端的兩個客戶端的名稱和家長,這樣做的一個事情是這樣的通過使用UNION

with customer_names as (select customer_id from s_customer_product where product_id =3), 

client_names as (select client_id , customer_id as Parent_id from s_client_assignment join customer_names using(customer_id)) 

select customer_id , name , null as Parent from s_customers join customer_names using(customer_id) 

union 

select a.client_id , b.name , a.parent_id as Parent from client_names a, s_customers b where b.customer_id = a.client_id;