仅显示日期是否少于14天前

时间:2012-12-21 15:59:56

标签: mysql

我有三张桌子 - 通知,notices_read和公司。通知包含显示在Web应用程序中的客户通知列表,而notices_read是他们点击并阅读消息的指示符,因此在公司保存公司信息(包括其加入日期)时不再显示该消息。此外,我只希望向超过14天前加入的客户显示通知。

一切都在14天前的部分工作 - 如果我删除该行,通知显示正确,取决于notices_read中是否有值,但如果我在那时添加日期行,虽然没有错误,但没有返回任何内容。

companies
+-----------------+
| id | datestamp  |
+-----------------+
| 1  | 2012-12-20 |
| 2  | 2012-12-20 |
| 3  | 2012-11-20 |
| 4  | 2012-11-20 |
+-----------------+

notices_read
+-----------------------------+
| id | company_id | notice_id |
+-----------------------------+
| 1  | 3          | 1         |
+-----------------------------+

notices
+----------------------+
| id | title  | active |
+----------------------+
| 1  | title1 | 1      |
| 2  | title2 | 0      |
+----------------------+
  • 通知2应该永远不会显示,因为它未设置为活动
  • 通知1不应向公司1或2显示,因为它们不是14天
  • 通知1不应向公司3显示,因为它已被阅读
  • 通知1应显示给公司4,因为它尚未被阅读且公司4超过14天

这是我的问题:

Select
  notices.description,
  notices.id,
  notices.title,
  notices_read.company_id,
  companies.datestamp
From
  notices Left Join
  notices_read On notices.id = notices_read.dismiss_id Left Join
  companies On notices_read.company_id = companies.id
Where
  notices.active = 1 And
  companies.datestamp <= DATE_SUB(SYSDATE(), Interval 14 Day) And
  (notices_read.company_id Is Null Or notices_read.company_id != '$company_id')

1 个答案:

答案 0 :(得分:3)

如果我理解您的问题,您只需要使用DATE_SUB

DATE_SUB(SYSDATE(), Interval 14 Day)

完整查询将是:

Select
  notices.description,
  notices.id,
  notices.title,
  notices_read.company_id,
  companies.datestamp
From
  notices_read Left Join
  notices On notices_read.dismiss_id = notices.id Left Join
  companies On notices_read.company_id = companies.id
Where
  notices.active = 1 And
  companies.datestamp <= DATE_SUB(SYSDATE(), Interval 14 Day) And
  (notices_read.company_id Is Null Or notices_read.company_id != '$company_id')