简体   繁体   中英

Left outer join to a generated table?

Am I on completely the wrong tack ? I want to do a left outer join to a query generated from 2 tables , but i keep getting errors. Do I need a different approach?

t1:

ID, Surname,Firstname

t2:

ID,JobNo,Confirmed

I have the following query:

SELECT JobNo AS N, StaffID AS P, Confirmed as C, 
       FirstName AS F,Surname AS S 
FROM gigs_players, Players 
WHERE t1.StaffID=t2.StaffID AND JobNo="2" 
      AND (`Confirmed` IS NULL OR Confirmed ='Y' ) 
ORDER BY Instrument,Surname

I want to add:

LEFT OUTER JOIN contacted (ON t1.StaffID=contact.ID AND t2.JobNo=contact.JobNo)"

Can I do a left outer join to a query generated from 2 tables ?

In order to use the t1 and t2 in the left outer join that you want to add you need to join them with the first tables, you can't reference them directly in the left outer join you, Something like the following:

SELECT JobNo AS N, StaffID AS P, Confirmed as C, 
   FirstName AS F,Surname AS S 
FROM gigs_players, Players
Inner join t1 on ...
Inner join t2 on ...
LEFT OUTER JOIN contacted c 
     on t1.StaffID=c.ID AND t2.JobNo = c.JobNo
WHERE t1.StaffID=t2.StaffID AND JobNo="2" 
    AND (`Confirmed` IS NULL OR Confirmed ='Y' ) 
ORDER BY Instrument,Surname

So, based in your tables' structure, define the conditions of the two joins with t1 and t2 with other tables.

Here is the an example of a left join to a sub query. This might be what you are looking for.

select 
parts.id, 
min(inv2.id) as nextFIFOitemid 
from test.parts 
left join 
( select 
  inventory.id, 
  coalesce(parts.id, 1) as partid 
  from test.inventory 
  left join test.parts 
  on (parts.id = inventory.partid) 
) inv2 
on (parts.id = inv2.partid) 
group by parts.id;

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