mysql - 以一对多关系显示不需要的重复结果

时间:2013-07-23 13:39:57

标签: mysql foreign-keys one-to-many relationship

我有3张桌子。

首先是公司表:Company_ID, Company_name

第二个是职位表:JOB_ID, Job_Name, Job_description

3rd是Comp_Jobs表:Comp_Job_ID, Company_ID, Job_ID

我正在尝试运行查询以创建与这些表的连接,以便它显示与公司相关的所有作业。例如,我希望显示的公司1有2个工作。但是当我运行这个查询时:

Select Company.Company_name, Jobs.Job_ID, Company.CAddress, 
Jobs.Job_Name, Jobs.Job_Description from Company, jobs
join company_job where Company.Company_ID = Company_Job.Company_ID
order by Company_job.Job_ID;

它将重复结果,因为在公司1中将显示作业1和2两次。

任何tekkers?

2 个答案:

答案 0 :(得分:1)

Select Company.Company_name, Jobs.Job_ID, Company.CAddress, 
Jobs.Job_Name, Jobs.Job_Description
from Company
join company_job on Company.Company_ID = Company_Job.Company_ID
join jobs on jobs.Job_ID =  Company_Job.job_id
order by Company_job.Job_ID;

试试这个。不确定这是不是你要的
与公司和工作没有适当的连接条件

答案 1 :(得分:1)

您应该使用INNER JOIN仅显示所需的行:

SELECT Company.Company_name, Jobs.Job_ID, 
       Company.CAddress, Jobs.Job_Name, Jobs.Job_Description
FROM Comp_Jobs
INNER JOIN Jobs ON Jobs.Job_ID = Comp_Jobs.Job_ID
INNER JOIN Company ON Company.Company_ID = Comp_Jobs.Company_ID    
ORDER BY Company_job.Job_ID;