左连接因on子句中的Unknown列而失败

时间:2013-02-24 02:10:54

标签: left-join

我有两个针对同一个表运行的查询,除了第二个查询因添加左连接而失败。

成功运行

 SELECT *
 FROM paypal_ipn_orders 
 LEFT join itemkey on paypal_ipn_orders.item_number = itemkey.item_id 
 WHERE packing_slip_printed = 0
 AND LOWER(payment_status) = 'completed'
 AND address_name <> ''
 order by itemkey.sort_id;

然而,第二个查询失败,“on clause”中的“未知列'paypal_ipn_orders.item_number'”,但它在左连接中运行正常。 Paypal_ipn_orders表确实包含item_number字段。

SELECT *
FROM paypal_ipn_orders as table1,
(SELECT payer_email, COUNT(*) as count FROM paypal_ipn_orders GROUP BY payer_email ORDER BY count DESC) as table2
LEFT join itemkey on table1.item_number = itemkey.item_id 
WHERE table1.payer_email = table2.payer_email 
and packing_slip_printed = 0
AND LOWER(payment_status) = 'completed'
AND address_name <> ''
ORDER BY count DESC, auction_multi_item, item_number;

table1之后的逗号是必需的(SELECT ...是FROM子句的一部分。

一个有趣的说明。我将From子句的顺序更改为:

SELECT *
FROM (SELECT payer_email, COUNT(*) as count FROM paypal_ipn_orders GROUP BY payer_email ORDER BY count DESC) as table1,
paypal_ipn_orders as table12
LEFT join itemkey on table2.item_number = itemkey.item_id 
WHERE table2.payer_email = table1.payer_email 
and packing_slip_printed = 0
AND LOWER(payment_status) = 'completed'
AND address_name <> ''
ORDER BY count DESC, auction_multi_item, item_number;

现在错误信息是:'where子句'中的未知列'table2.payer_email'。但这不会与左连接一起运行。在where子句消息中给出相同的Unknown列。

仅供参考 - 这有效:

 SELECT payer_email, COUNT(*) as count 
 FROM paypal_ipn_orders 
 WHERE packing_slip_printed = 0
 AND LOWER(payment_status) = 'completed'
 AND address_name <> ''
 GROUP BY payer_email 
 ORDER BY count DESC;

2 个答案:

答案 0 :(得分:0)

FROM paypal_ipn_orders table1,

你的意思是...... FROM paypal_ipn_orders AS table1 (...

另请注意table1,末尾的逗号。我不确定这是不是有意?

答案 1 :(得分:0)

这最终有效:

SELECT *
        FROM (SELECT payer_email, COUNT(*) as count 
           FROM paypal_ipn_orders 
           Where packing_slip_printed = 0
           AND LOWER(payment_status) = 'completed'
           AND address_name <> '' 
           GROUP BY payer_email 
           ORDER BY count DESC) as table1,
        paypal_ipn_orders as table2
        LEFT join itemkey on table2.item_number = itemkey.item_id 
        WHERE table1.payer_email = table2.payer_email 
        and packing_slip_printed = 0
        AND LOWER(payment_status) = 'completed'
        AND address_name <> ''
        ORDER BY count DESC, auction_multi_item, sort_id