SQL Query用于选择其他行不等于值的位置

时间:2014-04-02 09:41:07

标签: mysql sql

我正在尝试运行此查询:

SELECT arg2 as r 
FROM voipwallboard_ast_queue_log 
WHERE queuename = '0536*401'
      AND time > '2014-04-02 10:30:00'
      AND event = 'CONNECT'

但其他具有相同callid(列名称)的行也没有CONNECTABANDONRINGNOANSWER

的事件。

例如,我有这些行:

callid  queuename    time                 event          arg2
1234    0536*401    2014-04-02 10:30:00   ENTERQUEUE     0192837465
1234    0536*401    2014-04-02 10:30:00   CONNECT
1234    0536*401    2014-04-02 10:30:00   RINGNOANSWER

因此,因为包含事件CONNECTRINGNOANSWER的行与callid相同,arg2不应显示,但如果后两行不存在它会显示arg2

2 个答案:

答案 0 :(得分:0)

你需要将表加入到自身中。尝试:

SELECT arg2 as r FROM voipwallboard_ast_queue_log v1
    WHERE queuename = '0536*401'
    AND time > '2014-04-02 10:30:00'
    AND event = 'CONNECT'
    AND NOT EXISTS (SELECT 1 FROM voipwallboard_ast_queue_log v2
                    WHERE v1.CallID = v2.CallID
                    AND v2.event in ('CONNECT','ABANDON ','RINGNOANSWER')
                    )

答案 1 :(得分:0)

这是您查询的可读版本:

SELECT arg2 as r 
FROM voipwallboard_ast_queue_log 
WHERE queuename = '0536*401'
      AND time > '2014-04-02 10:30:00'
      AND callid NOT IN ( select callid 
                          from voipwallboard_ast_queue_log
                          where event not in ( 'CONNECT', 'ABANDON', 
                                               'RINGNOANSWER' )
                         )

但是性能不是最好的,因为它会检查每一行的子查询。

为了提高性能,您应该将连接表保留为自己:

SELECT l.arg2 as r 
FROM voipwallboard_ast_queue_log l left outer join
    ( select callid 
                          from voipwallboard_ast_queue_log
                          where event not in ( 'CONNECT', 'ABANDON', 
                                               'RINGNOANSWER' )
                         )  T
       on l.callid = T.callid
WHERE l.queuename = '0536*401'
      AND l.time > '2014-04-02 10:30:00'
      AND t.callid is null