简体   繁体   English

如何联接或左联接三个表以从其中一个表中获取数据?

[英]How to join or left join three tables to get a piece of data from one of the tables?

I have a users table, a jobs table, and a files table; 我有一个用户表,一个作业表和一个文件表; the exact table names are user_table , jobs , and files . 确切的表名是user_tablejobsfiles

The files table and jobs table have a common field, and the jobs table and users table have a common field, but all 3 do not have a common field. 文件表和作业表具有一个公共字段,而作业表和用户表具有一个公共字段,但是所有3个都没有一个公共字段。 So files table has jobid which equals id from jobs table, and jobs table has userid which equals userid from users table. 因此,文件表的jobid等于jobid表的id ,而jobs表的userid等于users表的userid

Example records 记录示例

files table

id    name        path                jobid
-------------------------------------------
7     test.gif    uploads/test.gif    130

jobs table

id     userid    ponumber    date
------------------------------------------------
130    1013      2322        10/14/2013 2:55:1pm

user_table table

userid    username    email              fname    sname
-------------------------------------------------------
1013      username    email@email.com    first    last

File 7 belongs to job 130, and job 130 belongs to user 1013. So when displaying files on a page, I want to also display the owner of the file, but that's two tables away. 文件7属于作业130,而作业130属于用户1013。因此,在页面上显示文件时,我还想显示文件的所有者,但是那是两张桌子。

How can I do this? 我怎样才能做到这一点? I haven't tried anything because I am new to MySQL programming. 我没有尝试任何东西,因为我是MySQL编程的新手。 If I were to try and guess something, it might go something like this: 如果要尝试猜测,可能会发生以下情况:

SELECT *
FROM user_table u
INNER JOIN jobs j USING (userid)
LEFT JOIN files f ON j.id = f.jobid

which probably is such a wild guess, it's not even worth mentioning. 这可能是一个疯狂的猜测,甚至不值得一提。

Well, if all users have jobs and all jobs have files OR you want to only show users with jobs that have files then 好吧,如果所有用户都有工作并且所有工作都有文件,或者您只想显示具有文件工作的用户,则

SELECT *
FROM user_table u
INNER JOIN jobs j ON j.id=u.userID
INNER JOIN files f ON j.id = f.jobid

will do that. 会做到的。

If all users DON'T have jobs and all jobs DON'T have files OR you want to show all users regardless if they have a job with files or not then 如果所有用户都没有工作,所有作业没有文件或要显示所有用户,无论他们是否有文件或不是一份工作,然后

SELECT *
FROM user_table AS u
LEFT JOIN jobs AS j ON j.id=u.userID
LEFT JOIN files AS f ON j.id = f.jobid

will do that. 会做到的。

HERE goes a description of joins that might help you understand joins a bit better. 这里介绍了连接,可能有助于您更好地了解连接。

SELECT user_table.username, files.*
FROM files 
INNER JOIN jobs ON files.jobid = jobs.id
INNER JOIN user_table ON jobs.userid = user_table.userid
SELECT files.id, files.name, jobs.id, user_table.username
FROM files LEFT JOIN jobs
ON files.id = jobs.id LEFT JOIN user_table
ON jobs.userid = user_table.userid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM