JOIN和COUNT错误的结果

时间:2014-04-08 09:36:52

标签: mysql sql join count

我有两个表,产品和基准 基准仅与一种产品相关联。每种产品每年只能有一个基准。

我想检索每个产品的名称一段时间,并计算每种产品的基准数。

SELECT p.name,
       p.id,
       COUNT(p.id) AS nb_benchmark
FROM product p
INNER JOIN benchmark b0 ON b0.product_id = p.id
INNER JOIN benchmark b1 ON b1.product_id = p.id
WHERE p.owner = "MyCompany"
  AND b0.year = 2011
  AND b1.year = 2012
GROUP BY p.id
ORDER BY nb_trials DESC

但是计数是错误的,它是通向高的,甚至比数据库中的实际结果更多。我想这是因为JOIN,但我不知道如何构建查询。

4 个答案:

答案 0 :(得分:1)

benchmark的联接可能会为product引入重复的行。 使用COUNT(DISTINCT xx)计算不同的值,即

SELECT p.name, 
       p.id, 
       COUNT(DISTINCT p.id) AS nb_benchmark
FROM ...

另外,请记住GROUP BY p.idp.name

的正确性

答案 1 :(得分:1)

试试这个:

SELECT p.name,
       p.id,
       COUNT(b0.id) AS nb_benchmark
FROM product p
INNER JOIN benchmark b0 ON b0.product_id = p.id
WHERE p.owner = "MyCompany"
  AND b0.year IN (2011, 2012)
GROUP BY p.name, p.id
ORDER BY nb_trials DESC

答案 2 :(得分:1)

我找到了实现我想要的方法

      SELECT p.name, p.id,  COUNT(DISTINCT(b0.id)) + COUNT(DISTINCT(b1.id))  as     nb_benchmark
      FROM product p
      INNER JOIN benchamrk b0 ON b0.product_id = p.id AND b0.year = 2011 
      INNER JOIN benchamrk b1 ON b1.product_id = p.id AND b1.year = 2012 
      WHERE
      p.owner = "myCompany" 
      GROUP BY p.id
      ORDER BY nb_benchmark DESC

答案 3 :(得分:0)

试试这个。

SELECT p.id, p.name, b.nb_benchmark
FROM product p
JOIN (
    /* number of benchpark per product for years 2011 and 2012 */
    SELECT product_id, COUNT(*) AS nb_benchmark
    FROM benchmark
    WHERE year = 2011 OR year = 2012
    GROUP BY product_id
) b ON p.id = b.product_id
WHERE p.owner = "MyCompany"
ORDER BY nb_benchmark DESC