一尘不染

相关子查询的MySQL范围界定问题

mysql

我有这个Mysql查询,它的工作原理:

SELECT 
    nom
    ,prenom
    ,(SELECT GROUP_CONCAT(category_en) FROM
            (SELECT DISTINCT category_en FROM categories c WHERE id IN
                (SELECT DISTINCT category_id FROM m3allems_to_categories m2c WHERE m3allem_id = 37)
            ) cS
      ) categories
    ,(SELECT GROUP_CONCAT(area_en) FROM 
            (SELECT DISTINCT  area_en FROM areas c WHERE id IN 
                (SELECT DISTINCT area_id FROM m3allems_to_areas m2a WHERE m3allem_id = 37)
            ) aSq
     ) areas
FROM m3allems m
WHERE m.id = 37

结果是:

nom             prenom      categories              areas
Man             Multi       Carpentry,Paint,Walls   Beirut,Baalbak,Saida

它可以正确执行,但仅当我将所需的ID硬编码到查询中时(37)。我希望它适用于m3allem表中的所有条目,因此我尝试这样做:

SELECT 
    nom
    ,prenom
    ,(SELECT GROUP_CONCAT(category_en) FROM
            (SELECT DISTINCT category_en FROM categories c WHERE id IN
                (SELECT DISTINCT category_id FROM m3allems_to_categories m2c WHERE m3allem_id = m.id)
            ) cS
      ) categories
    ,(SELECT GROUP_CONCAT(area_en) FROM 
            (SELECT DISTINCT  area_en FROM areas c WHERE id IN 
                (SELECT DISTINCT area_id FROM m3allems_to_areas m2a WHERE m3allem_id = m.id)
            ) aSq
     ) areas
FROM m3allems m

我得到一个错误:

“ where子句”中的未知列“ m.id”

为什么?从MySql手册中:

13.2.8.7. Correlated Subqueries 
[...] 
Scoping rule: MySQL evaluates from inside to outside.

所以…当子查询在SELECT部分​​中时,这不起作用吗?我什么都没读。

有人知道吗?我该怎么办?我花了很长时间来构建此查询…我知道这是一个庞然大物查询,但它在单个查询中就可以满足我的要求,而且我已经接近使它起作用!

有人可以帮忙吗?


阅读 335

收藏
2020-05-17

共1个答案

一尘不染

您只能关联一个级别的深度。

采用:

   SELECT m.nom,
          m.prenom,
          x.categories,
          y.areas
     FROM m3allens m
LEFT JOIN (SELECT m2c.m3allem_id,
                  GROUP_CONCAT(DISTINCT c.category_en) AS categories
             FROM CATEGORIES c
             JOIN m3allems_to_categories m2c ON m2c.category_id = c.id
         GROUP BY m2c.m3allem_id) x ON x.m3allem_id = m.id
LEFT JOIN (SELECT m2a.m3allem_id,
                  GROUP_CONCAT(DISTINCT a.area_en) AS areas
             FROM AREAS a
             JOIN m3allems_to_areas m2a ON m2a.area_id = a.id
         GROUP BY m2a.m3allem_id) y ON y.m3allem_id = m.id
    WHERE m.id = ?
2020-05-17