0

这是数据库架构:

[编辑]

我将描述我对下面的查询所做的事情:

最内层查询:选择所有saleId满足WHERE条件的s

中间查询:选择所有productId属于saleId

最外层查询SUMproducts.cost选择vendors.name

这是我想出的 SQL 查询:

SELECT vendors.name AS Company
, SUM(products.cost) AS Revenue
FROM
    products
    INNER JOIN sold_products
        ON (products.productId = sold_products.productId)
    INNER JOIN vendors
    ON (products.vendorId = vendors.vendorId)
            WHERE sold_products.productId IN (
                    SELECT sold_products.productId
                    FROM
                        sold_products
                    WHERE sold_products.saleId IN (
                            SELECT sales.saleId     
                            FROM
                                markets
                                INNER JOIN vendors
                                ON (markets.vendorId = vendors.vendorId)
                                INNER JOIN sales_campaign
                                ON (sales_campaign.marketId = markets.marketId)
                                INNER JOIN packet_headers
                                ON (sales_campaign.packetHeaderId = packet_headers.packetHeaderId)
                                INNER JOIN packet_details
                                ON (packet_details.packetHeaderId = packet_headers.packetHeaderId)
                                INNER JOIN sales
                                ON (sales.packetDetailsId = packet_details.packetDetailsId)
                            WHERE vendors.customerId=60
                            )
                    )
GROUP BY Company
ORDER BY Revenue DESC;

对优化有什么帮助吗?

4

1 回答 1

1

由于您只是使用内部连接,因此您通常将查询简化为如下所示:

SELECT  ve.name     AS Company
,       SUM(pr.cost) AS Revenue
FROM    products        pr
,       sold_products   sp
,       vendors         ve
,       markets         ma
,       sales_campaign  sc
,       packet_headers  ph
,       packet_details  pd
,       sales           sa
Where pr.productId = sp.productId
And   pr.vendorId  = ve.vendorId
And   ve.vendorId  = ma.vendorId
And   sc.marketId = ma.marketId
And   sc.packetHeaderId = ph.packetHeaderId
And   pd.packetHeaderId = ph.packetHeaderId)
And   sa.packetDetailsId = pd.packetDetailsId
And   ve.customerId = 60
GROUP BY ve.Company
ORDER BY pr.Revenue DESC;

请尝试这是否有效,如果它更快,请告诉我。

于 2012-11-11T13:16:04.940 回答