亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

sqlalchemy:獲取值不存在的ID

sqlalchemy:獲取值不存在的ID

白衣非少年 2023-04-18 16:03:19
有一個tablewith columns listing_ids,keys如何獲取listing_ids(和相應的缺失鍵)其中list_of_values不存在的值keys?list_of_values = [key2,key3]桌子listing_id  keys424         key1424         key2424         key3523         key12433        key22433        key153          key23           key3我需要得到以下結果:listing_id  keys_that_does_not_exist523         key2523         key32433        key353          key33           key2我試過:ids_without_keys_q = session.query(Table)\                             .filter(~ exists().where(Table.key.in_(list_of_values))我在用postgresql
查看完整描述

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)

)


查看完整回答
反對 回復 2023-04-18
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號