1 回答

TA貢獻1815條經驗 獲得超10個贊
問題是您期望返回多少個值。PostgreSQL 對生成的數據不是很好,就像這個解決方案使用的那樣,所以如果它太慢,只獲取所有組合的列表并使用 Python 查找不存在的組合可能會更快。
另外,我在這里根據您的查詢假設每個 listing_id/key 對有一行,并且您沒有將鍵存儲為字符串數組。如果是這樣,請告訴我,我會修改答案。
首先,我假設您不想要沒有匹配項的 ID,因此您可以像這樣構造它而不是生成列表。我使用 來func.count()過濾掉所有與所有鍵匹配的列表:
unique_incomplete_listings = session.query(Table.listing_id.label('listing_id'))
.group_by(Table.listing_id)
.having(func.count() < 3)
其次,將其轉換為CTE,然后從查詢中獲取 (listing, key) 的所有可能組合:
from sqlalchemy.dialects.postgresql import array
unique_incomplete_listings = unique_incomplete_listings.cte()
all_potential_matches = session.query(
unique_incomplete_listings.c.listing_id,
# this creates a cartesian product of listing_ids to elements in the array
func.unnest(array(['key1', 'key2', 'key3']))
)
使用EXCEPT刪除您在數據庫中找到的任何匹配項
query = all_potential_matches.except_all(
session.query(Table.listing_id, Table.key)
# We join here to prevent doing extra work if the listing does have all keys.
# If this makes the query slower, consider making the CTE a subquery and
# removing this join instead
.join(unique_incomplete_listings,
unique_incomplete_listings.c.listing_id == Table.listing_id)
)
添加回答
舉報