SQLAlchemy查询不返回与数据库相同的值

时间:2017-03-21 13:00:14

标签: sql flask sqlalchemy flask-sqlalchemy

我正在研究一个展示研究机会的项目,让学生注册参与其中。注册研究时,服务器会检查用户是否已经在同一研究的另一个时间段(不允许)。

SQLAlchemy代码如下:

same_study = db.session.query(db.func.count(['*'])) \
            .filter(Research.research_id == ResearchSlot.research_id) \
            .filter(ResearchSlot.research_slot_id == StudentResearch.research_slot_id) \
            .filter(StudentResearch.user_id == Users.user_id) \
            .filter(StudentResearch.student_research_id == slot_id) \
            .filter(Users.user_email == user_email) \
            .scalar()

在这里,slot_id和user_email是变量。当这个查询运行时(我输出正在运行的查询),它看起来像这样:

SELECT count(*)
FROM Research, ResearchSlot, StudentResearch, Users 
WHERE Research.ResearchID = ResearchSlot.ResearchID 
AND ResearchSlot.ResearchSlotID = StudentResearch.ResearchSlotID 
AND StudentResearch.UserID = Users.UserID 
AND StudentResearch.StudentResearchID = 10
AND Users.UserEmail = "foo@bar.com"

问题是,当在网站使用期间执行查询时,查询返回0(意味着它们不在同一研究的另一个实例中)应该返回1(因为它们在另一个实例中) 。当我从MySQL工作台手动执行此查询时,它按预期返回1。为什么不同?

CREATE TABLE Users (
    UserID BIGINT NOT NULL AUTO_INCREMENT,
    UserEmail VARCHAR(100) NOT NULL,
    UserPWHash VARCHAR(64) NOT NULL,
    UserSalt VARCHAR(64) NOT NULL,
    UserRole BIGINT NOT NULL,
    UserPsychMajor BOOLEAN NOT NULL,
    UserPsychMinor BOOLEAN NOT NULL,
    CreatedOn DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (UserID),
    FOREIGN KEY (UserRole) REFERENCES Role(RoleID)
);

CREATE TABLE Research (
    ResearchID BIGINT NOT NULL AUTO_INCREMENT,
    ResearchName VARCHAR(100) NOT NULL,
    ResearchFacilitator BIGINT NOT NULL,
    ResearchDescription VARCHAR(500) NOT NULL,
    ResearchCredits INT NOT NULL,
    IsVisible BOOLEAN DEFAULT TRUE NOT NULL,
    IsDeleted BOOLEAN DEFAULT FALSE NOT NULL,
    CreatedOn DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (ResearchID),
    FOREIGN KEY (ResearchFacilitator) REFERENCES Users(UserID)
);

CREATE TABLE ResearchSlot (
    ResearchSlotID BIGINT NOT NULL AUTO_INCREMENT,
    ResearchID BIGINT NOT NULL,
    ResearchSlotOpenings INT NOT NULL,
    StartTime DATETIME NOT NULL,
    EndTime DATETIME NOT NULL,
    CreatedOn DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (ResearchSlotID),
    FOREIGN KEY (ResearchID) REFERENCES Research(ResearchID)
);

CREATE TABLE StudentResearch (
    StudentResearchID BIGINT NOT NULL AUTO_INCREMENT,
    UserID BIGINT NOT NULL,
    ResearchSlotID BIGINT NOT NULL,
    IsCompleted BOOLEAN DEFAULT FALSE NOT NULL,
    CreatedOn DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY (StudentResearchID),
    FOREIGN KEY (UserID) REFERENCES Users(UserID),
    FOREIGN KEY (ResearchSlotID) REFERENCES ResearchSlot(ResearchSlotID)
);

1 个答案:

答案 0 :(得分:0)

在尝试了上面提到的一堆与SQL相关的事情之后,我发现它与实际的声明或信息无关。问题在于服务器不同部分的逻辑。