开发者

How to left join another table based on a value in the first table?

I tried where I would create a temporary column using case as开发者_如何学JAVA join_id but when I tried to left join on it it says the column doesn't exist

SELECT * , se_users.user_username,
CASE se_album_keys.key_owner_id
WHEN 28 THEN se_album_keys.key_user_id
ELSE se_album_keys.key_owner_id
END  AS key_join_id
FROM se_album_keys
LEFT JOIN se_users ON se_users.user_id=se_album_keys.key_join_id
LIMIT 10;

error:

ERROR 1054 (42S22): Unknown column 'se_album_keys.key_join_id' in 'on clause'

UPDATE: It's hard to pick an answer, using IF() as TehShrike suggested indexes can't be used, but after he suggested this solution for joining table by condition in the chatroom. I realized I was over-analyzing the whole situation and came up with this:

  SELECT se_album_keys.* FROM  se_album_keys 
  LEFT JOIN se_users AS users_see_mine ON se_album_keys.key_owner_id = 28 AND users_see_mine.user_id = se_album_keys.key_user_id 
LEFT JOIN se_users AS users_i_see ON se_album_keys.key_owner_id != 28 AND users_i_see.user_id = se_album_keys.key_owner_id
WHERE se_album_keys.key_user_id=28 OR se_album_keys.key_owner_id=28;

so I'll leave this question open for a while to see if the experts have something to say. I had already finished coding this and am only interested in learning more about high performance mysql!


You could use an IF() in your join:

LEFT JOIN users ON users.user_id = IF(album_keys.key_owner_id = 1337, 
  album_keys.key_user_id, album_keys.key_owner_id) 

But be aware that no indexes on the album_keys table will be used!

Edit: if you JOIN the other table on twice, you can use functions like COALESCE() to show you the relevant one:

LEFT JOIN users AS users_see_mine ON album_keys.key_owner_id = 1337 
  AND users_see_mine.user_id = album_keys.key_user_id 
LEFT JOIN users AS users_i_see ON album_keys.key_owner_id != 1337 
  AND users_i_see.user_id = album_keys.key_owner_id


Use UNION or UNION ALL.

SELECT  *,
        se_users.user_username
  FROM  se_album_keys
        LEFT JOIN 
        se_users 
        ON se_users.user_id = se_album_keys.key_user_id
 WHERE  se_album_keys.key_owner_id = 28

UNION ALL

SELECT  *,
        se_users.user_username
  FROM  se_album_keys
        LEFT JOIN 
        se_users 
        ON se_users.user_id = se_album_keys.key_owner_id
  WHERE se_album_keys.key_owner_id <> 28
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜