Mysql 如果id不在另一个表中,则根据使用sql的条件计算id的编号
我有一张由RepId和它的日期组成的表Mysql 如果id不在另一个表中,则根据使用sql的条件计算id的编号,mysql,sql,sql-server-2008,exists,Mysql,Sql,Sql Server 2008,Exists,我有一张由RepId和它的日期组成的表 Table: 1 RepID Date 108981 2013-04-09 00:00:00.000 108981 2013-04-09 00:00:00.000 108982 2013-04-10 00:00:00.000 108982 2013-04-11 00:00:00.000 108983 2013-04-11 00:00:00.000 108983 2013-04-11 00:00:00.000 我有另一张表,包括RepId和
Table: 1
RepID Date
108981 2013-04-09 00:00:00.000
108981 2013-04-09 00:00:00.000
108982 2013-04-10 00:00:00.000
108982 2013-04-11 00:00:00.000
108983 2013-04-11 00:00:00.000
108983 2013-04-11 00:00:00.000
我有另一张表,包括RepId和他们的logTime
Table: 2
repID logTime
108981 2013-04-09 00:00:00.000
108981 2013-04-09 00:00:00.000
108982 2013-04-11 00:00:00.000
108983 2013-04-11 00:00:00.000
108983 2013-04-11 00:00:00.000
108984 2013-04-10 00:00:00.000
我想要表1中的RepId计数,当表2中的rep的logtime不存在时
在这种情况下,我需要输出为
repId RepCount
108982 1
由于RepId-108982的表2中不存在日期“2013-04-10 00:00:00.000”
我已将该查询用作
select
t1.RepID, count(t1.RepID) as 'Rep Count'
from
table1 t1
where
not exists
(select t2.repID from table2 t2 where
CONVERT(date, t2.logTime) between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000')
group by
t1.RepID
但它总是一无所获。请帮助解决此问题。…您可以在此处使用左外部联接
SELECT
t1.repID, COUNT(t1.repID)
FROM
table1 t1
LEFT OUTER JOIN
table2 t2
ON
t1.repID = t2.repID
AND
t1.Date = t2.logTime
WHERE
t2.repID IS NULL
GROUP BY
t1.repID
我想你应该用
而不是来表达:
select t1.RepID, count(t1.RepID) as 'Rep Count'
from table1 t1
where t1.repid not in (select t2.repID
from table2 t2
where CONVERT(date, t2.logTime) between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000'
)
group by t1.RepID
或者使用相关子查询或左外部联接
查询的问题是,您正在查找该期间是否存在(或缺少)任何记录,并且必须存在一条记录。您确实想查找给定repId的记录。问题在于您没有将notexists中的子查询与外部查询关联,因此notexists子句总是返回false。试着这样做:
select
t1.RepID, count(t1.RepID) as 'Rep Count'
from
table1 t1
where
not exists
(select t2.repID from table2 t2 where t2.repId = t1.repId and
CONVERT(date, t2.logTime) between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000')
group by
t1.RepID
之间的将涵盖给定的开始日期和结束日期,如表2所示,日志时间将处于中间状态,这就是您无法获得任何记录的原因
您应该在
查看此演示,SQLFiddle演示
要么使用>而不使用主键?这两个表都有重复的行。
select
t1.RepID, count(t1.RepID) as 'Rep Count'
from
table1 t1
where
not exists
(select * from table2 t2 where
t2.RepID = t1.RepID and t2.LogTime = t1.Date)
group by
t1.RepID
select
t1.RepID, count(t1.RepID) as 'Rep Count'
from
table1 t1
where t1.RepID
not in
(select t2.repID from table2 t2 where
t2.logTime > '2013-04-08 00:00:00.000' and t2.logTime < '2013-04-11 00:00:00.000')
group by
t1.RepID
108982, '2013-04-11 01:00:00.000'
select
t1.RepID, count(t1.RepID) as 'Rep Count'
from
table1 t1
where t1.RepID
not in
(select t2.repID from table2 t2 where
t2.logTime between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000')
group by
t1.RepID