2017-03-21 60 views
0

我正在研究一個項目,顯示研究機會並讓學生註冊參與其中。在註冊研究時,服務器檢查用戶是否已經在同一研究的另一個時間片(不允許)。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 = "[email protected]" 

的問題是,當使用本網站的過程中,執行查詢,查詢返回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) 
); 
+0

錯誤/不同的數據庫?你已經給了很少的上下文去... –

+0

這絕對是相同的數據庫,什麼信息會有幫助嗎? –

+0

產生問題的最小自包含示例是理想選擇。您可以/應該至少包含精簡版模型定義。應該產生你想要的輸出的一小段示例數據是必須的。因爲它現在是非常難以驗證的,除非有人發現明確的編程錯誤,但是因爲如果將查詢轉換到不太可能的不同環境,查詢就可以工作。 –

回答

0

在嘗試了上面提到的一堆與SQL相關的事情後,我發現它與實際的語句或信息無關。問題出在服務器不同部分的邏輯上。

相關問題