Reputation: 532
not sure if my title is exactly waht I want to accomplish but it was a guess. I'm trying to see if something like the following is possible in PGSQL.
Basically, I have a set of data that I want to pull no matter what. But, if certain columns of data arent null, then I want it to join another table and pull data referencing that data. So, for example, let's say I have data like:
User_Accounts:
userid | companyname | first name |
---|---|---|
25df | Test Company 1 | Bob |
921f | Test Company 1 | Lawrence |
882s | Company test 2 | NULL |
8234 | Test Company 1 | Cleo |
8244s | Company test 2 | Paul |
825q | Test Company 1 | Bruce |
5552 | B Alpha Company | Lenny |
Baseball_Rosters:
userid | baseball_team | company | position |
---|---|---|---|
25df | Atlanta Aliens | Test Company 1 | P |
882s | Boston Bruisers | Company test 2 | DH |
8234 | California Craisins | Test Company 1 | 1B |
8244s | Tampa Titans | Company test 2 | P |
null | Tampa Titans | Test Company 1 | P |
5552 | Tampa Titans | B Alpha Company | 2B |
5552 | Tampa Titans | B Alpha Company | SS |
921f | California Craisins | Test Company 1 | P |
825q | Boston Bruisers | Test Company 1 | P |
How would I perform a query to get a result like:
userid | baseball_team | company | first name | position |
---|---|---|---|---|
null | Tampa Titans | Test Company 1 | null | P |
25df | Atlanta Aliens | Test Company 1 | Bob | P |
825q | Boston Bruisers | Test Company 1 | Bruce | P |
921f | California Craisins | Test Company 1 | Lawrence | P |
So essentially, inserting the firstname & lastname field if and only if userid is not null? And then to order by userid null first and then in order? Thanks for the help.
Upvotes: 0
Views: 109
Reputation: 78
This looks like a LEFT OUTER JOIN
.
Like this:
SELECT baseball_rosters.user_id, baseball_team, comapny, first_name, position
FROM baseball_rosters
LEFT OUTER JOIN user_accounts ON user_accounts.user_id = baseball_rosters.user_id;
Upvotes: 1