I am having a problem with MySQL joins.
Table_A:
A_id Cost1 A1_id Cost2 1 500 0 200 1 100 1 100 1 50 2 60 1 10 3 50 2 5 0 10
Table_B (Refers B_id: from Table_A A1_id):
B_id FName LName 1 X A 2 Y B 3 Z C
Table_C (Refers C_id: from Table_A A_id):
C_id Towns 1 Atlanta 2 NewYork
I need to combine all three tables, like the following output:
- I extract the
Townsthat match(Table_A.A_id=Table_C.C_id). - I extract the
Fname,Lnamethat match(table_A.A1_id=Table_b.b_id). - I need to skip the
TownsifA1_id != 0. - I need to skip the
Fname,LnameifA1_id == 0.
The remaining data may either be a value or null, which I specify as ‘#’. What would be an efficient MySQL query for the given scenario?
Output:
A_id Cost1 A1_id cost2 Fname Lname Towns 1 500 0 200 # # Atlanta 1 100 1 100 X A # 1 50 2 60 Y B # 1 10 3 50 Z C #
This looks like a UNION of two distinct queries to me. I’m going to assume that the ID columns never contain negative values.
I’m not completely confident about that formulation. There’s a chance that the conditions on B.B_id < 0 and C.C_id < 0 need to be associated with the corresponding ON clauses.
There’s also a decent chance that using two left outer joins in a single SELECT with appropriate OR’d filters would achieve the correct result.