I have three tables as shown in below image.
Note: Lead column of projectheader table stores an employee id.
What I want to have is be able to retrieve something like the one in table my goal(Lead, displays the lead name of that employee)
I was able to do that using the query below.
SELECT DISTINCT
projectdetails.ProjectDetailsID,
projectheader.ProjectID,
projectheader.ProjectName,
projectheader.Lead,
projectheader.StartDate,
projectheader.EndDate,
projectheader.Status,
projectheader.Remarks,
projectdetails.EmployeeID,
employee.Firstname,
employee.Lastname,
Lead.Leadname
FROM
projectheader,
projectdetails,
employee,
( SELECT
projectheader.ProjectID AS projid,
CONCAT(employee.Firstname,' ',employee.Lastname) AS Leadname
FROM employee, projectheader, projectdetails
WHERE projectheader.ProjectID = projectdetails.ProjectID
AND projectheader.Lead = employee.EmployeeID
) AS Lead
WHERE projectheader.ProjectID = projectdetails.ProjectID
AND projectdetails.EmployeeID = employee.EmployeeID
AND projectheader.ProjectID = Lead.projid
AND projectdetails.ProjectID = Lead.projid
And got this result:
The query that I used is quite long and perhaps not well written, I want to know a different way on how I could achieve the same result using a better sql query either by using join or a subquery. (I added a DISTINCT on the beginning of the projectdetails.ProjectDetailsID because without it some rows are duplicated). I'm in search for a better query than the one I'm currently using.
It is possible, and indeed common, to join more than just two tables together. This is done by adding additional JOIN clauses to your SELECT statement.
Subqueries can be used as an alternative to joins. A subquery is typically nested inside the WHERE clause. Subqueries must always be enclosed within parentheses. The table that's specified in the subquery is typically different than the one in the outer query, but it can be the same.
A subquery cannot contain an ORDER BY clause. A subquery in an UPDATE statement cannot retrieve data from the same table in which data is to be updated. A subquery in a DELETE statement cannot retrieve data from the same table in which data is to be deleted.
Try something like this (haven't tested it, you can give it a try):
SELECT
projectdetails.ProjectDetailsID,
projectheader.ProjectID,
projectheader.ProjectName,
projectheader.Lead,
projectheader.StartDate,
projectheader.EndDate,
projectheader.Status,
projectheader.Remarks,
projectdetails.EmployeeID,
employee.Firstname,
employee.Lastname,
CONCAT(Lead.Firstname,' ',Lead.Lastname) AS Leadname
FROM
projectheader,
projectdetails,
employee,
employee as Lead
WHERE projectheader.ProjectID = projectdetails.ProjectID
AND projectdetails.EmployeeID = employee.EmployeeID
AND projectheader.Lead = Lead.EmployeeID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With