Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do join on multiple criteria, returning all combinations of both criteria

I am willing to bet that this is a really simple answer as I am a noob to SQL.

table 1 has column 1 (criteria 1) column 2 (criteria 2) column 3 (metric 1)

table 2 has column 1 (criteria 1) column 2 (criteria 2) column 3 (metric 2 specific to table2.criteria2)

There can be anywhere from 1 - 5 values of criteria 2 for each criteria 1 on the table.

when I use the join statement here (assuming I identify table 1 as One prior to this):

Select WeddingTable, TableSeat, TableSeatID, Name, Two.Meal FROM table1 as One inner join table2 as Two on One.WeddingTable = Two.WeddingTable and One.TableSeat = Two.TableSeat 

I only get one of the criteria 1/criteria 2 combinations even when I know for a fact that there are 3 or 4. How do I get all combinations?

Take the situation where there is a wedding where table 1 is basically a seating chart, and table 2 is the meal option that each table/seat has chosen. Table 1 has the convenient TableSeatID, but Table 2 does not have a comparable ID.

Sample Data:

enter image description here

The results needs to show all 4 lines, being all 3 seats at WeddingTable 001 and the one seat at WeddingTable 002.

Desired Results:

enter image description here

like image 485
tarheel Avatar asked Oct 30 '12 00:10

tarheel


People also ask

Which join type returns all possible combination of records?

CROSS JOIN Note, that this join does not need any condition to join two tables. In fact, CROSS JOIN joins every row from the first table with every row from the second table and its result comprises all combinations of records in two tables.

What join type will return all the rows for both tables?

FULL JOIN. A FULL JOIN or FULL OUTER JOIN is essentially a combination of LEFT JOIN and RIGHT JOIN . This type of join contains all of the rows from both of the tables.

How do I combine two conditions in SQL?

Syntax. SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]... AND [conditionN]; You can combine N number of conditions using the AND operator.


1 Answers

select one.*, two.meal from table1 as one left join table2 as two on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat) 
like image 140
Anom Avatar answered Oct 17 '22 12:10

Anom