SQL 查询 select * if <this> 但 not if <condition>

rsh*_*haq 2 sql if-statement

我有一个表存储员工姓名和工作年限。这些列是:

employeeID int NOT NULL,
year int NOT NULL
Run Code Online (Sandbox Code Playgroud)

主键是复合的:employeeID 和year。我需要选择表中存在 2012 年该员工 ID 的所有记录,但不选择 2011 年。换句话说,我需要一个在 2012 年工作但不在 2011 年工作的员工列表。我不知道为什么我不能这样做!如果您理解该问题,请跳过下面的 Java 代码。

如果我用 Java 解析员工表,它将是:

// This is what is returned at the end
List theQueryResults = new List();

// This would be all employees and the years they worked, assume it's filled.
Table employees = new Table (int employeeID, int year); 

for (int i = 0; i < employees.count(); i++) {
    boolean addToQuery = false;
    for (int j = 0; j < employees[0].length; j++) {
        if ( theArray[i][j] == 2011) {
            addToQuery = false;
            break;
        }
        if ( theArray[i][j] == 2012) { addToQuery = true; }
    }

    if (addToQuery == true) { theQueryResults.add(employees[i].id); }
}
Run Code Online (Sandbox Code Playgroud)

我将不胜感激。我脑子有病

Ste*_*rea 5

SELECT employeeID 
FROM tab
WHERE year = 2012
and employeeID not in (SELECT employeeID FROM tab WHERE year = 2011)
Run Code Online (Sandbox Code Playgroud)