我有两个表,table1
和table2
。我已经用一些条件编写了查询,如下所示
Select t2.employee_id,
t2.adddate,
t2.previousaleave
from table2 as t2, table1 as t1
WHERE t1.enddate IS NULL
OR t1.enddate>t2.adddate
AND t2.adddate<=now()
AND t2.leavetype='annualleave'
如果我运行它,条件不起作用。它正在选择表t2.的所有empid。我检查问题是否为t1.enddate is NULL
条件。由于enddate
列可以是
null
如果t1.enddate IS NULL
和其他条件成功,我需要获得empid。这里留下的类型与每个empid不同。 (每位员工只有一行用于年度提交)。有没有其他替代方法可以做到这一点。
答案 0 :(得分:0)
如果使用OR
,则总是需要括号例如:
Select t2.employee_id,t2.adddate,t2.previousaleave
from table2 as t2
Inner join table1 as t1 ON ............. ?????
WHERE (t1.enddate IS NULL OR t1.enddate>t2.adddate AND t2.adddate<=now())
AND t2.leavetype='annualleave'
但也请注意您似乎没有加入表格。始终使用显式ANSI连接语法,以避免从表中创建行的意外笛卡尔积。
如果两个表中都存在empid,请尝试
Select t2.employee_id,t2.adddate,t2.previousaleave
from table2 as t2
Inner join table1 as t1 ON t2.empid = t1.empid
WHERE (t1.enddate IS NULL OR t1.enddate>t2.adddate AND t2.adddate<=now())
AND t2.leavetype='annualleave'
答案 1 :(得分:0)
SELECT t2.employee_id, t2.adddate, t2.previousaleave
FROM table2 AS t2
INNER JOIN table1 as t1
ON (
( t1.enddate IS NULL OR t1.enddate > t2.adddate )
AND t2.adddate <= now()
AND t2.leavetype = 'annualleave'
)
t2.adddate
可能是> now()
吗?这看起来很尴尬。