I have a MySQL query that joins a 2 tables based on the relation by the table to a 3rd table, but it doesn’t always seem to working fully. The query is:
SELECT a.ID, a.ECPCodeID, a.RegDate, a.BusName, b.ID as RepCodeID, b.RepCode
FROM ECPs_Registration a, Reps_Codes b
WHERE SUBSTR(a.ZipCode,1,5)
IN (
SELECT SUBSTR(c.Zip,1,5)
FROM Reps_Zip c
WHERE c.RepCodeID = b.ID
)
ORDER BY b.RepCode,a.BusName
If I take out the Rep_Codes table from the main join and put it in the Reps_Zip select, it works, but I don’t get the fields from the Reps_Codes table that I need:
SELECT a.ID, a.ECPCodeID, a.RegDate, a.BusName
FROM ECPs_Registration a
WHERE SUBSTR(a.ZipCode,1,5)
IN (
SELECT SUBSTR(c.Zip,1,5)
FROM Reps_Zip c, Reps_Codes b
WHERE c.RepCodeID = b.ID
)
ORDER BY a.BusName
How would I change this to get the same result as the second query, but get the Reps_Codes fields in the result?
EDIT:
I get the same result as the first query if I do:
SELECT a.ID, a.ECPCodeID, a.RegDate, a.BusName, b.ID as RepCodeID, b.RepCode
FROM ECPs_Registration a, Reps_Codes b, Reps_Zip c
WHERE SUBSTR(a.ZipCode,1,5) = SUBSTR(c.Zip,1,5) AND c.RepCodeID = b.ID
ORDER BY b.RepCode,a.BusName
What I am looking for is to get all the records of ECPs_Registration table and then get some information for that record from Reps_Codes table. That Reps_Codes connects to the ECPs_Registration by a third table Reps_Zip.
There was no problem with the queries, it was an issue where the Reps_Zip had duplicate zip codes in it.