MySql结合多个表来获得一个结果?

时间:2014-07-13 00:17:11

标签: mysql sql

很抱歉这么模糊,但我真的可以用这个帮助让我直截了当。我似乎无法弄清楚这背后的思考过程,任何帮助或指导将不胜感激! 我有一个数据库,其架构如下:

Customers(custID, name, firstOrderDate, city)
Items(itemID, description, size, color)
Orders(orderID, orderDate, custID)
ItemsOrdered(itemID, orderID, qty)

这是我需要做的: - 检索以相同顺序同时购买牛津鞋和T恤的客户的ID和名称。

我需要在Items中找到所有tshirt和oxford itemID。转到itemordered并找到以相同顺序购买它们的人的orderID。然后去订单找到customerID,这样我就可以回到客户那里找到那些人的名字。我希望这是有道理的!

如果有人能够朝着正确的方向推动我,我真的需要它!我完全不知道如何在这一个上前进!

2 个答案:

答案 0 :(得分:2)

基本上,您希望选择包含这两种类型项目的所有订单,并将其与客户联系起来。

我为此假设Description表示它是什么类型的项目 - 这应该指向正确的方向:

Select  Distinct C.CustId, C.Name
From    Orders          O
Join    Customers       C   On C.CustId = O.CustId
Where Exists
(
    Select  1
    From    ItemsOrdered IO
    Where   IO.OrderId = O.OrderId
    And     ItemId In
    (
        Select  ItemId
        From    Items
        Where   Description = 'TShirt'
    )
) 
And Exists
(
    Select  1
    From    ItemsOrdered IO2
    Where   IO2.OrderId = O.OrderId
    And     ItemId In
    (
        Select  ItemId
        From    Items
        Where   Description = 'Oxford'
    )
)

答案 1 :(得分:1)

SELECT 
    c.custID, c.name 
FROM 
    Customers AS c 
    INNER JOIN orders AS o 
    ON c.custID = o.custID
    INNER JOIN ItemsOrdered AS ioTshirts
    ON ioTshirts.orderID = o.orderID
    INNER JOIN ItemsOrdered as ioOxfords
    ON ioOxfords.orderID = o.orderID
    INNER JOIN Items tshirts
    ON ioTshirts.itemID = tshirts.itemID
    INNER JOIN Items oxfords
    ON ioOxfords.itemID = oxfords.itemID
WHERE
    tshirts.description like '%tshirt%' AND
    oxfords.description like '%oxford%'
GROUP BY
    c.custID