MySQL SELECT如果没有更新的记录

时间:2017-12-16 07:39:14

标签: mysql select where

我正试图从即将到期的MySQL中提取合同。我用以下陈述做了哪些:

SELECT 
    c.id, c.file, c.user, c.contractno, c.startdate, c.enddate, f.name, f.path 
FROM signedcontracts c 
LEFT JOIN files f ON c.file = f.id 
    WHERE c.enddate < NOW() + INTERVAL 30 DAY 
    AND c.enddate > NOW() 
ORDER BY c.enddate ASC

但我无法弄清楚如何确保它不会为已经在signedcontracts签订新合同的用户返回任何合同。

2 个答案:

答案 0 :(得分:1)

也许您只需检查现在+ 30天后没有结束日期

MariaDB [sandbox]> select * from t;
+------+------------+------------+
| id   | start_date | end_date   |
+------+------------+------------+
|    1 | 2017-10-01 | 2017-10-31 |
|    1 | 2017-12-01 | 2017-12-31 |
|    2 | 2017-10-01 | 2017-12-31 |
|    2 | 2018-10-01 | 2018-10-31 |
|    3 | 2018-10-01 | 2018-10-31 |
|    4 | 2017-10-01 | 2018-10-31 |
+------+------------+------------+
6 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]>
MariaDB [sandbox]> select *
    -> from t
    -> where end_date between now()  and now() + interval 30 day
    -> and id not in (select id from t where end_date > now() + interval 30 day);
+------+------------+------------+
| id   | start_date | end_date   |
+------+------------+------------+
|    1 | 2017-12-01 | 2017-12-31 |
+------+------------+------------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

我使用了这个查询:

SELECT 
    c.id, c.file, c.user, c.contractno, c.startdate, c.enddate, f.name, f.path 
FROM signedcontracts c 
LEFT JOIN files f ON c.file = f.id 
    WHERE c.enddate < NOW() + INTERVAL 30 DAY 
    AND c.enddate > NOW()
    AND c.user NOT IN (SELECT user FROM signedcontracts WHERE enddate > NOW() + INTERVAL 30 DAY)
ORDER BY c.enddate ASC

enddate

之前检查用户是否签订了超过30天的合同