我是新來的SQL和在讀的加入,但我有點困惑所以想幫助....SQL查詢加入2個表
我有一個表稱爲student_sport存儲StudentID和SportID
我有另一個表存儲細節匹配...所以基本上sportsID,MatchId,...
我想要做的是....對於一個perticular學生顯示在其中比賽已發揮的體育。即。如果一個sportID存在於第二張表中,那麼當我檢查學生演奏的是哪一項運動時,就會顯示這個。
ResultSet中只能包含在比賽已經打....
感謝
我是新來的SQL和在讀的加入,但我有點困惑所以想幫助....SQL查詢加入2個表
我有一個表稱爲student_sport存儲StudentID和SportID
我有另一個表存儲細節匹配...所以基本上sportsID,MatchId,...
我想要做的是....對於一個perticular學生顯示在其中比賽已發揮的體育。即。如果一個sportID存在於第二張表中,那麼當我檢查學生演奏的是哪一項運動時,就會顯示這個。
ResultSet中只能包含在比賽已經打....
感謝
這時你有兩個表:
// One record per student/sport association
student_sport
StudentID
SportID
// A match is only for one sport (warning to your plural) no?
matches
SportID
MacthID
您想要的:對於一個學生的所有體育在比賽
SELECT DISTINCT StudentID, student_sport.SportID
FROM student_sport, matches
WHERE
-- Select the appropriate player
student_sport.StudentID = @StudentID
-- Search all sport played in a match and plays by the student
-- (common values sportid btw student_sport & matches)
AND student_sport.SportID = matches.SportID
或使用其他語法(加盟)已經發揮(它使複雜查詢更容易理解,所以這是很好的學習)
SELECT DISTINCT StudentID, student_sport.SportID
FROM student_sport
-- Search all sport played in a match and plays by the student
-- (common values sportid btw student_sport & matches)
INNER JOIN matches on student_sport.SportID = matches.SportID
WHERE
-- Select the appropriate player
student_sport.StudentID = @StudentID
PS:包括揚鄔達克評析,爲德克薩斯州它
謝謝.....我基本上理解如何現在加入... – John
不客氣...不要猶豫 –
這是正確的,但兩個尼姑:1.我會添加(添加,不只是使用;重要的是要知道它們的意思是相同的)等效的join/on語法;它使得複雜的查詢更容易理解,所以學習是很好的,2.請使用標準的SQL註釋使用'--'領導者,因爲所有的數據庫都接受這些註釋,更多的接受C風格的評論,很少接受你使用的C++風格的評論。 –
好的,因爲這是作業(感謝老實說)我不會提供解決方案。
設計查詢的通用方法是:如何寫FROM塊
你顯然需要加入你的兩個表。對於加入的語法是:
FROM table1
JOIN table2 ON boolean_condition
這裏您boolean_condition是你的兩個表中的列sportid
之間的平等。
您還需要篩選您的加入將生成的記錄,以便僅保留與您的特定學生匹配的記錄,並使用WHERE
子句。
之後,選擇你需要的東西(你想要所有的運動ID)。
這有幫助嗎?
+1給出一個解釋,而不僅僅是確切的答案 –
因爲您只需要返回student_sport
表中的結果,所以連接類型爲semijoin。用於半連接的標準SQL操作符足夠有趣MATCH
SELECT *
FROM student_sport
WHERE SportID MATCH (
SELECT SportID
FROM matches
WHERE student_sport.SportID = matches.SportID
);
在SQL中編寫半連接還有很多其他方法,例如:這裏有三個:
SELECT *
FROM student_sport
WHERE SportID IN (
SELECT SportID
FROM matches
WHERE student_sport.SportID = matches.SportID
);
SELECT *
FROM student_sport
WHERE EXISTS (
SELECT *
FROM matches
WHERE student_sport.SportID = matches.SportID
);
SELECT student_sport.*
FROM student_sport
INNER JOIN matches
ON student_sport.SportID = matches.SportID;
這並不困難。既然這是一個家庭作業問題,那麼你最好看看它。這裏是一個暗示:谷歌的「內部連接」 –
我的想法是這樣 SELECT * FROM表1 WHERE EXISTS(SELECT * FROM表2) 但不知道如何做到這一點的perticulat學生 – John
@約翰:子查詢使用子查詢過度複雜。子查詢會給你哪些行在另一個表中有相應的行,而連接則會給你所有相應行的組合。而你確實需要從另一張桌子上的位,對吧? –