SELECT A.A_id, A.Name, COASLESCE(C.State, 'Default_Value')
FROM
A LEFT JOIN
(B INNER JOIN C ON C.B_id = B.B_id)
ON B.A_id = A.A_id
Some information on joins: What is the difference between "INNER JOIN" and "OUTER JOIN"?
What's happening here is that we are joining table B and C with an INNER JOIN
where the respective B_id
column is equal. The INNER
specifies that results will be returned only when records exist in both tables that match the C.B_id = B.B_id
condition.
The LEFT JOIN
will join those combined values to table A if the matching condition exists, while still returning the records from table A if no match exists. That is, if nothing exists for the condition B.A_id = A.A_id
, NULL
values are returned for the columns from the right side of the join (the B and C join). We perform the COASLESCE
, so that if the queried column returns with NULL
, it can default to some specified value.
COALESCE
has some added benefits when performing this function: http://msdn.microsoft.com/en-us/library/ms190349.aspx
One last thing, table B in your example is commonly known as a junction table (or join table, or bridge table)... http://en.wikipedia.org/wiki/Junction_table