如何使用 SQL 更新日期記錄列值,並設定當前日期之前的相應記錄為 1


假設當前日期是 2019-08-20。現在,對於我們的示例,我們將建立一個表 -

mysql> create table DemoTable
(
   ProductStatus tinyint(1),
   ProductExpiryDate date
);
Query OK, 0 rows affected (1.03 sec)

使用插入命令在表中插入一些記錄 -

mysql> insert into DemoTable values(0,'2019-06-12');
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable values(0,'2019-10-11');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable values(0,'2018-07-24');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(0,'2018-09-05');
Query OK, 1 row affected (0.27 sec)

使用選擇語句從表中顯示所有記錄 -

mysql> select *from DemoTable;

這會產生以下輸出 -

+---------------+-------------------+
| ProductStatus | ProductExpiryDate |
+---------------+-------------------+
| 0             | 2019-06-12        |
| 0             | 2019-10-11        |
| 0             | 2018-07-24        |
| 0             | 2018-09-05        |
+---------------+-------------------+
4 rows in set (0.00 sec)

以下是為當前日期之前的記錄設定值 1 的查詢

mysql> update DemoTable
   set ProductStatus=1
   where ProductExpiryDate <=CURDATE();
Query OK, 3 rows affected (0.95 sec)
Rows matched : 3 Changed : 3 Warnings : 0

讓我們再次檢查表記錄 -

mysql> select *from DemoTable;

這會產生以下輸出 -

+---------------+-------------------+
| ProductStatus | ProductExpiryDate |
+---------------+-------------------+
| 1             | 2019-06-12        |
| 0             | 2019-10-11        |
| 1             | 2018-07-24        |
| 1             | 2018-09-05        |
+---------------+-------------------+
4 rows in set (0.00 sec)

更新日期: 07-Oct-2019

259 圍觀

Kickstart Your Career

完成課程獲得認證

開始吧
廣告