0

我正在尝试返回在指定日期范围内销售的商品类型的降序列表。

我了解如何获取项目类型的数量并对其进行计数,但我对如何链接到其他表感到困惑。我将把我的工作代码和我认为需要如何完成的伪代码放在一起,非常感谢任何帮助。

SELECT Item_Type, COUNT(*) as theAmount
FROM  myDB.Item

//LINK order_ID to item 
//WHERE order_ID includes Item_Type

//Link to session
//Find Ses_Date that order was made

GROUP BY Item_Type
ORDER BY theAmount desc
LIMIT 10

我需要从中提取数据的三个表,显示了所需的字段:

Item
PK: Item_ID
Row: Item_Type
FK: Order_ID

Order
PK: Order_ID
FK: Session_ID    

Session
PK: Ses_ID
Row: Ses_date 
4

3 回答 3

1
SELECT   i.Item_Type, COUNT(i.Item_Type) as theAmount
FROM     Item AS i
JOIN     Order AS o ON o.order_ID = i.Order_ID 
JOIN     Session AS s ON s.Ses_ID = o.Session_ID 
WHERE    s.Ses_date between @date1 AND @date2 
GROUP BY i.Item_Type
ORDER BY theAmount DESC
LIMIT    10 
于 2012-11-10T15:37:35.930 回答
1
SELECT Item_Type, COUNT(*) as theAmount, Session_date
FROM  Item
left outer join Order 
    on Item.Order_id = Order.Order_id
left outer join Session 
    on Order.Session_id = Session.Session_id
GROUP BY Item_Type
ORDER BY theAmount desc
LIMIT 10

上面的查询会给你结果。

于 2012-11-10T15:38:13.567 回答
0

您需要LEFT JOIN在这种情况下使用,因此如果您在另一个表上没有匹配的记录,则 for 的值Item_Type将为零。

SELECT  a.Item_Type, COUNT(c.Ses_ID) theAmount
FROM    Item a
        LEFT JOIN   `Order` b
            ON  a.Order_ID = b.Order_ID
        LEFT JOIN   `Session` c
            ON b.Session_ID = c.Ses_ID
GROUP BY a.Item_Type
-- ORDER BY theAmount DESC
-- LIMIT 10
于 2012-11-10T15:34:28.577 回答