当第三个表中可能不存在值时,从3个表中进行选择

时间:2013-10-18 20:04:33

标签: mysql sql

我有三张桌子:

APPS

|---------------------------|
| app_id  |     app_name    |
|    1    |     Some App    |   
|    2    | Some Other App  |
|    3    |   custom_image  |

USER_APPS

|----------------------------------------|
| user_app_id  |   app_id   |  user_id   |
|      1       |      1     |     1      |
|      2       |      2     |     1      |
|      3       |      3     |     1      |

CUSTOM_IMAGES

|------------------------------------------------------------------|
| custom_image_id  |   app_id   |  user_id   |       image_url     |
|        1         |      3     |     1      | /img/image_name.jpg |

这只是一个说明我问题的示例。我需要为给定用户选择所有三个表中的值,但我没有做任何我需要的东西。

我现在拥有的是:

SELECT ua.app_id, ua.app_position, aa.app_name, ci.image_url, ci.custom_image_id
FROM (app_user_apps AS ua, app_apps AS aa)
JOIN app_custom_images AS ci ON (ua.user_id = ci.user_id)
WHERE ua.user_id = :user_id
AND aa.app_id = ua.app_id       
ORDER BY ua.app_position

但是这并没有将cutom图像表中的图像URL绑定到apps表。

1 个答案:

答案 0 :(得分:0)

为了解我的问题,这是我的代码。

代码:

select app_id,app_position,app_name,image_url,custom_image_id
from app_apps aa
join user_apps ua on aa.app_id = ua.app_id
join app_custome_images ci on ua.userid = ci.user_id
where ua.user_id = ci.user_id and aa.app_id = ua.app_id
order by ua.app_position