SQL查询从满足条件的两个表

时间:2017-11-20 07:21:21

标签: mysql sql

Table 1 name: Student
Name      Department
Alex         CSE
Bob          EEE
Briyan       ME
John         CSE
James        ETE
Mike         CE

Table 2 name: Program
Department    Semester
   CSE         Summer
   CSE         Winter
   EEE         Summer
   ETE         Summer
   ME          Winter
   CE          Summer
   CE          Winter

打印名称和学期的SQL查询是什么,每个学生的部门只有一种类型的学期? (服务器是mysql)

SQL Query Result should be like this:
Name     Semester
Bob       Summer
Briyan    Winter
James     Summer

在这里,CSE和CE都有夏季和冬季学期。所以Alex,John和Mike都不包括在内。

我试过这个:

SELECT Student.Name,
     Program.Semester
FROM Student
JOIN Program
    ON Program.Department = Student.Department
WHERE ....

4 个答案:

答案 0 :(得分:1)

您可以在子查询上使用In子句,只需要一个条目就可以使用

  select a.Name, b.Departmnet 
  from Student a
  inner join program b on a.Department = b.Department and b.Department In (
  select Department from Program
  group by Department having count(*)=1 
  ) 

答案 1 :(得分:1)

CREATE TABLE #Student(Name NVARCHAR(50),Department NVARCHAR(50))
CREATE TABLE  #Program (Department NVARCHAR(50),Semester NVARCHAR(50))

INSERT INTO #Student
SELECT 'Alex','CSE' UNION ALL 
SELECT 'Bob','EEE'   UNION ALL 
SELECT 'Briyan','ME' UNION ALL 
SELECT 'John','CSE' UNION ALL 
SELECT 'James','ETE' UNION ALL 
SELECT 'Mike','CE'


INSERT INTO #Program
SELECT 'CSE','Summer' UNION ALL 
SELECT 'CSE','Winter' UNION ALL 
SELECT 'EEE','Summer'UNION ALL 
SELECT 'ETE','Summer'UNION ALL 
SELECT 'ME','Winter'UNION ALL 
SELECT 'CE','Summer'UNION ALL 
SELECT 'CE','Winter'

;WITH CTE AS (
  SELECT Name ,MAX(b.Semester)semester
  FROM #Student a INNER JOIN  #Program b ON a.Department=b.Department
  group by name
  having count(distinct semester) = 1

)
SELECT * FROM CTE 

GO

答案 2 :(得分:1)

您希望加入单学期部门的学生。因此,按学期汇总您的课程数据,以获得单学期的部门。由于这些部门只有一个学期,您可以使用any_value(semester)学习该学期。

select s.name, d.the_semester
from student s
join
(
  select any_value(semester) as the_semester
  from program
  group by department
  having count(*) = 1
) d on d.department = s.department
order by s.name;

另一种方法是让所有学生学期组合和学生分组只保留单学期学生。

select s.name, any_value(p.semester) as the_semester
from student s
join program p on p.department = s.department
group by s.name
having count(*) = 1
order by s.name;

选择您最喜欢的查询。

答案 3 :(得分:0)

您可以在having子句中使用聚合和过滤器来查找只有一个学期的名称:

select s.name,
    max(p.semester) as semester
from student s
join program p
    on s.department = p.department
group by s.name
having count(distinct p.semester) = 1;