I have a problems with a CTE query using multiple consecutive joins (A -> B -> C -> D). A and B have both relation to other table so they are joined by that other_id value. C has FK to B and C-D are One to One (id=id).
The query looks like so:
latest_message = (session.query(
models.Main.id.label('main_id'),
message_models.Third.id,
message_models.Third.type,
message_models.Fourth.status,
).select_from(
models.Main, models.Second, message_models.Third, message_models.Fourth,
).join(
models.Second, models.Main.other_id == models.Second.other_id,
).join(
message_models.Third, message_models.Third.second_id ==
models.Second.id,
).join(
message_models.Fourth,
message_models.Fourth.id ==
message_models.Third.id,
).filter(
models.Main.some_feld == 'abcd',
).distinct(
models.Main.id,
).order_by(
message_models.Third.created_at.desc(),
).cte('latest_message'))
Which results in an error:
Can't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Please use the .select_from() method to establish an explicit left side, as well as providing an explicit ON clause if not present already to help resolve the ambiguity.
If I omit explicit join rules it manages to generate an SQL but it's not valid:
(psycopg2.errors.DuplicateAlias) table name "third_table" specified more than once
And looking at it it does generate weird joins.
Written by hand in SQL it works as needed - something like this:
Anyone know how to fix the SQLAlchemy query version?