我需要连接两个表来获取student_info表中的所有记录

时间:2011-01-26 08:35:13

标签: sql-server sql

我需要连接两个表来获取student_info表中的所有记录,以及student_activities表中student_id相等的记录。

由于单个student_id的学生活动表中可能有多条记录,因此当我使用左连接打印输出时,我会收到重复记录。

SELECT *
FROM student_info 
LEFT JOIN student_activities 
ON student_info.student_id=student_activities.student _id

有人建议我使用以下内容,但我得到错误,说明特定字段不是聚合函数的一部分。

SELECT student_info.student_id, student_info.student_name, student_info.phone, student_info.age, COUNT (student_activities.student_id) AS COA
FROM student_info 
LEFT OUTER JOIN student_activities 
ON student_info.student_id=student_activities.student_id 
GROUP BY student_info.student_id

3 个答案:

答案 0 :(得分:1)

  SELECT student_info.student_id, student_info.student_name, student_info.phone, student_info.age, ISNULL(t.COA, 0) COA
  FROM   student_info
  LEFT   JOIN (SELECT student_id, COUNT(*) COA FROM student_activities GROUP BY student_id) t
  ON     student_info.student_id = t.student_id

答案 1 :(得分:1)

SELECT 
 student_info.student_id, 
 student_info.student_name, 
 student_info.phone, 
 student_info.age, 
 COUNT (student_activities.student_id) AS COA
FROM student_info LEFT OUTER JOIN student_activities 
ON student_info.student_id=student_activities.student_id 
GROUP BY student_info.student_id,student_info.student_name, student_info.phone, student_info.age

答案 2 :(得分:0)

未经测试,但应该有效或类似:

SELECT DISTINCT *
FROM student_info 
WHERE student_info.student_id = 
(SELECT student_activities.student _id FROM student_activities)