2011-01-19 7 views
0

3 개의 테이블이 있지만 다른 테이블 수만 조인 할 수 있습니다. 아래를 참조하십시오. 아래는 매력처럼 작동하지만 다른 테이블에서 다른 "개수"를 추가해야합니다.이중 조인을 사용하는 mysql 쿼리

있다 "ci_nomatch"라는 3 테이블이고 (많은 많은) 여러 항목을 가지고 있지만 난 단지 그 테이블의 수를 필요로 할 수있는 을 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

작동하지 않는 두 번째 조인 코드를 표시하면 해결해 드리겠습니다. –

답변

1

댓글에 대한 @updated 선택

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 

에서 직접 하위 쿼리 수 있습니다. 추가 열 "(matchcount - othercount) AS deducted"를 포함하면 하위 쿼리로 가장 잘 수행됩니다.

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

+0

[ci_nomatch라는 세 번째 테이블이 있으며 ci_address_book.reference에 대한 참조가 포함되어 있습니다] - ci_nomatch의 어떤 필드가 book.reference에 조인합니까? – RichardTheKiwi

+0

이것이 작동하는 것으로 나타났습니다. SELECT c. * IFNULL (p.total 0) matchcount AS, \t (SELECT COUNT (*) ci_falsepositives FROM \t N 가 \t WHERE n.addressbook_id = c.reference \t) ci_address_book C로부터 AS othercount LEFT이 \t 가입 matchcount의 DESC LIMIT 0, 이제 15 – renevdkooi

관련 문제