2013-11-26 44 views
0

我有以下兩個表:有麻煩了PostgreSQL的查詢

用戶

userid | email | phone 
1 | [email protected] | 555-555-5555 
2 | [email protected] | 555-444-3333 
3 | [email protected] | 333-444-1111 
4 | [email protected] | 123-333-2123 

UserTag

id | user_id | tag 
1 | 1 | tag1 
2 | 1 | tag2 
3 | 1 | cool_tag 
4 | 1 | some_tag 
5 | 2 | new_tag 
6 | 2 | foo 
6 | 4 | tag1 

我想運行在SQLAlchemy的查詢加入這兩個表並返回沒有標籤「tag1」或「tag2」的所有用戶。在這種情況下,查詢應返回用戶2和3。任何幫助將不勝感激。

我需要這個查詢的反面:

users.join(UserTag, User.userid == UserTag.user_id) 
    .filter(
     or_(
      UserTag.tag.like('tag1'), 
      UserTag.tag.like('tag2') 
     )) 
    ) 

我一直在這個持續了幾個小時,但總是用錯誤的用戶或有時他們都結束了。實現這一點的SQL查詢也會有所幫助。我會嘗試將其轉換爲SQLAlchemy。

回答

1

不知道如何做到這一點看在SQLAlchemy的,但希望和爲什麼查詢是它會幫助你到達那裏的方式解釋。

這是一個外部聯接 - 你想從一個表(用戶)即使有另一個表(UserTag)沒有記錄,如果我們把用戶首先它是一個左連接的所有記錄。除此之外,您需要在UserTag中沒有匹配特定過濾器的所有記錄。

SELECT user.user_id, email, phone 
    FROM user LEFT JOIN usertag 
    ON usertag.user_id = user.user_id 
    AND usertag.tag IN ('tag1', 'tag2') 
    WHERE usertag.user_id IS NULL; 
0

SQL會去這樣

select u.* from user u join usertag ut on u.id = ut.user_id and ut.tag not in ('tag1', 'tag2'); 
所以你需要將其轉換爲相當於SQLAlchemy的查詢我沒有使用SQLAlchemy的

希望它有幫助。

謝謝。

0

假設你的模型定義如下關係:

class User(Base): 
    ... 

class UserTag(Base): 
    ... 
    user = relationship("User", backref="tags") 

查詢如下:

qry = session.query(User).filter(~User.tags.any(UserTag.tag.in_(tags))).order_by(User.id)