MySQL - 如何让所有在过去两小时内没有被呼叫的客户

时间:2016-07-26 18:16:58

标签: mysql sql join foreign-keys foreign-key-relationship

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

客户有两个字段: id name

致电的字段为:

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

还有一些客户尚未被召集。可以多次调用客户。

如何查询所有在过去两小时内未被呼叫的客户?

SQL摆弄架构和一些最小数据:http://sqlfiddle.com/#!9/5c80f/1(请记住,SQL Fiddle Server可能位于与您不同的时区!)

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我们需要检查一个人上次接听电话的时间。这是更新的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

答案 2 :(得分:0)

您可以将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。不需要混淆。