SQL SELECT 从三个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6032691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL SELECT from three tables
提问by Kosso
I have three tables:
我有三个表:
Map_table
- id
- content_id
- from_user_id
- to_user_id
- timestamp
User_table
- id
- name
Content_table
- id
- title
eg: I want to select rows from the Map_table where Map_table.to_user_id = 1
例如:我想从 Map_table 中选择行,其中 Map_table.to_user_id = 1
and also provide the User_table.name where Map_table.from_user_id = User_table.id
并提供 User_table.name 其中 Map_table.from_user_id = User_table.id
and also provide the Content_table.title where Map_table.content_id = Content_table.id
并提供 Content_table.title 其中 Map_table.content_id = Content_table.id
Map_table.content_id might be null and therefore not map to the Content_table
Map_table.content_id 可能为空,因此不会映射到 Content_table
If been through a load of answers here and still tearing my hair out to get the results I need. Can any SQL gurus out there see a simple solution. The potential JOINs required are frying my brain.
如果在这里经历了大量的答案并且仍然撕毁我的头发以获得我需要的结果。任何 SQL 专家都可以看到一个简单的解决方案。所需的潜在 JOIN 正在煎炸我的大脑。
Any help would be much appreciated. For the sake of my scalp, among other things ;)
任何帮助将非常感激。为了我的头皮,除其他外;)
回答by CristiC
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
回答by Justin Wignall
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
回答by maple_shaft
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
You need to join against user_table twice to do this.
您需要两次加入 user_table 才能执行此操作。