简体   繁体   English

SQLAlchemy - 一次查询列出两个表中的数据

[英]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我是 Flask 和 Sqlalchemy 的新手,我很难找到一些解决方案,我可以通过一个查询从 SQLAlchemy 的两个表中获取数据

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:是否有一个查询,我可以在其中按名称过滤两个表,例如“first_name”并得到如下内容:

<A 1>
<B 1>

I tried with.join, but I'm getting this output, if there are more records with the same name:我尝试了 with.join,但如果有更多同名记录,我会得到这个 output:

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

If you want to return all results from each table that match certain conditions, you can use UNION如果要返回每个表中符合特定条件的所有结果,可以使用UNION

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM