在MySQL表中显示另一行不存在的行

时间:2014-03-07 18:20:30

标签: php mysql sql

我的MySQL数据库中有一个表,其中包含以下列:

  • CallId的
  • 事件

我想选择事件为'ENTERQUEUE'的所有行:

SELECT count(*) AS avg_hold_time
FROM ast_queue_log
WHERE queuename = '0536*401'
  AND DATE(time) = '2014-03-07'
  AND event = 'ENTERQUEUE'
ORDER BY time DESC;

但是我要显示所有其他行,其中'callid'等于上述查询的结果(对于上面查询中返回的每一行) AND 没有行所在的行事件等于'CONNECT'。

2 个答案:

答案 0 :(得分:1)

您可以将子查询与NOT EXISTS运算符一起使用:

SELECT   AVG(arg1) AS avg_hold_time 
FROM     ast_queue_log aql
WHERE    queuename = '0536*401' AND
         DATE(time) = '2014-03-07' AND
         event = 'ENTERQUEUE' AND
         NOT EXISTS (SELECT cnt.callid
                     FROM   ast_queueu_log cnt
                     WHERE  -- Same conditions as the surrounding query
                            queuename = '0536*401' AND
                            DATE(time) = '2014-03-07' AND
                            event = 'CONNECT' AND
                            -- matching callids
                            cnt.callid = aql.callid)
ORDER BY time DESC

答案 1 :(得分:1)

这通常通过反连接形式的自联接来解决:

SELECT avg(aql1.arg1) AS avg_hold_time
FROM ast_queue_log aql1
// Left outer join on other records with 'CONNECT' event for same callid
LEFT JOIN ast_queue_log aql2
ON aql1.callid = aql2.callid AND aql2.event = 'CONNECT'
WHERE aql1.queuename = '0536*401'
  AND DATE(aql1.time) = '2014-03-07'
  AND aql1.event = 'ENTERQUEUE'
  // Then only include those records that didn't successfully join
  AND aql2.callid IS NULL
ORDER BY aql1.time DESC;

也许您需要在JOIN上抛出一些其他条件,例如具有相同队列名和日期的“CONNECT”事件,但您尚未指定。