从内部查询加入

时间:2017-07-19 18:07:53

标签: mysql

我的查询很糟糕,它给了我一个错误

  

每个派生表都必须有自己的别名

select payout+earning balance,ps.auto_rebuy
 from (
   select IFNULL((SELECT sum(pe.amount)  from package_earning pe WHERE pe.type in(0,1,3) and pe.create_date='1500332400' and pe.payment_to=1 GROUP BY pe.payment_to),0) as earning,
   IFNULL((SELECT p.app_id  from package_earning p WHERE p.type in(0,1,3) and p.create_date='1500332400' and p.payment_to=1 GROUP BY p.payment_to),0) as my_app_id,
   IFNULL((SELECT sum(pp.amount*(pd.payout/100))  from package_payout pp join package_payout_dates pd on pd.create_date between pp.start_date and pp.end_date WHERE pd.create_date = '1500332400' and app_id=1 GROUP BY app_id),0) as payout   
 ) 
left join package_setting ps on ps.app_id=my_app_id

2 个答案:

答案 0 :(得分:0)

格式化后,有4个潜在的关注领域

SELECT payout+earning balance
     , ps.auto_rebuy
FROM (SELECT IFNULL((SELECT sum(pe.amount)  
                     FROM package_earning pe 
                     WHERE pe.type in(0,1,3) 
                       and pe.create_date='1500332400' 
                       and pe.payment_to=1 
                     GROUP BY pe.payment_to) Z ,0) as earning          --I added the Z
           , IFNULL((SELECT p.app_id  
                     FROM package_earning p 
                     WHERE p.type in(0,1,3) 
                       and p.create_date='1500332400' 
                       and p.payment_to=1 
                     GROUP BY p.payment_to)Y ,0) as my_app_id         -- I added the Y
           , IFNULL((SELECT sum(pp.amount*(pd.payout/100))  
                     FROM package_payout pp 
                     INNER JOIN package_payout_dates pd 
                        on pd.create_date between pp.start_date and pp.end_date 
                     WHERE pd.create_date = '1500332400' 
                       and app_id=1 GROUP BY app_id) X,0) as payout    --I added the X
     )  A                                                              --I added the A
LEFT JOIN package_setting ps 
  on ps.app_id=A.my_app_id

但我认真考虑重构此查询

答案 1 :(得分:0)

我相信您需要为“FROM”添加别名,如此

select payout+earning balance,ps.auto_rebuy
 from (
   select IFNULL((SELECT sum(pe.amount)  from package_earning pe WHERE pe.type in(0,1,3) and pe.create_date='1500332400' and pe.payment_to=1 GROUP BY pe.payment_to),0) as earning,
   IFNULL((SELECT p.app_id  from package_earning p WHERE p.type in(0,1,3) and p.create_date='1500332400' and p.payment_to=1 GROUP BY p.payment_to),0) as my_app_id,
   IFNULL((SELECT sum(pp.amount*(pd.payout/100))  from package_payout pp join package_payout_dates pd on pd.create_date between pp.start_date and pp.end_date WHERE pd.create_date = '1500332400' and app_id=1 GROUP BY app_id),0) as payout   
 ) a
left join package_setting ps on ps.app_id=my_app_id

然后在您的加入条件中包含该别名

left join package_setting ps on ps.app_id=a.my_app_id