2011-01-19 101 views
0

我有3個表,但我只能加入另一個表計數。見下文。 下面的工作就像一個魅力,但我需要從另一個表中添加另一個「計數」。雙連接mysql查詢

有一個名爲「ci_nomatch」第三表,幷包含一個參考ci_address_book.reference 可能有多個條目(很多很多),但我只需要該表的計數。

所以如果ci_address_book將有項叫 「物品1」, 「項目2」, 「項目3」 和ci_nomatch將產生 「1,物品1,用戶1」, 「2,物品1,USER4」

我會喜歡在查詢中爲Item1返回「2」。

任何想法?我嘗試了另一個連接,但它告訴我該引用不存在,而它的確存在!

SELECT c.*, IFNULL(p.total, 0) AS matchcount 
FROM ci_address_book c 
LEFT JOIN (
    SELECT addressbook_id, COUNT(match_id) AS total 
    FROM ci_matched_sanctions 
    GROUP BY addressbook_id 
) AS p 
ON c.id=p.addressbook_id 
ORDER BY matchcount DESC 
LIMIT 0,15 
+0

顯示第二次連接的代碼不起作用,我們將嘗試爲您進行調試。 – 2011-01-19 10:22:36

回答

1

你可以在選擇

SELECT c.*, IFNULL(p.total, 0) AS matchcount, 
    (SELECT COUNT(*) FROM ci_nomatch n on n.reference = c.reference) AS othercount 
FROM ci_address_book c 
LEFT JOIN (
    SELECT addressbook_id, COUNT(match_id) AS total 
    FROM ci_matched_sanctions 
    GROUP BY addressbook_id 
) AS p 
ON c.id=p.addressbook_id 
ORDER BY matchcount DESC 
LIMIT 0,15 

@updated徵求意見直接子查詢它。包括一個額外的列「(matchcount - othercount)AS扣除」最好通過子查詢完成。

SELECT *, matchcount - othercount AS deducted 
FROM 
(
    SELECT c.* , IFNULL(p.total, 0) AS matchcount, (
     SELECT COUNT(*) FROM ci_falsepositives n 
     WHERE n.addressbook_id = c.reference) AS othercount 
    FROM ci_address_book c 
    LEFT JOIN (
     SELECT addressbook_id, COUNT(match_id) AS total 
     FROM ci_matched_sanctions GROUP BY addressbook_id) AS p 
     ON c.id = p.addressbook_id ORDER BY matchcount DESC LIMIT 0 , 15 
) S 
+0

它給了我一個錯誤「on n.reference = c.reference」 – renevdkooi 2011-01-19 10:33:33