Gargo
Gargo

Reputation: 13

SQLAlchemy - list data from two tables with one query

I'm new in Flask and Sqlalchemy and I struggle to find some solution where I can get data from two tables in SQLAlchemy with one query

For example if I have two tables:

table A                               table B
-------------------------             --------------------
id   |  value | name                 id   |   pass   |   name
 1   |  10    | first_name            1   |    no    |   first_name
 2   |  20    | second_name           2   |    yes   |   second_name

Is there a query where I can filter both of the tables by name, for example "first_name" and get something like this:

<A 1>
<B 1>

I tried with .join, but I'm getting this output, if there are more records with the same name:

[<A1> <B1>]
[<A3> <B1>]
[<A1> <B3>]
[<A3> <B3>]etc...

Upvotes: 1

Views: 217

Answers (1)

David Espart
David Espart

Reputation: 11780

If you want to return all results from each table that match certain conditions, you can use UNION

SELECT 'A' as tablename, id FROM A WHERE name='first name'
UNION
SELECT 'B' as tablename, id FROM B WHERE name='first name'

Upvotes: 1

Related Questions