Mysql:如何知道日期字段的值(审计表)

时间:2014-07-25 10:13:31

标签: mysql sql

我有一个表与CONT_out字段联系。

字段opt_out可能包含值' Y' N' N'和NULL。

我有一个表CONTACT_AUDIT,其中包含字段

date
contact_id
field_name
value_before
value_after

当我添加新联系人时,CONTACT表中会添加一个新行,而不是CONTACT_AUDIT表。

当我编辑联系人时,例如,如果我将opt_out字段值从NULL更改为' Y',则会更改CONTACT表中的opt_out字段值,并使用值将新行添加到CONTACT_AUDIT表中

date=NOW()
contact_id=<my contact's id>
field_name='opt_out'
value_before=NULL
value_after='Y'

我需要知道有opt_out =&#39; Y&#39;在给定的日期。

我试过了:

SELECT count(*) AS nb
FROM contacts c
WHERE
( -- contact is optout now and has never been modified before
    c.optout = 'Y'
    AND c.id NOT IN (SELECT DISTINCT contact_id FROM contacts_audit WHERE field_name =     'optout')
)
OR ( -- we consider contacts where the last row before date in contacts_audit is     optout = 'Y'
    c.id IN (
      SELECT ca.contact_id
      FROM contacts_audit ca
      WHERE date_created BETWEEN '2014-07-24' AND DATE_ADD( '2014-07-24', INTERVAL 1 DAY )
      AND field_name = 'optout'
      ORDER BY date_created
      LIMIT 1
    )
)

但是mysql在子查询中不支持LIMIT。

所以我尝试了HAVING:

SELECT count(*) AS nb
FROM contacts c
WHERE
( -- contact is optout now and has never been modified before
    c.optout = 'Y'
    AND c.id NOT IN (SELECT DISTINCT contact_id FROM contacts_audit WHERE field_name =     'optout')
)
OR ( -- we consider contacts where the last row before date in contacts_audit is     optout = 'Y'
    c.id IN (
      SELECT ca.contact_id
      FROM contacts_audit ca
      WHERE date_created BETWEEN '2014-07-24' AND DATE_ADD( '2014-07-24', INTERVAL 1 DAY )
      AND field_name = 'optout'
      HAVING MAX(date_created)
    )
)

查询运行,但现在,我不知道如何知道子查询值对应的值是否为&#39; Y&#39;或者&#39; N&#39;如果我添加一个WHERE子句来仅检查&#39; Y&#39;价值观,&#39; N&#39;价值将被过滤,我将无法知道日期的最后一个值是否为&#39; Y&#39;或者&#39; N&#39; ...

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你可能想要使用联盟。我现在没有mysql来测试它,但代码可能是这样的。告诉我这是否有帮助

select c.id, c.optout 
where c.optout = 'Y'
AND c.id NOT IN (SELECT DISTINCT contact_id FROM contacts_audit WHERE field_name =          'optout')
UNION
select c.id, c.optout where c.id IN (
  SELECT ca.contact_id
  FROM contacts_audit ca
  WHERE date_created BETWEEN '2014-07-24' AND DATE_ADD( '2014-07-24', INTERVAL 1 DAY )
  AND field_name = 'optout'
  HAVING MAX(date_created)
)