2012-06-15 35 views
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 
+0

用戶表是否實際上有一個列ID? –

+0

是的它確實有.... – user1421214

+0

嘗試將子查詢更改爲:從公司c選擇姓名 INNER JOIN user_company uc ON c.id = uc.company_id WHERE uc.user_id = u.id –

回答

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 
+0

感謝隊友.... – user1421214

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 
+0

第一個查詢中存在拼寫錯誤 - 但都起作用 - 謝謝! – user1421214

+0

@ user1421214那麼你應該投票並接受答案。錯字固定! :) –

+0

+1我 - 但我接受德姆回答...對不起,但我真的很感謝你的回答。 :) – user1421214