Skip to content
Advertisement

How can I join two tables with different number of rows in Flask SQLAlchemy?

I have two tables I want to join. They possess a one-to-many relationship. One is called FundingSource, and the other is called AllocationSummary. They have a different number of columns and a different number of rows (FundingSource has more of both).

I need to query the FundingSource table (Table 1) to get all the rows from the database, and then add the rows from AllocationSummary (Table 2) to it, joining each corresponding row together and leaving the remaining AllocationSummary (Table 2) column values null since there are less rows.

The resulting table needs to have 5 of the columns from my FundingSource table (including id), 4 of the columns from my AllocationSummary table, and however many rows my FundingSource table has.

For example, this is my FundingSource table with 5 rows:

JavaScript

This is my AllocationSummary table with 3 rows:

JavaScript

And this is the RESULT table I want AFTER joining: (format was getting ruined so I attached a picture) Resulting Table

Also note, I want the id column to come from the FundingSource table, so joining the two tables should not create a new table. It should query from the FundingSource table and just add on the state, eligible_applicant, recipient, and amount columns to it from the AllocationSummary table.

These are my two tables:

JavaScript

Here is my .py file:

JavaScript

Here is my HTML file:

JavaScript

I just can’t seem to find a way to query using attributes from 2 different tables at once to display in my table. These are some of the queries I have tried:

JavaScript

Any help would be greatly appreciated!

Advertisement

Answer

You want a left outer join between FundingSource and AllocationSummary, which you can do like this:

JavaScript

The above is a bit cumbersome, but allows the HTML template to be a simple loop. The converse – simple Python but complicated template – could be achieved by passing FundingSource.query.all() to the template and handle multiple or missing allocations there.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement