Sql-Server

SQL查詢來自兩個滿足條件的表

  • November 22, 2017
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 查詢是什麼?

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 ....

您想執行這樣的查詢(請參閱此處的 db-fiddle ):

SELECT 
 st.student_name, 
 -- st.student_dept,  -- <<= uncomment for an insight into
 -- sm.semester_dept, -- <<= how the query works!
 sm.semester_name
FROM student st
JOIN semester sm
ON
 st.student_dept = sm.semester_dept
WHERE st.student_dept IN
(
 SELECT
   sm.semester_dept AS sem_dept
 FROM semester sm
 GROUP BY sm.semester_dept
 HAVING COUNT(sm.semester_dept) = 1 
)

結果:

Student name  Semester name
___________________________
        Bob         Summer
     Briyan         Winter
      James         Summer

此查詢(我相信)適用於任何/所有主要的 RDBMS 伺服器 - 適用於 MySQL 和(我的參考實現,此處為 PostgreSQL )。哦,是的,只是需要注意一點 - 該student_name欄位應該是 a PRIMARY KEY(或至少UNIQUE帶有NOT NULL),以保證它正常工作!

這個解決方案比我原來的查詢解決方案(這裡)要優雅得多——感謝@ypercube 的提示!

============== DDL和DML ==================

CREATE TABLE student
(
 student_name VARCHAR (20) NOT NULL,
 student_dept VARCHAR (4) NOT NULL
);

INSERT INTO student VALUES
('Alex',   'CSE'),
('Bob' ,   'EEE'),
('Briyan', 'ME'),
('John',   'CSE'),
('James',  'ETE'),
('Mike',   'CE');

CREATE TABLE semester
(
 department VARCHAR (4) NOT NULL,
 semester   VARCHAR (6) NOT NULL
);

INSERT INTO semester VALUES
('CSE', 'Summer'),
('CSE', 'Winter'),
('EEE', 'Summer'),
('ETE', 'Summer'),
('ME',  'Winter'),
('CE',  'Summer'),
('CE',  'Winter');

引用自:https://dba.stackexchange.com/questions/191262