Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join different tables depending on row information

Tags:

sql

join

select

Suppose I have table A with a field that can be either 1 or 2...

How do I select such that for each row in table A, if the field is 1, join the select with table B and if the field is 2, join the select with table C?

like image 632
xster Avatar asked Mar 13 '10 23:03

xster


People also ask

How do you join two tables based on conditions?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.

How do I do a conditional join in SQL?

A conditional column join is a fancy way to let us join to a single column and to two (or more) columns in a single query. We can accomplish this by using a case statement in the on clause of our join. A case statement allows us to test multiple conditions (like an if/else if/else) to produce a single value.

How do I join different tables in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

Which join will combine rows from different tables?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them.


1 Answers

(
SELECT MyField1, MyField2 FROM A
INNER JOIN B ON A.Id = B.Id
AND A.MyField = 1
)
UNION
(
SELECT MyField1, MyField2 FROM A
INNER JOIN C ON A.Id = C.Id
AND A.MyField = 2
)
like image 169
newdayrising Avatar answered Nov 03 '22 11:11

newdayrising