简体   繁体   中英

Only show if date is less than 14 days ago

I have three tables - notices, notices_read and companies. Notices contains a list of notices for clients which are displayed in a web app and notices_read is an indicator that they have clicked and read the message so it is not shown again whilst companies holds the company info including their join date. Additionally, I only want the notice to be shown to clients who joined more than 14 days ago.

Everything works bar the 14 day ago part - if I remove that line the notice shows correctly depending on whether there is a value in notices_read but if I add the date line in then, whilst there is no error, nothing is returned.

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      |
+----------------------+
  • Notice 2 should never show as it is not set to active
  • Notice 1 should not show to company 1 or 2 as they are not 14 days old
  • Notice 1 should not show to company 3 as it has already been read
  • Notice 1 should show to company 4 as it has not been read and company 4 is older than 14 days

Here is my query:

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')

If I understood your problem correctly, you only need to use DATE_SUB

DATE_SUB(SYSDATE(), Interval 14 Day)

The full query would be:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM