source

sqlalchemy ORM 쿼리에서 NOT IN 절을 사용하는 방법

goodcode 2022. 9. 5. 22:59
반응형

sqlalchemy ORM 쿼리에서 NOT IN 절을 사용하는 방법

다음 mysql 쿼리를 sqlalchemy로 변환하려면 어떻게 해야 합니까?

SELECT * FROM `table_a` ta, `table_b` tb where 1
AND ta.id = tb.id
AND ta.id not in (select id from `table_c`)

지금까지 sqalchemy에 대해 알고 있습니다.

query = session.query(table_a, table_b)
query = query.filter(table_a.id == table_b.id)

ORM 내부에서는 오퍼레이터를 설명합니다(이전에는notin_()다음과 같이 말할 수 있습니다.

query = query.filter(table_a.id.not_in(subquery))
#                               ^^^^^^

문서에서:

ColumnOperators 메서드에서 상속됨

NOT IN 연산자를 구현합니다.

이것은, ColumnOperators.in_()에 부정(~x.in_(y)을 사용하는 것과 같습니다.

버전 1.4의 스테이트는 다음과 같습니다.

not_in()연산자 이름이 에서 변경됨notin_()를 참조해 주세요.이전 버전과의 호환성을 위해 이전 이름을 사용할 수 있습니다.

찾을 수 있습니다.notin_()경우에 따라서는.

이것을 시험해 보세요.

subquery = session.query(table_c.id)
query = query.filter(~table_a.id.in_(subquery))

주의:table_a,table_b그리고.table_c매핑된 클래스여야 합니다.Table인스턴스.

다음은 전체 코드입니다.

#join table_a and table_b
query = session.query(table_a, table_b)
query = query.filter(table_a.id == table_b.id)

# create subquery
subquery = session.query(table_c.id)
# select all from table_a not in subquery
query = query.filter(~table_a.id.in_(subquery))

언급URL : https://stackoverflow.com/questions/26182027/how-to-use-not-in-clause-in-sqlalchemy-orm-query

반응형