MYSQL计算2个表中的相关行

时间:2012-04-27 18:03:17

标签: mysql

我有3张桌子

products table
productid   productname
---------   -----------
 1          product 1
 2          product 2
 5          product 3
 10         product 4
 11         product 5
 12         product 6

accounts_products table
id  productid   accountid
--  ---------   ---------
1   1           accountid 1
2   10          accountid 2
3   2           accountid3

leads_products table
id  productid    leadid
--  ---------    ---------
1   1            leadid 1
2   5            leadid 2
3   2            leadid 3

我正在尝试根据相同的产品计算lead_products和accounts_products表中的总产品数量。

Expected result

Product ID    Product Name    Total
-----------   ------------    --------
1             product 1         2
2             product 2         2
5             product 3         1
10            product 4         1

到目前为止我试过了

SELECT p.productid as 'Product ID', 
       p.productname as 'Product Name', 
       COUNT(*) as 'Total' FROM products p
INNER JOIN leads_products l ON (l.productid=p.productid)
INNER JOIN accounts_products a ON (a.productid=p.productid)
GROUP BY p.productname,p.productid

以上查询计算并显示比预期更高的数字。

我希望这是有道理的。

2 个答案:

答案 0 :(得分:8)

试试这个:

SELECT p.productid as 'Product ID', 
       p.productname as 'Product Name', 
       (SELECT COUNT(*)
        FROM leads_products AS l
        WHERE l.productid = p.productid) + 
       (SELECT COUNT(*)
        FROM accounts_products AS a
        WHERE a.productid=p.productid) AS 'Total'
FROM products AS p

http://www.sqlfiddle.com/#!2/f8472/5

使用JOIN的替代方法(更好的性能):

SELECT p.productid as 'Product ID', 
       p.productname as 'Product Name', 
       IFNULL(l.count, 0) + IFNULL(a.count, 0) as 'Total'
FROM products AS p
LEFT JOIN (
    SELECT productid, COUNT(*) AS count
    FROM leads_products
    GROUP BY productid
) AS l
ON l.productid = p.productid
LEFT JOIN (
    SELECT productid, COUNT(*) AS count
    FROM accounts_products
    GROUP BY productid
) AS a
ON a.productid = p.productid

http://www.sqlfiddle.com/#!2/f8472/33

答案 1 :(得分:-1)

我使用p.products的左连接来保留所有产品,然后计算每个列表中的产品并将它们一起添加。先工作尝试。可能有十亿种方法可以做到这一点。

SELECT p.productid 'Product ID', 
       p.productname 'Product Name', 
       COUNT(a.accountid) + COUNT(l.leadid) total
FROM products p
LEFT JOIN accounts_products a ON p.productid = a.productid
LEFT JOIN leads_products l ON p.productid = l.productid
GROUP BY p.productid

http://www.sqlfiddle.com/#!2/f8472/37