[英]Specify multiple alternate Join conditions using conditional expression with SQLalchemy
I'm joining two tables in SQLalchemy. 我正在加入SQLalchemy中的两个表。 If a certain condition is met I want to join on column 'C' in the right table otherwise I want to join on column 'D' in the right table. 如果满足某个条件,我想加入右表中的列'C',否则我想加入右表中的列'D'。
With raw SQL I would use a CASE statement. 使用原始SQL我会使用CASE语句。 I tried to implement this in SQLalchemy but got this error: 我试图在SQLalchemy中实现这个,但是遇到了这个错误:
TypeError: 'bool' object is not iterable TypeError:'bool'对象不可迭代
Here's how I would write the statement in raw SQL: 以下是我将如何在原始SQL中编写语句:
SELECT
t1.A,
t2.B
FROM t1
JOIN t2 ON CASE
WHEN t2.E = '1' THEN t2.C
ELSE t2.D
END LIKE t1.CD || %
And how I tried to write it in SQLalchemy: 我是如何尝试在SQLalchemy中编写它的:
select([t1.columns.A, t2.columns.B]).select_from(
t1.join(t2, case([t2.columns.E == '1', t2.columns.C],
else_=t2.columns.D).like(t1.columns.CD + '%')))
The syntax of my case statement was wrong. 我的case语句的语法错误。 The condition should be a tuple surrounded in brackets. 条件应该是括号括起来的元组。 Instead of: 代替:
case([t2.columns.E == '1', t2.columns.C], else_=t2.columns.D)
It should be: 它应该是:
case([(t2.columns.E == '1', t2.columns.C)], else_=t2.columns.D)
I don't think you can do a like statement as a join condition. 我不认为你可以做一个类似的声明作为连接条件。 You can do a cartesian product join and do a where statement with a like in it. 你可以做一个笛卡尔积产品加入,并在其中做一个where语句。
SELECT t1.A, t2.B
FROM t1, t2
where CASE WHEN t2.E = '1' THEN t2.C ELSE t2.D END LIKE t1.CD||'%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.