我設法解決它在兩個查詢之間使用UNION,我相信我的嘗試是有點關閉,並試圖做一個數學增加。這是problaby不是你可以做到的最好方式,但它有效,對我來說就足夠了。感謝您的幫助。創建視圖+查詢(組合列+添加額外的屬性)
工作液:
CREATE VIEW Registrations AS
(SELECT S.identificationnumber AS StudentId, S.name AS StudentName, C.code AS CourseCode, C.name AS CourseName, 'Waiting' AS Status
FROM Waitinglist W, Student S, Course C
WHERE S.identificationnumber = W.identificationnumber
AND W.code = C.code) UNION (SELECT S.identificationnumber AS StudentId, S.name AS StudentName, C.code AS CourseCode, C.name AS CourseName, 'Registered' AS Status
FROM Registeredat R, Student S, Course C
WHERE S.identificationnumber = R.identificationnumber
AND R.code = C.code);
原著的問題:
我在數據庫和SQL一個begginner,這樣的事情可能不看那個專業。
我想用純文本做什麼: 我試圖爲所有註冊和等待學生創建所有課程的視圖。我還想添加一個新的「列」,即「註冊」或「等待」。
我怎麼想的觀點看:
StudentID, StudentName, CourseCode, CourseName, Status
StudentID = Combined idenficationnumber for Table "RegisterdAt" and "Waitinglist"
StudentName = Based on StudentID find matching name in Table "Student"
CourseCode = Combined code for Table "RegisterdAt" and "Waitinglist"
CourseName = based on code find matching name in Table "Course"
Status = Either "registered" or "waiting"
depending on if we got the "row" from Table "RegisterdAt" or "Waitinglist"
的創建的表(我還添加了一些examplery數據放進去,更容易測試):
CREATE TABLE Student(
identificationnumber VARCHAR(20),
name VARCHAR(50),
branchname VARCHAR(50),
programmename VARCHAR(50),
PRIMARY KEY(identificationnumber),
FOREIGN KEY(branchname, programmename) REFERENCES Branch(name, programmename)
);
CREATE TABLE Course(
code CHAR(6),
name VARCHAR(50),
credits VARCHAR(10),
departmentname VARCHAR(50),
PRIMARY KEY(code),
FOREIGN KEY(departmentname) REFERENCES Department(name)
);
CREATE TABLE Waitinglist(
identificationnumber VARCHAR(20),
code CHAR(6),
ddate VARCHAR(10),
PRIMARY KEY(identificationnumber, code),
FOREIGN KEY(identificationnumber) REFERENCES Student(identificationnumber),
FOREIGN KEY(code) REFERENCES Course_with_maxstudents(code)
);
CREATE TABLE Registeredat(
identificationnumber VARCHAR(20),
code CHAR(6),
PRIMARY KEY(identificationnumber,code),
FOREIGN KEY(identificationnumber) REFERENCES Student(identificationnumber),
FOREIGN KEY(code) REFERENCES Course(code)
);
試圖創建視圖(不工作,缺少註冊/等待屬性):
CREATE VIEW Registrations AS
SELECT (R.identificationnumber + W.identificationnumber) AS StudentId, S.name AS StudentName, (R.code + W.code) AS CourseCode, C.name as CourseName
FROM Registeredat R, Waitinglist W, Student S, Course C
WHERE S.identificationnumber = (R.identificationnumber + W.identificationnumber)
AND C.code = (R.code + W.code);
當我進入你的'創建table's和'創建view'到[SQL小提琴(http://www.sqlfiddle.com/#!2/4c307 ),沒有投訴。 –
表應該工作,「創建視圖」不會爲我工作,雖然。但我沒有嘗試過使用「SQL小提琴」。但是如果你看到這個視圖可以工作,你知道如何在視圖中添加一個額外的列「狀態」:根據我們是從表「RegisterdAt」還是「 Waitinglist「 – Pro9