使用多列子查询优化查询

时间:2015-07-02 16:07:41

标签: mysql sql database subquery mysql-workbench

SELECT 

   daf.id as affiliate_id,

   daf.name as affiliate_name,

   dal.name as allocation_name,

   dal.id as allocation_id,

   dal.allocation,dal.price,

   (select lead_price from paul.affiliates_price where affiliate_id = daf.id and allocation_id = dal.id) as lead_price,

   (select live from paul.affiliates_price where affiliate_id = daf.id and allocation_id = dal.id) as live,

   (select allocation from paul.affiliates_price where affiliate_id = daf.id and allocation_id = dal.id) as allocation

FROM 

     degreeamerica.affiliates daf, degreeamerica.allocations dal;

ORDER BY daf.id;

任何人都可以帮助使用多列子查询优化此查询吗?请帮忙!!!

我已经尝试过这个:

 SELECT 

   daf.id as affiliate_id,

   daf.name as affiliate_name,

   dal.name as allocation_name,

   dal.id as allocation_id,

   dal.allocation,dal.price

FROM 

     degreeamerica.affiliates daf, degreeamerica.allocations dal 

JOIN 

     (select pap.lead_price,pap.live, pap.allocation_id,pap.affiliate_id from paul.affiliates_price pap) pafp  

ON (dal.id=pafp.allocation_id and daf.id=pafp.affiliate_id) 

ORDER BY daf.id;

导致错误。未知的daf.id 我正在使用具有多列子查询的笛卡尔积。 我已经花了8到9个小时。请帮忙。 在我的查询中告诉我第二个错误或为我优化第一个错误。 请帮忙。

2 个答案:

答案 0 :(得分:1)

我认为这会给你你想要的东西

-E

答案 1 :(得分:0)

你可以试试这个。不确定它是否真的优化了任何东西。

SELECT 
   daf.id as affiliate_id,
   daf.name as affiliate_name,
   dal.name as allocation_name,
   dal.id as allocation_id,
   dal.allocation,
   dal.price,
   p.lead_price,
   p.live,
   p.allocation
FROM 
     degreeamerica.affiliates daf, degreeamerica.allocations dal, paul.affiliates_price p
WHERE 
    p.affiliate_id = daf.id and p.allocation_id = dal.id
ORDER BY 
    daf.id

您还可以CROSS JOIN affiliatesallocations然后LEFT JOIN affiliates_price

SELECT 
    daf.id as affiliate_id,
    daf.name as affiliate_name,
    dal.name as allocation_name,
    dal.id as allocation_id,
    dal.allocation,
    dal.price,
    p.lead_price,
    p.live,
    p.allocation
FROM 
    degreeamerica.affiliates daf
    CROSS JOIN degreeamerica.allocations dal 
    LEFT JOIN paul.affiliates_price p ON p.affiliate_id = daf.id and p.allocation_id = dal.id
ORDER BY 
    daf.id