2011-10-03 116 views
1

我是新来的SQL和在读的加入,但我有点困惑所以想帮助....SQL查询加入2个表

我有一个表称为student_sport存储StudentID和SportID

我有另一个表存储细节匹配...所以基本上sportsID,MatchId,...

我想要做的是....对于一个perticular学生显示在其中比赛已发挥的体育。即。如果一个sportID存在于第二张表中,那么当我检查学生演奏的是哪一项运动时,就会显示这个。

ResultSet中只能包含在比赛已经打....

感谢

+0

这并不困难。既然这是一个家庭作业问题,那么你最好看看它。这里是一个暗示:谷歌的“内部连接” –

+0

我的想法是这样 SELECT * FROM表1 WHERE EXISTS(SELECT * FROM表2) 但不知道如何做到这一点的perticulat学生 – John

+0

@约翰:子查询使用子查询过度复杂。子查询会给你哪些行在另一个表中有相应的行,而连接则会给你所有相应行的组合。而你确实需要从另一张桌子上的位,对吧? –

回答

2

这时你有两个表:

// 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:包括扬邬达克评析,为德克萨斯州它

+0

谢谢.....我基本上理解如何现在加入... – John

+0

不客气...不要犹豫 –

+0

这是正确的,但两个尼姑:1.我会添加(添加,不只是使用;重要的是要知道它们的意思是相同的)等效的join/on语法;它使得复杂的查询更容易理解,所以学习是很好的,2.请使用标准的SQL注释使用'--'领导者,因为所有的数据库都接受这些注释,更多的接受C风格的评论,很少接受你使用的C++风格的评论。 –

-1

学生的体育嘛查询是类似的东西:

select sm.* 
from student_sport ss join student_matches sm on ss.sportid = sm.sportId 
where ss.StudentId = @studendId 

Thisthis应该给你一些SQL连接的见解

3

好的,因为这是作业(感谢老实说​​)我不会提供解决方案。

设计查询的通用方法是:如何写FROM块

  • 思(什么是您的数据源)
  • 怎么会想到写WHERE块(申请什么过滤器)
  • 写入SELECT块(你想从过滤的数据中得到)。

你显然需要加入你的两个表。对于加入的语法是:

FROM table1 
JOIN table2 ON boolean_condition 

这里您boolean_condition是你的两个表中的列sportid之间的平等。

您还需要筛选您的加入将生成的记录,以便仅保留与您的特定学生匹配的记录,并使用WHERE子句。

之后,选择你需要的东西(你想要所有的运动ID)。

这有帮助吗?

+0

+1给出一个解释,而不仅仅是确切的答案 –

0

因为您只需要返回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;