这是数据库架构:
[编辑]
我将描述我对下面的查询所做的事情:
最内层查询:选择所有saleId
满足WHERE
条件的s
中间查询:选择所有productId
属于saleId
最外层查询:SUM
并products.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;
对优化有什么帮助吗?