如何select其他条件下的最新工资? MySQL

How to select the latest salary under some other conditions? MySQL

我想select只是高级女员工的最新工资。我现在有以下查询:

SELECT 
    e.emp_no,
    e.gender,
    tit.title,
    s.* 

FROM employees e
INNER JOIN titles tit ON tit.emp_no = e.emp_no
INNER JOIN salaries s ON e.emp_no = s.emp_no
WHERE e.gender = "F"
AND tit.title LIKE '%Senior%'


结果如下:

gender  title               emp_no  salary  from_date       to_date
"F"     "Senior Engineer"   "10006" "40000" "1990-08-05"    "1991-08-05"
"F"     "Senior Engineer"   "10006" "42085" "1991-08-05"    "1992-08-04"
"F"     "Senior Engineer"   "10006" "42629" "1992-08-04"    "1993-08-04"
"F"     "Senior Engineer"   "10006" "45844" "1993-08-04"    "1994-08-04"
"F"     "Senior Engineer"   "10006" "47518" "1994-08-04"    "1995-08-04"
"F"     "Senior Engineer"   "10006" "47917" "1995-08-04"    "1996-08-03"
"F"     "Senior Engineer"   "10006" "52255" "1996-08-03"    "1997-08-03"
"F"     "Senior Engineer"   "10006" "53747" "1997-08-03"    "1998-08-03"
"F"     "Senior Engineer"   "10006" "56032" "1998-08-03"    "1999-08-03"
"F"     "Senior Engineer"   "10006" "58299" "1999-08-03"    "2000-08-02"
"F"     "Senior Engineer"   "10006" "60098" "2000-08-02"    "2001-08-02"
"F"     "Senior Engineer"   "10006" "59755" "2001-08-02"    "9999-01-01"
"F"     "Senior Staff"      "10007" "56724" "1989-02-10"    "1990-02-10"
"F"     "Senior Staff"      "10007" "60740" "1990-02-10"    "1991-02-10"
"F"     "Senior Staff"      "10007" "62745" "1991-02-10"    "1992-02-10"


我在这里错过了什么?

如果您只想要最新的,您可以使用按 to_date 排序 并限制 1

SELECT 
    e.emp_no,
    e.gender,
    tit.title,
    s.* 

FROM employees e
INNER JOIN titles tit ON tit.emp_no = e.emp_no
INNER JOIN salaries s ON e.emp_no = s.emp_no
WHERE e.gender = "F"
AND tit.title LIKE '%Senior%'
order by to_date 
limit 1 

并且对于每个 emp_no ypu 可以使用带有 subqiery formax(to_date)

的连接
  SELECT 
      e.emp_no,
      e.gender,
      tit.title,
      s.* 

  FROM employees e
  INNER JOIN titles tit ON tit.emp_no = e.emp_no
  INNER JOIN salaries s ON e.emp_no = s.emp_no
  INNER JOIN  (
          SELECT 
          e.emp_no,
          max(s.to_date) max_date 
      FROM employees e
      INNER JOIN titles tit ON tit.emp_no = e.emp_no
      INNER JOIN salaries s ON e.emp_no = s.emp_no
      WHERE e.gender = "F"
      AND tit.title LIKE '%Senior%'
      GROUP BY e.emp_no 
  ) t on t.emp_no  = e.emp_no 
      AND s.to_date = t.max_date
  WHERE e.gender = "F"
  AND tit.title LIKE '%Senior%'

您缺少只显示最后工资的条件。表达这一点的一种方法是要求员工没有以后的工资:

SELECT 
  e.emp_no,
  e.gender,
  tit.title,
  s.* 
FROM employees e
INNER JOIN titles tit ON tit.emp_no = e.emp_no
INNER JOIN salaries s ON e.emp_no = s.emp_no
WHERE e.gender = 'F'
AND tit.title LIKE '%Senior%'
AND NOT EXISTS
(
  SELECT *
  FROM salaries s2
  WHERE s2.emp_no = s.emp_no
  AND s2.from_date > s.from_date
);

或select所有最新日期并使用它们:

...
AND tit.title LIKE '%Senior%'
AND (emp_no, from_date) IN
(
  SELECT emp_no, MAX(from_date)
  FROM salaries
  GROUP BY emp_no
);