无法在内部查询

时间:2017-03-24 05:53:44

标签: mysql

我有这个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

1 个答案:

答案 0 :(得分:1)

试试这个:

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