Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

python - sqlalchemy select duplicates from multiple lists

I Have two list (a real case):

user_1_list = [(3, True), (4, True), (5, True), (6, True), (7, True), (8, True), (9, True), (12, True), (13, True), (14, True)]  # 10 items
user_2_list = [(1, True), (2, True), (3, False), (4, True), (5, True), (6, True), (7, True), (8, False)]  # 8 items

both lists I'm getting via sqlalchemy query:

db.query(Table.post_id, Table.bool_value).filter(Table.user_id == user_id).all()

How I can combine a single sqlalchemy query to get post_id - bool_value pairs that present (matching) in both lists? P.S. list with distinct pairs I also need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPD

There are couple of ways I have on my mind:

  1. utilize count and window functions, and then filter where count = 2 (but it just a bit complex to write this in sqlalchemy)
  2. Just do inner join

Please, try something like this

user_query_1 = db.query(Table.post_id, Table.bool_value).filter(Table.user_id == user_id_1).subquery()
user_query_2 = db.query(Table.post_id, Table.bool_value).filter(Table.user_id == user_id_2).subquery()

(
    user_query_1
    .join(
        user_query_2,
        and_(
            user_query_1.c.post_id == user_query_2.c.post_id,
            user_query_1.c.bool_value == user_query_2.c.bool_value,
        )
    )
    .all()
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...