简体   繁体   中英

MySQL Query missing some results with 3rd JOIN

I have a core query with a simple join that works great:

SELECT 
     TableA.JobType, 
     TableA.AssignedTech, 
     TableB.EmpNumber, 
     TableB.EmpFirstName, 
FROM 
     TableA, TableB
WHERE 
     TableA.AssignedTech=TableB.EmpNumber

I need to JOIN a third table to get access to a field in a third table.

SELECT 
     TableA.JobType, 
     TableA.AssignedTech, 
     TableB.EmpNumber, 
     TableB.EmpFirstName, 
     images.image 
FROM 
     TableA, TableB, images 
WHERE 
     TableA.AssignedTech=TableB.EmpNumber
AND 
     TableA.AssignedTech=images.empno

This is fine UNLESS there is no relationship for: "TableA.AssignedTech=images.empno" at which point the record is not returned.

I need to display ALL records from my core query and append the images.empno if it is available.

You need to use left join like the following. For now I have joined both the tables with left join but if TableA and TableB always have matching data between them then you can have inner join between TableA and TableB. But in any case from your requirement it looks like you will always need to use left join for table images

SELECT 
     TableA.JobType, 
     TableA.AssignedTech, 
     TableB.EmpNumber, 
     TableB.EmpFirstName, 
     images.image 
FROM 
     TableA
Left join TableB
  On TableA.AssignedTech=TableB.EmpNumber
Left join images 
  On 
     TableA.AssignedTech=images.empno

You should use explicit join and so first join is a INNER JOIN for the 3th table you need a left join

SELECT 
     TableA.JobType, 
     TableA.AssignedTech, 
     TableB.EmpNumber, 
     TableB.EmpFirstName, 
     images.image 
FROM TableA
INNER JOIN TableB ON 
LEFT JOINN  images ON TableA.AssignedTech=images.empno

What are you after is a left join. From the documentation :

If there is no matching row for the right table in the ON or USING part in a LEFT JOIN, a row with all columns set to NULL is used for the right table.

Your query would then be:

SELECT 
    TableA.JobType, 
    TableA.AssignedTech, 
    TableB.EmpNumber, 
    TableB.EmpFirstName, 
    images.image 
FROM 
    TableA
    JOIN TableB ON TableA.AssignedTech=TableB.EmpNumber
    LEFT JOIN  images ON TableA.AssignedTech=images.empno

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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