MySQL - 如何获取过去两个小时内未被呼叫的所有客户

MySQL - How to get all Customers who haven't been called in the last two hours

在我的 MySQL-db 中,我有两个表 customercall

Customer 有两个字段:idname.

Call 具有以下字段:

id 
customer (NOT NULL FK)
dateOfCall (NOT NULL DATE)
timeOfCall (NOT NULL TIME).

还有一些客户还没有被调用。一个客户可以被多次调用。

我如何进行查询以获取过去两个小时内未接到电话的所有客户?

SQL Fiddle 模式和一些最小数据:http://sqlfiddle.com/#!9/5c80f/1(请记住 SQL Fiddle 服务器可能在另一个时区比你还厉害!)

SELECT * FROM customer 
WHERE id NOT IN (
    SELECT DISTINCT customer FROM `call` 
    WHERE timeOfCall NOT BETWEEN 
    SUBTIME(curtime() , '02:00:00') AND curtime());

我们需要核对某人上次接到电话的时间。这是更新后的 sql。

Select 
    cust.* 
from 
    `customer` cust 
left join 
(
    select
    customer
    from `call` cl 
    group by customer
    having 
    max(STR_TO_DATE(CONCAT(cl.dateOfCall, ' ', cl.timeOfCall), '%Y-%m-%d %H:%i:%s')) >= date_sub(NOW(), interval 2 hour)
) aa on cust.id = aa.customer
where aa.customer is null

您可以将 date_sub 与左外连接一起使用:

SELECT * 
FROM `customer` as cu
LEFT OUTER JOIN 
(
SELECT * FROM `call` WHERE 
 call.dateOfCall >= DATE_FORMAT(DATE_SUB(CURTIME(), INTERVAL 2 HOUR),'%Y-%m-%d') 
 AND
 ( call.timeOfCall > DATE_SUB(CURTIME(), INTERVAL 2 HOUR ) )
) as ca
  ON (ca.customer = cu.id)
  WHERE ca.customer IS NULL;

fiddle

编辑:将 date_add 替换为 date_sub。无需混淆。