1

请看下面的查询 - 我得到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
4

2 回答 2

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
于 2012-06-15T11:06:21.280 回答
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
于 2012-06-15T10:52:23.033 回答