SQL LEFT JOIN 子查询别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16776176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:26:06  来源:igfitidea点击:

SQL LEFT JOIN Subquery Alias

sqlsubqueryleft-join

提问by CharleyXIV

I'm running this SQL query:

我正在运行这个 SQL 查询:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198

And I get this error:

我得到这个错误:

#1054 - Unknown column 'a.post_id' in 'on clause'.

#1054 -“on 子句”中的未知列“a.post_id”。

I think my code is pretty simple, but I can't make it right. What am I doing wrong?

我认为我的代码很简单,但我做对了。我究竟做错了什么?

回答by Mahmoud Gamal

You didn't select post_idin the subquery. You have to select it in the subquery like this:

您没有post_id在子查询中选择。您必须像这样在子查询中选择它:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

回答by EJay

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

我认识到答案有效并已被接受,但有一种更简洁的方式来编写该查询。在 mysql 和 postgres 上测试。

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198