SQL-Alchemy连接查询 - 最有效的查询方式

时间:2014-08-02 00:07:28

标签: python sql flask sqlalchemy flask-sqlalchemy

我正在尝试生成一个查询,并且很难找到在sqlalchemy中执行此操作的最有效方法,(注意我使用flask-sqlalchemy)

目标是找到所有用户与特定用户的会议。

所以让我们说弗兰克有10次会议,我想生成一份弗兰克会见的所有人的名单。

以下是我的模特:

class UserMeeting(db.Model):
    """ Associative table, links meetings to users in a many to many fashion"""
    __tablename__ = 'userMeeting'
    id = db.Column(db.Integer, primary_key = True)
    meeting_id = db.Column(db.Integer, db.ForeignKey('meeting.id'), primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)

class Meeting(db.Model):
    __tablename__ = "meeting"
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(128))
    #... other columns
    #associative reference
    attendees = db.relationship('UserMeeting', backref='meeting')

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(128), index=True, unique=True)
    password = db.Column(db.String(128))
    #associative reference
    attendingMeetings = db.relationship("UserMeeting", backref="user", cascade="all, delete-orphan") 

以下是我尝试的内容:

#Assume frank's a user with id == 1
frank = User.query.get(1)
franks_meetings = Meeting.query.join(Meeting.attendees).filter(UserMeeting.user == frank).all()
#not efficient way of getting users in meetings with frank
users = []
for meeting in franks_meetings:
    for userMeeting in meeting.attendees:
        if userMeeting.user != frank:
            users.append(userMeeting.user)

#is there a way to just generate one query and get this data?

我似乎错过了如何使用连接来获取此数据。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

您需要使用meeting_id作为连接键加入UserMeeting表。您可能需要对表进行别名以便引用它两次。我不知道我是否可以在我的脑海中输入sqlalchemy语法,但是sql看起来像:

select distinct(b.user_id) as other_user_id
from usermeeting a
inner join usermeeting b
on a.meeting_id=b.meeting_id
where a.user_id=1 and b.user_id != 1;

1是弗兰克。

哦,并获得用户的详细信息。可能你最终会在sqlalchemy中直接使用User个对象:

select distinct(u.id), u.email
from usermeeting a
inner join usermeeting b
on a.meeting_id=b.meeting_id
inner join users u
on b.user_id=u.id
where a.user_id=1 and b.user_id != 1;

答案 1 :(得分:1)

这里是查询的sqlalchemy版本供参考:

#get all users in meetings with Frank, (frank.id == 1)
um = aliased(UserMeeting)
frank = User.query.get(1)

q = session.query(User).join(User.attendingMeetings).\
    filter(UserMeeting.meeting_id == um.meeting_id).\
    filter(UserMeeting.user_id != frank.id, um.user_id == frank.id)

users_meeting_with_frank = q.all()