简体   繁体   中英

SQL query gives too many results

I am trying to write a PostgreSQL query for the problem:

How many products have been bought in 2011? (Bought in 2011 means that the orderdescription is 'Completed' in 2011). 图

So far I've got this query:

    SELECT
      COUNT(product.id)
    FROM
      product
    JOIN orderitem ON 
      productid = product.id
    JOIN "order" ON 
      "order".id = orderitem.orderid AND
      EXTRACT(year FROM orderplaced) = 2011
    JOIN orderstatus ON 
      orderstatus.orderid = "order".id
    JOIN orderstatusdescription ON 
      orderstatusdescription.id = orderstatusdescriptionid AND
      orderstatusdescription.description = 'Completed';

But this results in 231410 products while the database only contains 1000. Using DISTINCT(product.id) logically results in a count of 1000.

I have no idea what I am doing wrong.

Slightly modified query from Andres Olarte:

SELECT
  COUNT(orderitem.productid)
FROM
  orderitem
JOIN "order" ON 
  "order".id = orderitem.orderid
JOIN orderstatus ON 
  orderstatus.orderid = "order".id
JOIN orderstatusdescription ON 
  orderstatusdescription.id = orderstatusdescriptionid 
WHERE 
  EXTRACT(year FROM orderplaced) = 2011
AND  orderstatusdescription.description = 'Completed';

Try something like this:

SELECT
  COUNT(product.id)
FROM
  product
JOIN orderitem ON 
  productid = product.id
JOIN "order" ON 
  "order".id = orderitem.orderid
JOIN orderstatus ON 
  orderstatus.orderid = "order".id
JOIN orderstatusdescription ON 
  orderstatusdescription.id = orderstatusdescriptionid 
WHERE 
  EXTRACT(year FROM orderplaced) = 2011
AND  orderstatusdescription.description = 'Completed';

You're getting a larger number because you have multiple records being match by one or more of your join conditions.

For example, when you join the product table to orderitem you probably have more than one orderitem record that gets matched. So you get that product.id in your result set more than once.

Try COUNT(distinct product.id) -- that should give you the count of distinct products that were purchased.

This will tell you which products were bought in 2011 (untested -- not at computer with PG):

     select distinct OI.productid, P.description
     from orderitem OI inner join products P on OI.productid=P.id
     inner join
     (   
     select order.id as orderid from order
     inner join orderstatusdescription OSD
     on order.orderstatusdescriptionid = OSD.id and OSD.description = 'COMPLETED'
     where extract(year from order.orderplaced)=2011  
     ) as Orders2011
     on Orders2011.orderid = OI.orderid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM