简体   繁体   English

MySQL查询 - 连接表以显示一个表中的所有值,并仅匹配其他列中的结果

[英]MySQL Query - join tables to show all values from one table and only matching results in other column

Apologies for the poor question title. 为可怜的问题标题道歉。

I have two tables, jobs and Persons-Jobs. 我有两张桌子,工作和人员 - 工作。

Jobs Table 工作表

1    Painting

2    Plumbing

3    Executive

4    CraneOperator

Persons-Jobs Table 人员 - 工作表

JohnSmit   Painting

JohnSmit   CraneOperator

TomJones   Executive

BradPit    Plumbing

Question

I want to run a query that returns two columns. 我想运行一个返回两列的查询。 The first column must show ALL the records from the jobs table. 第一列必须显示jobs表中的所有记录。 the second column must show the name of the person that does the job. 第二列必须显示执行该作业的人员的姓名。 I want a where clause that returns only results for one user, in this example JohnSmit. 我想要一个where子句,只返回一个用户的结果,在本例中为JohnSmit。 as an example the query should output: 作为示例,查询应输出:

    Painting   JohnSmit

    Plumbing   *NULL*

    Executive  *NULL*

CraneOperator  JohnSmit

I have tried the outer join but it fails where there are multiple persons in the Persons-Jobs table. 我已经尝试过外连接,但是在Persons-Jobs表中有多个人的地方失败了。

select j.job,p.person 
from jobs j 
LEFT OUTER JOIN `Persons-Jobs` p on j.job = p.job
where p.person='JohnSmit' 
or p.person is NULL

any help,as always would be appreciated. 任何帮助,一如既往地表示赞赏。

Thanks and regards, Smudger 谢谢和问候,Smudger

You can put the restriction on the person in the join clause. 您可以在join子句中对person进行限制。 That way, the other people will get filtered out before the join happens. 这样,在加入发生之前,其他人将被过滤掉。

select j.job,p.person 
from   jobs j 
LEFT 
JOIN   `Persons-Jobs` p 
on     j.job = p.job 
and    p.person='JohnSmit'

暂无
暂无

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

相关问题 MySQL \\联接2个表并在一列中显示2行的结果 - MySQL \ join 2 tables and show results from 2 rows in one column MYSQL从一个表查询SELECT并将结果与​​另一表联接 - MYSQL query SELECT from one table and join results with other table 显示一个表中的所有内容,仅显示另一个表中的内容 - Show all content from one table and only matching from the other mysql join 2 个表 - 显示一个表中的所有行 - mysql join 2 tables - show all rows from one table MYSQL QUERY LEFT JOIN显示一个表中的所有数据 - MYSQL QUERY LEFT JOIN SHOW ALL DATA FROM ONE TABLE mysql join查询从两个表中选择行,一个表有多个与第一个表匹配的行 - mysql join query for select rows from two tables that one table is having multiple rows matching to the first table MySQL内部连接两个表,并在匹配的行字段中将一个表的行插入另一个表 - MySQL Inner Join two tables and insert row from one table to other on matching row field MySQL将其他2个匹配ID的表的结果合并到表中 - MySQL merge results into table from count of 2 other tables, matching ids 加入MySQL表:在左表的一行中显示右表的所有结果 - Join MySQL Tables: Display All Results From Right Table In One Row Of Left Table PHP Codeigniter MySQL 查询 - 将 4 个表连接在一起,其中 3 个表使用每个表中的一列分组 - PHP Codeigniter MySQL query - join 4 tables together, with 3 tables using group by one column from each table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM