I have two tables and one of the table has two columns and a row will only contain data in one of the columns:
Table 2:
| column1 | column2 | ------------------------- | something | Null | ------------------------- | Null | something | -------------------------
I am trying to do something like:
q = session.query(Table1.column1, (Table2.column1, Table2.column2).label('content')) \
.outerjoin(Table2) \
.all()
for v in q:
x = v.column1
content = v.content
print(x, content)
How can it be done?
Sql coalesce should help. It will return the first non-null value among the list of values.
from sqlalchemy import func
q = session.query(Table1.column1, func.coalesce(Table2.column1, Table2.column2).label('content')) \
.outerjoin(Table2) \
.all()
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.