比较子查询中的计数

时间:2014-01-14 12:29:42

标签: mysql count compare subquery

是否可以以某种方式比较子查询计数结果:

SELECT
    c_contact.id,
    c_contact.name,
    c_contact.firstnames,
    c_contact.securityid
FROM c_monitoring 
  JOIN c_contact ON c_contact.securityid = c_monitoring.securityid 
  JOIN c_ln_event_debtor ON c_ln_event_debtor.f_contact = c_contact.id 
  JOIN c_event ON c_event.id = c_ln_event_debtor.f_event
WHERE
  ( 
    SELECT count(c_event.id) 
    FROM c_event 
    WHERE c_event.id = c_ln_event_debtor.f_event
    AND c_event.f_status IN(50,51,52)
  ) = (
    SELECT count(c_event.id)
    FROM c_event
    WHERE c_event.id = c_ln_event_debtor.f_event
  )
GROUP BY
    c_monitoring.securityid

我希望只有在所有引用c_event行都有f_status 50或51或52的情况下才能将行设置为结果集。我试过没有运气。

1 个答案:

答案 0 :(得分:2)

我喜欢这种查询的EXISTS子句。在下面我们过滤掉了f_status不是50,51,51的c_events:

SELECT
    c_contact.id,
    c_contact.name,
    c_contact.firstnames,
    c_contact.securityid
FROM c_monitoring 
  JOIN c_contact ON c_contact.securityid = c_monitoring.securityid 
  JOIN c_ln_event_debtor ON c_ln_event_debtor.f_contact = c_contact.id 
  JOIN c_event ON c_event.id = c_ln_event_debtor.f_contact
WHERE NOT EXISTS (
    SELECT 1
        FROM c_event 
        WHERE c_event.id = c_ln_event_debtor.f_event
        AND c_event.f_status NOT IN (50,51,52)
    )

GROUP BY
    c_monitoring.securityid

如果上述内容仍会产生意外结果,那么您可以将EXISTS加入c_ln_event_debtor:

SELECT
            c_contact.id,
            c_contact.name,
            c_contact.firstnames,
            c_contact.securityid
        FROM c_monitoring 
          JOIN c_contact ON c_contact.securityid = c_monitoring.securityid 
          JOIN c_ln_event_debtor ON c_ln_event_debtor.f_contact = c_contact.id 
          JOIN c_event ON c_event.id = c_ln_event_debtor.f_event
        WHERE NOT EXISTS (
            SELECT 1
                FROM 
                c_ln_event_debtor d
                JOIN c_event ce ON ce.id = d.f_event
                WHERE d.f_contact = c_contact.id
                AND ce.f_status NOT IN (50,51,52)
            )

        GROUP BY
            c_monitoring.securityid;

编辑:我注意到c_event上的联接使用c_ln_event_debtor.f_contact这是故意的吗?