三个表格的 SQL SELECT

8

我有三个表:

Map_table
- id
- content_id
- from_user_id
- to_user_id
- timestamp

User_table
- id
- name

Content_table
- id
- title

例如:我想从Map_table中选择行,其中Map_table.to_user_id = 1

并提供Map_table.from_user_id = User_table.id时的User_table.name

并提供Map_table.content_id = Content_table.id时的Content_table.title

Map_table.content_id可能为空,因此不会映射到Content_table

如果您已经查看了许多答案,仍然无法获得所需的结果。有没有SQL大师能够看到简单的解决方案。所需的潜在JOIN正在烧毁我的大脑。

任何帮助将不胜感激。为了我的头皮和其他事情的缘故;)


1
从描述来看,你走在了正确的道路上。你尝试过什么? - manji
很奇怪,我从来没有收到回复的通知,只是回到这里看看……与此同时,我终于设法让它运行起来,使用了Parkyprg在下面的相同答案;)我会尝试Justin的方式,看看哪个更快。谢谢你的回复!我的头皮还是完好无损的。 - Kosso
3个回答

14
SELECT mt.*, ut.name, ct.title
FROM
     Map_table mt
INNER JOIN
     User_table ut on mt.from_user_id = ut.id
LEFT JOIN 
     Content_table ct on mt.content_id = ct.id
WHERE 
     mt.to_user_id = 1

1
在程序中添加以下内容:WHERE m.to_user_id = 1 :) - Manoj
这就是我最终得到的结果。谢谢!;) - Kosso

4
SELECT m.id,m.content_id,m.from_user_id,m.to_user_id,m.timestamp,u.name,c.title
FROM Map_table m
INNER JOIN User_table u ON u.id = m.from_user_id
LEFT OUTER JOIN Content_table c ON c.id = m.content_id
WHERE m.to_user_id = 1

他想要筛选出 to_user_id = 1 的内容。 - maple_shaft

0
SELECT mt.*, ut1.name
FROM map_table mt inner join user_table ut1 on mt.from_user_id = ut1.id
inner join user_table ut2 on mt.to_user_id = ut2.id
where mt.to_user_id = 1

你需要两次与用户表(user_table)进行连接(join)来完成这个任务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接