У меня есть следующие модели SQLAlchemy.
Код: Выделить всё
class BaseModel( DeclarativeBase ):
pass
class ABC( BaseModel ):
__tablename__ = "ABC"
__table_args__ = (
Index( "index1", "account_id" ),
ForeignKeyConstraint( [ "account_id" ], [ "A.id" ], onupdate = "CASCADE", ondelete = "CASCADE" ),
)
id: Mapped[ int ] = mapped_column( primary_key = True, autoincrement = True )
account_id: Mapped[ int ]
account_idx: Mapped[ int ]
class A( BaseModel ):
__tablename__ = "A"
__table_args__ = (
Index( "index1", "downloaded", "idx" ),
)
id: Mapped[ int ] = mapped_column( primary_key = True, autoincrement = True )
downloaded: Mapped[ date ]
account_id: Mapped[ str ] = mapped_column( String( 255 ) )
display_name: Mapped[ str ] = mapped_column( String( 255 ) )
idx: Mapped[ int ]
type: Mapped[ str ] = mapped_column( String( 255 ) )
Код: Выделить всё
select
a.account_id,
(
select
group_concat( a2.account_id )
from
ABC abc
left join A a2 on a2.downloaded = a.downloaded and a2.idx = abc.account_idx
where
abc.account_id = a.id
) as 'brokerage_client_accounts'
from
A a
where
a.downloaded = "2024-11-12" and
a.type != 'SYSTEM'
order by
a.account_id
;
Код: Выделить всё
A2 = aliased( A )
brokerage_client_accounts_subq = select(
func.aggregate_strings( A2.account_id, "," ).label( "accounts" ),
).select_from(
A
).outerjoin(
A2,
and_( A2.downloaded == A.downloaded, A2.idx == ABC.account_idx )
).where(
ABC.account_id == A.id
)
stmt = select(
Account.account_id,
brokerage_client_accounts_subq.c.accounts,
).where(
and_(
A.downloaded == date( 2024, 11, 12 ),
A.type != "SYSTEM"
)
).order_by(
Account.account_id
)
Код: Выделить всё
SAWarning: SELECT statement has a cartesian product between FROM element(s) "anon_1" and FROM element "A". Apply join condition(s) between each element to resolve.
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'ABC.account_idx' in 'on clause'
Он создает SQL. .. (переформатировал для удобства чтения)
Код: Выделить всё
SELECT
`A`.account_id,
anon_1.accounts
FROM
`A`,
(
SELECT
group_concat( `A_1`.account_id SEPARATOR %(aggregate_strings_1)s) AS accounts
FROM
`A` LEFT OUTER JOIN `A` AS `A_1` ON `A_1`.downloaded = `A`.downloaded AND `A_1`.idx = `ABC`.account_idx, `ABC`
WHERE
`ABC`.account_id = `A`.id
) AS anon_1
WHERE
`A`.downloaded = %(downloaded_1)s AND `A`.type != %(type_1)s
ORDER BY
`A`.account_id
Params:
{ 'aggregate_strings_1': ',', 'downloaded_1': datetime.date(2024, 11, 12), 'type_1': 'SYSTEM' }
Кто-нибудь может помочь, пожалуйста.
Подробнее здесь: https://stackoverflow.com/questions/791 ... rent-query
Мобильная версия