gpt4 book ai didi

python - Flask-SQLAlchemy 左外连接过滤查询

转载 作者:可可西里 更新时间:2023-11-01 07:30:19 29 4
gpt4 key购买 nike

最初我试图做一个“右外连接”,但一旦我发现它不受支持,我就开始着手从左连接。但是,我无法准确地弄清楚如何编写我需要的内容。基本上我有两个表,Table_1Table_2 我需要 Table_1 中的所有行,其中 column_c 等于 1。此外,我需要 Table_2 中的所有行,其中 column_b 尚未在 Table 1 中。视觉上看起来像这样:

**Table_1**
column_a ( a and b are the
column_b ( primary key.
column_c

**Table_2**
column_b

这就是我用 SQL 编写它的方式:

SELECT *
FROM (SELECT * FROM Table_1 WHERE column_a = 123) t1
RIGHT OUTER JOIN Table_2 t2 ON t1.column_b = t2.column_b
WHERE t1.column_c = 1 or t1.column_c is NULL;

SELECT *
FROM Table_2 t2
LEFT OUTER JOIN (SELECT * FROM Table_1 WHERE column_a = 123) t1
ON Table_2 t2 ON t1.column_b = t2.column_b
WHERE t1.column_c = 1 or t1.column_c is NULL;

这是我在 Flask-SQLAlchemy 中的形式,重要的是要注意这是 Table_2 的 db.Model 类中的一个方法。

def all_exclude(self, column_a):
return self.query.outerjoin(
Table_1,
Table_1.column_b==Table_2.column_b).filter(or_(
Table_1.column_c==None,
and_(Table_1.column_c==1,
Table_1.column_a==column_a))).all()

不幸的是,我在写它的时候并没有考虑它,而且它不会真的那样工作,因为我不能从类表单中调用方法。我必须在初始化仅来自单行的查询之后执行此操作,这不是我需要的。我知道我可以像这样将其作为查询运行:

Business.query.outerjoin(
Table_1,
Table_1.column_b==Table_2.column_b).filter(or_(
Table_1.column_c==None,
and_(Table_1.column_c==1,
Table_1.column_a==column_a))).all()

但出于 OOP 的目的,我试图将我的类分开,但即便如此,我认为这也行不通,因为从技术上讲,过滤器并未在连接之前完成。也许解决方案比我想象的要容易,但我不能完全理解它。提前致谢!

最佳答案

根据您的评论,这应该可以回答您的问题:

SELECT Table_1.column_a, Table_1.column_b
FROM Table_1
WHERE Table_1.column_a = 123
AND Table_1.column_c = 1
UNION
SELECT Table_2.column_a, Table_2.column_b /* I'm assuming these columns exist in Table_2. Make sure these columns are same as selected columns from Table_1 */
FROM Table_2
WHERE NOT EXISTS (SELECT 1 FROM Table_1
WHERE Table_1.column_b = Table_2.column_b
AND Table_1.column_a = 123);

这在 Python SQLAlchemy 中转换为:

from sqlalchemy import exists

query_1 = (db.session.query(Table_1)
.with_entities(Table_1.column_a, Table_1.column_b)
.filter(Table_1.column_a == 123)
.filter(Table_1.column_c == 1)

query_2 = (db.session.query(Table_2)
.with_entities(Table_2.column_a, Table_2.column_b)
.filter(
~exists().where(Table_1.column_b == Table_2.column_b)
)
)
query = query_1.union(query_2).all()

关于python - Flask-SQLAlchemy 左外连接过滤查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109734/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com