gpt4 book ai didi

SQLAlchemy 带括号的连词

转载 作者:行者123 更新时间:2023-12-02 03:26:42 26 4
gpt4 key购买 nike

我正在尝试在 sqlalchemy 核心中生成以下 sql。我无法让连词 AND OR 中的括号出现。

select from member t1 
inner join member t2
on (
(
t1.first_name = t2.last_name and
t1.last_name = t2.first_name and
t1.dob = t2.dob
)
or (
t1.last_name = t2.last_name and
t1.first_name = t2.first_name and
t1.dob = t2.dob
)
)
group by t2.id

我使用的sqlalchemy核心语句是:

selStmt = select([t1]).select_from(
t1.join(
t2, or_(
and_(
t1.c.first_name == t2.c.last_name,
t1.c.last_name == t2.c.first_name,
t1.c.dob == t2.c.dob
),
and_(
t1.c.last_name == t2.c.last_name,
t1.c.first_name == t2.c.first_name,
t1.c.dob == t2.c.dob
)
)
)
).group_by(t2.c.id)

生成的sql代码为:

SELECT t1
FROM t1
JOIN t2 ON
t1.first_name = t2.last_name AND
t1.last_name = t2.first_name AND
t1.dob = t2.dob OR
t1.last_name = t2.last_name AND
t1.first_name = t2.first_name AND
t1.dob = t2.dob
GROUP BY t2.id

由于不包括括号,因此逻辑不正确。如何在连词中使用括号?

最佳答案

显然 AND 运算的优先级高于 OR。因此在我的例子中不需要括号。

关于SQLAlchemy 带括号的连词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29933991/

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