snippetsqlMinor
How can I write a proper query to JOIN all of these tables without duplicates?
Viewed 0 times
canthesetableswithoutallquerywritejoinhowproper
Problem
Let's say I have four tables:
Let's say Michael Vick has an id of 100. I want to get his full name and all of his stats for each year (passing, rushing, and receiving).
I don't want any duplicates, meaning that rushing stats for 2011 should appear in the same row as passing stats for 2011.
What is the most elegant way to write this query? Thanks.
TABLE: players
COLUMNS: id, first_name, last_name
TABLE: passing_stats
COLUMNS: id, year, passing_yards (several other passing columns)
TABLE: rushing_stats
COLUMNS: id, year, rushing_yards (several other rushing columns)
TABLE: receiving_stats
COLUMNS: id, year, receiving_yards (several other receiving columns)Let's say Michael Vick has an id of 100. I want to get his full name and all of his stats for each year (passing, rushing, and receiving).
I don't want any duplicates, meaning that rushing stats for 2011 should appear in the same row as passing stats for 2011.
What is the most elegant way to write this query? Thanks.
Solution
The following will work in Postgres. Test here: SQL-Fiddle, postgres-test. SQL-Server does not have
NATURAL JOIN and MySQL has NATURAL but doesn't have FULL joins:SELECT
id,
first_name,
last_name,
year,
passing_yards,
rushing_yards,
receiving_yards
FROM
players p
NATURAL LEFT JOIN
( passing_stats pas
NATURAL FULL JOIN
rushing_stats rus
NATURAL FULL JOIN
receiving_stats rec
)Code Snippets
SELECT
id,
first_name,
last_name,
year,
passing_yards,
rushing_yards,
receiving_yards
FROM
players p
NATURAL LEFT JOIN
( passing_stats pas
NATURAL FULL JOIN
rushing_stats rus
NATURAL FULL JOIN
receiving_stats rec
)Context
StackExchange Database Administrators Q#16383, answer score: 6
Revisions (0)
No revisions yet.