- ~
查找全部員工入職時候的薪水狀況,給出emp_no以及salary, 並按照emp_no進行逆序
CREATE TABLE employees
(emp_no
int(11) NOT NULL,birth_date
date NOT NULL,first_name
varchar(14) NOT NULL,last_name
varchar(16) NOT NULL,gender
char(1) NOT NULL,hire_date
date NOT NULL,
PRIMARY KEY (emp_no
));測試
CREATE TABLE salaries
(emp_no
int(11) NOT NULL,salary
int(11) NOT NULL,from_date
date NOT NULL,to_date
date NOT NULL,
PRIMARY KEY (emp_no
,from_date
));spa
此題應注意如下四個知識點: 一、因爲測試數據中,salaries.emp_no不惟一(由於號碼爲emp_no的員工會有屢次漲薪的可能,因此在salaries中對應的記錄不止一條),employees.emp_no惟一,即salaries的數據會多於employees,所以需先找到employees.emp_no在salaries表中對應的記錄salaries.emp_no,則有限制條件e.emp_no = s.emp_no 二、根據題意注意到salaries.from_date 和employees.hire_date的值應該要相等,所以有限制條件 e.hire_date = s.from_date 三、根據題意要按照emp_no值逆序排列,所以最後要加上 ORDER BY e.emp_no DESC 四、爲了代碼良好的可讀性,運用了Alias別名語句,將employees簡化爲e,salaries簡化爲s,即 employees AS e與salaries AS s,其中AS能夠省略 方法一:利用 INNER JOIN 鏈接兩張表 SELECT e.emp_no, s.salary FROM employees AS e INNER JOIN salaries AS s ON e.emp_no = s.emp_no AND e.hire_date = s.from_date ORDER BY e.emp_no DESC 方法二:直接用逗號並列查詢兩張表 SELECT e.emp_no, s.salary FROM employees AS e, salaries AS s WHERE e.emp_no = s.emp_no AND e.hire_date = s.from_date ORDER BY e.emp_no DESC