子选择查询中的表名别名范围

时间:2012-06-15 10:38:36

标签: php mysql sql phpmyadmin

请查看下面的查询 - 我收到了Unknown column 'u.id' in 'on clause'

SELECT id, username, 

coalesce(
 (SELECT name from company c 
    INNER JOIN user_company uc 
    ON uc.user_id = u.id 
    AND c.id = uc.company_id), 'NOT-AVAILABLE' 
) companyname

FROM `user` u

2 个答案:

答案 0 :(得分:1)

解决问题的一种方法:

SELECT u.id,
       u.username,
       COALESCE(aux.name, 'NOT-AVAILABLE') as 'companyname'
FROM `user` u
LEFT JOIN
 (SELECT user_id, name from company c 
    INNER JOIN user_company uc
    ON c.id = uc.company_id) aux ON aux.user_id = u.id

另一种解决方法:

SELECT u.id,
       u.username,
       COALESCE(c.name, 'NOT-AVAILABLE') AS 'companyname'
FROM `user` u
LEFT JOIN user_company uc ON uc.user_id = u.id 
LEFT JOIN company c ON c.id = uc.company_id

答案 1 :(得分:1)

根据您的评论,相关性不能放在相关子查询的JOIN内。

但是,它可以放在相关子查询的WHERE子句中。

SELECT
  id,
  username,
  coalesce(
    (SELECT name
       FROM company      c
 INNER JOIN user_company uc
         ON c.id = uc.company_id
      WHERE uc.user_id = u.id
    ),
    'NOT-AVAILABLE'
  ) companyname
FROM
  `user` u 

这回答了你的明确问题;为什么你的查询语法失败。


但是,我会用简单的LEFT JOIN替换整个相关性。

SELECT
  u.id,
  u.username,
  COALESCE(c.name, 'NOT-AVAILABLE') companyname
FROM
  `user` u 
LEFT JOIN
  `user_company` uc
      ON uc.user_id = u.id
LEFT JOIN
  `company` c
    ON c.id = uc.company_id