I'm joining two tables in 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.
With raw SQL I would use a CASE statement. I tried to implement this in SQLalchemy but got this error:
TypeError: 'bool' object is not iterable
Here's how I would write the statement in raw 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:
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. 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.
SELECT t1.A, t2.B
FROM t1, t2
where CASE WHEN t2.E = '1' THEN t2.C ELSE t2.D END LIKE t1.CD||'%'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.