I have three MySQL tables that I’m trying to query into a single result. As close as I’ve gotten this, I think it’s possible, but I’ve hit a wall in getting the last part working.
Basically I have two tables (table_one and table_two) which I’m trying to UNION DISTINCT, which works perfectly. It’s when I try to bring in the third table that it all blows up and decides to return nothing. I’m sure it’s user error 🙂
This code may not have everything in the right place for how I’m trying to do it, so maybe I just need a little nudge in the right direction.
SELECT
part_code,
name
FROM
table_three
WHERE
table_three.part_code = (
SELECT
part_code
FROM
table_one
UNION DISTINCT
SELECT
part_code
FROM
table_two
)
ORDER BY
name ASC
I appreciate any direction someone can offer.
Edit
Here are some alternatives that satisfies: Gief all rows in Table 3 such that the part code exists in either Table 1 or Table 2.
Derived table with union
Inner join with union
Bonus. I have no idea why I did this.
Let me know how they work out.
Edit 2.
Ok, try the following. It should produce the union of tables T1 and T2. Then for each row, it will pick the name from T3 if such a part code can be found.
If part_code is a key in all tables, you can do a
UNION ALLinstead.