带双连接的mysql查询

时间:2011-01-19 10:10:57

标签: sql mysql

我有3张桌子,但我只能加入另一张桌子。见下文。 下面的一个就像一个魅力,但我需要从另一个表中添加另一个“计数”。

有一个名为“ci_nomatch”的第3个表,其中包含对ci_address_book.reference的引用 可能有多个条目(许多条目很多),但我只需要该表的计数。

所以如果ci_address_book有一个名为“item1”,“item 2”,“item3”的条目 和ci_nomatch会有“1,item1,user1”,“2,item1,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

1 个答案:

答案 0 :(得分: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