This question has been a little difficult for me to formulate but I think I have come up with an example that will get the idea across.
I have three tables bird_brd, state_stt, and bird_in_state_bis
The first two tables are just lists and the third table is a way to join the other two togther and has a count field for the number of times a bird has been seen in a state.
I don’t think the structure of the tables matters too much but here are the basics
bird_brd
=====================
| id_brd | name_brd |
=====================
| 1 | Blue Jay |
| 2 | Robbin |
=====================
state_stt
=====================
| id_stt | name_stt |
=====================
| 1 | Utah |
| 2 | Arizona |
| 3 | Wyoming |
=====================
bird_in_state_bis
=======================================
| stt_id_bis | brd_id_bis | count_bis |
=======================================
| 1 | 1 | 5 |
| 2 | 2 | 3 |
=======================================
What I want to be able to do is combine these tables so that if there is an entry in the bird_in_state table for a state it will show the count for all birds whether they are in the bird_in_state table or not.
so when I run the query I would expect results like the following
==================================
| State Name | Bird Name | Count |
==================================
| Utah | Blue Jay | 5 |
| Utah | Robbin | 0 |
| Arizona | Blue Jay | 0 |
| Arizona | Robbin | 3 |
==================================
Note that this is something I’m trying to do for work and the above tables are not the actual tables I’m working with but they are a good example of the structure I have to work with.
I have tried to use some sort of left or right join but I don’t get what I’m looking for.
Thanks in advance for any help.
I think this is what you’re looking for.
It first does the Cartesian Join across all used States and all available birds to get all possible combinations. Then it joins back to the original three tables to get the names of the birds, states, and counts. In such a join, the count would be null if it weren’t available, so we use the
IFNULLfunction to convert all nulls to 0’s.Where I’m using these tables: