如何使用左连接的用户聚合功能? MySQL的

时间:2014-11-14 10:47:50

标签: mysql sql left-join aggregate

我有这个问题:

SELECT business.bussId, COUNT(invoices.userId) as invoices, COUNT(rating.bussId) as ratingCount ,
       FROM business
       LEFT JOIN invoice ON (invoice.bussId = business.bussId AND invoice.userId = '3000' )
       LEFT JOIN rating ON (rating.bussId = business.bussId )
       WHERE business.bussId=100

COUNT(invoices.userId)用户应该返回发票表中的行数,其中userId = 3000 AND bussId = 100。 换句话说,这个查询:

SELECT COUNT(*) as invoice FROM `invoices` WHERE bussId = '100' AND userId = '30000'.

第二个查询返回COUNT(*)= 3和第一个查询(当我用户LEFT JOIN时)它返回15,如何修复?

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

SELECT business.bussId, (select count(invoices.userId) from invoice where invoice.bussId = a.bussId AND invoice.userId = '3000' ) as invoices, (select COUNT(rating.bussId) from rating where rating.bussId = a.bussId ) as ratingCount ,
       FROM business a
              WHERE business.bussId=100

答案 1 :(得分:0)

您尚未发布任何测试数据或任何表格声明,因此这是对这些数据进行假设。

您当前的查询将获得企业的每种发票和评级组合。因此,如果有3个发票和5个评级,将产生15个组合。

这通常可以通过使用COUNT(DISTINCT)来修复,但是当你是一个常数时,你正在计算发票的用户ID数。

假设您的发票表和评级表都有名为id的唯一键,那么您应该能够将这些字段的计数更改为不同的计数: -

SELECT business.bussId, COUNT(DISTINCT invoices.id) as invoices, COUNT(DISTINCT rating.id) as ratingCount 
FROM business
LEFT JOIN invoice ON (invoice.bussId = business.bussId AND invoice.userId = '3000' )
LEFT JOIN rating ON (rating.bussId = business.bussId )
WHERE business.bussId = 100

这可以避免使用子查询,这取决于数据通常会执行得很糟糕。虽然在这种情况下看起来你可能只返回一行,所以这不太可能是一个问题

修改

要获得价格的总和,这会使用子查询来获取发票的数量和价格的总和,然后将其加入到业务表中: -

SELECT business.bussId, invoice_count as invoices, invoice_price, COUNT(DISTINCT rating.id) as ratingCount 
FROM business
LEFT JOIN 
(
    SELECT bussId, COUNT(id) AS invoice_count, SUM(price) AS invoice_price
    FROM invoice
    WHERE userId = '3000'
    GROUP BY bussId
) invoice_sub
ON invoice_sub.bussId = business.bussId 
LEFT JOIN rating ON (rating.bussId = business.bussId )
WHERE business.bussId = 100
GROUP BY business.bussId, invoices, invoice_price