为什么我的 sqlalchemy 查询代码出错,而 raw mysql 却没有?
Why is my code for sqlalchemy query getting an error while raw mysql isn't?
我在使用 SQLAlchemy 时遇到问题。执行以下代码时出现错误 (1066, "Not unique table/alias: \'user_role\'")
。如果我要在从 sqlalchmey 查询字符串中获取的 mysql-console 中自己执行查询,我不会收到这样的错误。是什么让 sqlachemy 抛出了这样的错误?
用户角色是 table user_role。
@classmethod
def get_stud_no_edu_route(cls, cur_user):
query = cur_user.db.query(User)\
.join(UserRole, User.id == UserRole.user_id) \
.join(School, UserRole.school_id == School.id) \
.filter((UserRole.role == Role.STUDENT) & (User.educational_route == None) & (School.name.like('%gymnas%')))
query = User.apply_dashboard_permission(query, cur_user)
return query
原始 mysql:
SELECT user.id AS user_id, user.active AS user_active, user.was_activated AS user_was_activated, user.archived AS user_archived, user.hidden_photo AS user_hidden_photo, user.first_name AS user_first_name, user.last_name AS user_last_name, user.full_name AS user_full_name
FROM user INNER JOIN user_role ON user.id = user_role.user_id INNER JOIN school ON user_role.school_id = school.id
WHERE user_role.`role` = 'Student' AND user.educational_route IS NULL AND school.name LIKE '%gymnas%';
出于某种原因,问题不是 user_role 而是学校问题。第二天打开项目后,错误问题是 'school' 而不是 'user_role'.
我之前尝试添加 stud_roles = orm.aliased(UserRole)
但无济于事。通过添加 schools = orm.aliased(School)
以及我的问题得到解决。
我读到 select-query 中的每个 table 都需要别名。不是 100% 的原因,但它解决了我的问题。
我在使用 SQLAlchemy 时遇到问题。执行以下代码时出现错误 (1066, "Not unique table/alias: \'user_role\'")
。如果我要在从 sqlalchmey 查询字符串中获取的 mysql-console 中自己执行查询,我不会收到这样的错误。是什么让 sqlachemy 抛出了这样的错误?
用户角色是 table user_role。
@classmethod
def get_stud_no_edu_route(cls, cur_user):
query = cur_user.db.query(User)\
.join(UserRole, User.id == UserRole.user_id) \
.join(School, UserRole.school_id == School.id) \
.filter((UserRole.role == Role.STUDENT) & (User.educational_route == None) & (School.name.like('%gymnas%')))
query = User.apply_dashboard_permission(query, cur_user)
return query
原始 mysql:
SELECT user.id AS user_id, user.active AS user_active, user.was_activated AS user_was_activated, user.archived AS user_archived, user.hidden_photo AS user_hidden_photo, user.first_name AS user_first_name, user.last_name AS user_last_name, user.full_name AS user_full_name
FROM user INNER JOIN user_role ON user.id = user_role.user_id INNER JOIN school ON user_role.school_id = school.id
WHERE user_role.`role` = 'Student' AND user.educational_route IS NULL AND school.name LIKE '%gymnas%';
出于某种原因,问题不是 user_role 而是学校问题。第二天打开项目后,错误问题是 'school' 而不是 'user_role'.
我之前尝试添加 stud_roles = orm.aliased(UserRole)
但无济于事。通过添加 schools = orm.aliased(School)
以及我的问题得到解决。
我读到 select-query 中的每个 table 都需要别名。不是 100% 的原因,但它解决了我的问题。