繁体   English   中英

不能在内部查询中使用外部查询的列

[英]Can't use outer query's column inside inner query

我有这个 mysql 查询,如果我在 where 子句中放置一个固定数字,它似乎可以工作,但是当我尝试用外部查询中的列替换该数字时,我收到以下错误:

错误代码:1054。“where 子句”中的“a.latest_version_id”列未知。

我尝试了各种方法来执行此查询并重新执行了 3 次。 请查看下面我的查询,看看其他人是否可以看到我做错了什么。 我使用##### 做笔记。

基本上,我想使用a.latest_version_idb.version_id (它们都是相同的值)来过滤我的子查询中的结果。 我去掉了 where 子句,但这只是给我没有结果。

SELECT 
    DISTINCT 
    b.version_id,
    b.title, 
    b.email, 
    b.contact_first_name, 
    b.contact_last_name,
    b.physical_address_1, 
    b.physical_address_2, 
    b.physical_suburb, 
    b.phone_number, 
    b.phone_code, 
    a.latest_version_id,
    c.name,
    f.categories 
FROM 
    products a
LEFT JOIN 
    product_versions b ON a.latest_version_id = b.version_id 
LEFT JOIN 
    product_version_city c ON b.version_id = c.version_id 
    ##### this is the block of code I am struggling with
LEFT JOIN  
    (SELECT 
         e.version_id, 
         GROUP_CONCAT(d.name SEPARATOR ', ') as categories           
     FROM 
         category_product_version e
     INNER JOIN 
         (SELECT 
              id, name 
          FROM 
              categories) AS d ON d.id = e.category_id 
     WHERE 
         e.version_id = a.latest_version_id ##### the issue is on this line.
        ##### It works if I put '1' there instead of a.latest_version_id
     ) as f ON f.version_id = a.latest_version_id
WHERE 
    b.version_id IS NOT NULL 
    AND b.title IS NOT NULL

尝试这个:

SELECT  
    a.version_id,
    a.title, 
    a.email, 
    a.contact_first_name, 
    a.contact_last_name,
    a.physical_address_1, 
    a.physical_address_2, 
    a.physical_suburb, 
    a.phone_number, 
    a.phone_code, 
    a.latest_version_id,
    a.name,
    f.categories 
FROM

(SELECT 
    DISTINCT 
    b.version_id,
    b.title, 
    b.email, 
    b.contact_first_name, 
    b.contact_last_name,
    b.physical_address_1, 
    b.physical_address_2, 
    b.physical_suburb, 
    b.phone_number, 
    b.phone_code, 
    a.latest_version_id,
    c.name

FROM products a
    LEFT JOIN product_versions b ON a.latest_version_id = b.version_id 
    LEFT JOIN product_version_city c ON b.version_id = c.version_id) as a


    LEFT JOIN  
    (
       SELECT 
         e.version_id, 
         GROUP_CONCAT(d.name SEPARATOR ', ') as categories           
       FROM category_product_version e
        INNER JOIN (
            SELECT id, name FROM categories  
        ) AS d ON d.id = e.category_id 

     ) as f ON f.version_id = a.latest_version_id

 WHERE  f.version_id = a.latest_version_id and a.version_id IS NOT NULL AND a.title IS NOT NULL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM