MySQL:选择上次修改时具有一个属性但过去没有其他属性的项目

时间:2016-12-22 17:13:42

标签: mysql sql

所以我有一个以下面的方式构建的表标题

emp_no  title               from_date   to_date
109006  Senior Engineer     1998-02-10  9999-01-01
109008  Senior Engineer     1998-09-23  9999-01-01
109009  Senior Engineer     1998-10-21  9999-01-01
109010  Assistant Engineer  1986-05-23  1994-05-23
109010  Senior Engineer     2002-05-23  9999-01-01
109012  Senior Engineer     1995-08-31  2000-04-30
109014  Senior Engineer     1986-09-04  9999-01-01
109015  Senior Engineer     1996-10-15  9999-01-01
109017  Assistant Engineer  1997-06-22  9999-01-01
109018  Assistant Engineer  1988-08-15  1996-08-15

我想选择那些高级工程师,而不是那些助理工程师。例如,不应显示emp_no 109010 select * from titles where title='Senior Engineer' AND title NOT IN (select emp_no from titles where title='Assistant Engineer') 的那个。

我试过这个

@Configuration
@Profile("Test")
public class TestConfig {

    @Mock
    AmazonS3Client client;

    public TestConfig(){
        MockitoAnnotations.initMocks(this);
    }

    @Bean
    public AmazonS3Client amazonS3Client(){
        return client;
    }
}

但它不起作用。

2 个答案:

答案 0 :(得分:1)

你很近:

select * from titles 
where title='Senior Engineer' and emp_no
NOT IN (select emp_no from titles where title='Assistant Engineer')

答案 1 :(得分:0)

尝试:

SELECT *
FROM titles t
WHERE 

  -- items that have one atribute when last modified 
  title='Senior Engineer' 
  AND
  NOT EXISTS(
   SELECT null FROM titles t1
      AND t1.emp_no = t.empno
      AND t1.from_date > t.from_date
  )
  AND

  -- but did not have some other atrubute in the past
  NOT EXISTS(
   SELECT null FROM titles t1
      AND t1.emp_no = t.empno
      AND t1.from_date < t.from_date
      AND (t1.title <>'Senior Engineer' OR t1.title IS NULL)
  )