Jnr
Jnr

Reputation: 1664

MYSQL select statement through multiple associative entities

I am trying to retrieve data through multiple associative entities, namely company_area (in pink) and jobs_employees (in blue). I want to retrieve all the jobs (in green) that employees (in grey) did from a specific company and area. How would I do this with the database structure I have?

What I've tried:

select Jobs.idJobs,jobs.Title, jobs.JobDescription, jobs.Deadline, 
jobs.JobStarted, jobs.jobEnded, jobs.Completed, jobs.Remarks, Priority

from company_area

inner join employees 
on employees.idEmployees = company_area.FK_Employee
inner join jobs_employees
on jobs_employees.FK_Employees = employees.idEmployees
inner join JobPriority 
on jobs_employees.FK_Priority = JobPriority.idJobPriority
inner join jobs
on jobs_employees.FK_Employees = jobs.idJobs 

where company_area.FK_Company = '2' and company_area.FK_Area = '1'

Notes: I know I can create an associative entity between company, area, and jobs but is it possible and efficient to do it without the extra entity?

Code to create DB >> ERD diagram

Upvotes: 1

Views: 819

Answers (1)

burnall
burnall

Reputation: 842

A few advices:

  1. There is no magic: if you access a table to obtain column value or to join other, you definitely need the table.

  2. Possible problem in your query: you can get one job several times if job is performed by a few users.

  3. Better use table prefix for all columns. Column name with prefix FK is a bit misleading - it is standard prefix for naming foreign keys.

Upvotes: 1

Related Questions