左连接查询

时间:2016-01-13 09:12:57

标签: mysql mysqli

我一直在使用此查询收到语法错误。我正在尝试计算行数:

1)栏目收益_campaign_free_id = 43

2)栏目收益_campaign_paid_id = 43

所以有两个输出:paid_views,free_views

SELECT 

cp.campaign_paid AS paid_views
cf.campaign_free AS free_views

FROM

(
    SELECT COUNT(earning_paid_campaign_id) AS campaign_paid
    FROM earnings
    WHERE earning_paid_campaign_id = 43
) cp

LEFT JOIN

(
    SELECT COUNT(earning_free_campaign_id) AS campaign_free
    FROM earnings
    WHERE earning_free_campaign_id = 43
) cf

ON cf.earning_campaign_free_id = cp.earning_paid_campaign_id

这是错误:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法

     在'cf.campaign_free AS free_views

附近      

     

(       SELECT COUNT(第4行的earning_paid_campaign_i'

如何解决此错误?

1 个答案:

答案 0 :(得分:2)

试试这个。

SELECT 

cp.campaign_paid AS paid_views,
cf.campaign_free AS free_views

FROM

(
    SELECT earning_paid_campaign_id,COUNT(earning_paid_campaign_id) AS campaign_paid
    FROM earnings
    WHERE earning_paid_campaign_id = 43
) cp

LEFT JOIN

(
    SELECT earning_campaign_free_id,COUNT(earning_free_campaign_id) AS campaign_free
    FROM earnings
    WHERE earning_free_campaign_id = 43
) cf

ON cf.earning_campaign_free_id = cp.earning_paid_campaign_id

您正尝试加入ON cf.earning_campaign_free_id = cp.earning_paid_campaign_id的基础,但是当您编写sub query然后mysql创建temporary表时,您不会选择该ID。所以发生错误