Slightly unusual requirement here, which unfortunately is down to a poor table design a long way back down the development path!
I have 3 tables, repairs, staff, technicians
The repairs table contains all the information on repair tasks booked in to my system. This contains a field “Technician” this field will contain the ID of either a staff member (from the table staff) or an ID of an outsourced (offsite) technician (from the table technicians), in this latter case the ID will have a prefix of “T”
So, due to this latter case prefix, I need to be able to grab that T and use it to determine whether my SQL query needs to JOIN table staff or table technicians
So, I have a fairly simple SQL Query:
SELECT technicians.screenName,
repairs.turnAround, repairs.technician, repairs.dateIn, repairs.Type,
invoices.status, invoices.grossTotal
FROM repairs
LEFT JOIN invoices ON repairs.invNo=invoices.id
LEFT JOIN technicians ON technicians.id = REPLACE(repairs.technician, 'T','')
WHERE repairs.id ='REQUIRED JOB ID' ORDER BY repairs.dateIn DESC
This will work fine, and overcomes the “T” prefix for all cases where I have an outsourced technician.
BUT…
The IDs will mix up if I try to JOIN the staff table.
So I need a conditional join, such as:
LEFT JOIN
WHEN instr(repairs.technican,'T') > 0 THEN
JOIN TECHNICIANS TABLE
ELSE
JOIN STAFF TABLE
END
The further issue I can see here is that the field technicans.screenName being included in the field list will not work if I am not joining the technicians table, however, as the staff table includes a field screenName which I’d need if I joined that table, if I had an ambiguous field name screenName with no table prefix it should work shouldn’t it?
EDIT: I should probably add that the conditional join example above does NOT work!
You can join both tables with including/excluding
INSTRcondition, and show not null value then: