选择子查询中的Mysql未知列

时间:2018-03-05 11:54:15

标签: mysql

它会在' where子句'中抛出未知列company_names。在

SELECT `user`.`id`, 
    `user`.`email`,  
    (SELECT  Group_concat(c.name)  
       FROM user_company uc  
          inner join company as c  
            on uc.company_id = c.id  
      where uc.user_id = user.id  
      GROUP BY uc.user_id) as company_names  
 FROM `user` AS `user`  
WHERE  company_names LIKE '%sa%' LIMIT 0, 20;

1 个答案:

答案 0 :(得分:0)

您无法在

的位置使用别名作为列名

但您可以在子查询上使用内部联接并在此

上进行过滤
  SELECT `user`.`id`, 
      `user`.`email`,  
      t.my_company_name

  FROM `user` AS `user`  
  INNER JOIN (
    SELECT user_id,  Group_concat(c.name)   my_company_name
    FROM user_company uc  
    inner join company as c  on uc.company_id = c.id  
         AND uc.user_id = user.id  
    GROUP BY uc.user_id
  )  t on t.user_id = user.id and t.my_company_names LIKE '%sa%' 
  LIMIT 0, 20;