2014-07-15 75 views
1

我有三個具有相同結構的表。添加多個表的字段問題

表1

id | email   | count  
1 | [email protected] | 5  
2 | [email protected] | 5 
3 | [email protected] | 5 

表2

id | email   | count  
1 | [email protected] | 50  
2 | [email protected] | 50  
3 | [email protected] | 50 

表3

id | email   | count  
1 | [email protected] | 40  
2 | [email protected] | 45  
3 | [email protected] | 50 

現在我想什麼是表1,爲FIR st記錄「[email protected]」,我需要下兩個表的「count」字段的總和。所以我用下面的查詢

SELECT (IFNULL(sum(distinct(table2.count)), 0) +  
IFNULL(sum(distinct(table3.count)), 0)) as total 
FROM table1 
LEFT JOIN table2 ON table1.email = table2.email 
LEFT JOIN table3 ON table1.email = table3.email 
WHERE table1.email = '[email protected]' 

該查詢給我下面的記錄:

185

但結果應該是如下:

235

這是因爲我有添加字段時使用不同。但是如果我不使用截然不同的東西,它會給我285

請幫忙。我該怎麼辦?

+1

是[這](http://sqlfiddle.com/#!2/6ddb9/19)你的意思呢? –

+0

謝謝@Jack它適用於我.. –

回答

2

你的問題是因爲,首先,你使用的是LEFT JOIN(沒有意義,因爲NULL記錄不會提供任何內容),第二,這就是JOIN的工作原理。用查詢說明:

SELECT 
    t1.id AS id_1, 
    t1.email AS email_1, 
    t1.count AS count_1, 
    t2.id AS id_2, 
    t2.email AS email_2, 
    t2.count AS count_2, 
    t3.id AS id_3, 
    t3.email AS email_3, 
    t3.count AS count_3 
FROM 
    table1 AS t1 
    INNER JOIN table2 AS t2 ON t1.email=t2.email 
    INNER JOIN table3 AS t3 ON t1.email=t3.email 
WHERE 
    t1.email='[email protected]' 

(小提琴是here)。正如你所看到的,你會從第二個和第三個表中獲得重複的id - 是的,那是因爲有多行用於連接條件。

要解決你的問題,你可以通過id添加區分到連接(以及後來用變量或類似的過濾),但我不會推薦它。 JOIN根本不是你的問題。使用UNION,如:

SELECT 
    SUM(`count`) AS s 
FROM 
    (
    SELECT 
     table2.count 
    FROM 
     table2 
    WHERE 
     email='[email protected]' 
    UNION ALL 
    SELECT 
     table3.count 
    FROM 
     table3 
    WHERE 
     email='[email protected]' 
) AS u 

(見fiddle