三个表中的SQL SELECT

Kos*_*sso 5 sql select join

我有三张桌子:

Map_table
- id
- content_id
- from_user_id
- to_user_id
- timestamp

User_table
- id
- name

Content_table
- id
- title
Run Code Online (Sandbox Code Playgroud)

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

并提供User_table.name,其中Map_table.from_user_id = User_table.id

并提供Content_table.title,其中Map_table.content_id = Content_table.id

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

如果在这里经过了大量的答案,仍然撕裂我的头发,以获得我需要的结果.任何SQL专家都可以看到一个简单的解决方案.潜在的JOIN需要煎炸我的大脑.

任何帮助将非常感激.为了我的头皮,除其他外;)

Cri*_*tiC 12

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
Run Code Online (Sandbox Code Playgroud)