Mysql 当第三个表中可能不存在值时,从三个表中选择
我有三张桌子: 应用程序 用户应用程序Mysql 当第三个表中可能不存在值时,从三个表中选择,mysql,sql,Mysql,Sql,我有三张桌子: 应用程序 用户应用程序 |----------------------------------------| | user_app_id | app_id | user_id | | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 3 | 1 | 自定义图像 |-------
|----------------------------------------|
| user_app_id | app_id | user_id |
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
自定义图像
|------------------------------------------------------------------|
| 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 images表中的图像URL绑定到apps表。为了理解您的问题,这是我编写的代码 代码:
你需要使用“左连接”而不是“连接”,默认为“内部连接”,其中是
ua。app\u position
declare?@TJ-,也可以写下来作为答案。你不仅需要按照@TJ-使用左连接,还需要摆脱隐式连接(这->来自(app\u user\u apps as ua,app\u apps as aa)
以及aa.app\u id=ua.app\u id
并使用join…ON…
TJ将其作为一个显式连接,你是正确的。我将投票作为答案。Max app\u位置在user\u apps表中。AgRizzo,我尝试了一个连接,但它不起作用,这篇文章解释了原因,
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
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