简体   繁体   English

MySQL日期列弄乱了

[英]mySQL date column is messed up

I've made a table: 我做了一张桌子:

+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| date    | date         | NO   |     | NULL    |                |
| user_id | int(8)       | YES  |     | NULL    |                |
| isbn    | varchar(13)  | NO   |     | NULL    |                |
| price   | decimal(6,2) | NO   |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+

And, the date colomn isn't working. 而且,日期列不起作用。 I figured I need to modify the table to default to "CURDATE()". 我认为我需要将表修改为默认为“ CURDATE()”。 That's what I've got from googling. 这就是我从谷歌搜索中获得的东西。 I'm not even sure if that's the problem, but my alter statement isn't work. 我什至不确定这是否是问题,但是我的alter语句不起作用。

I'm trying to alter with this: 我正在尝试与此:

mysql> ALTER TABLE buybacks MODIFY date date not null default curdate();

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'curdate()' at line 1

Can someone help? 有人可以帮忙吗?

It's generally not a good idea to have column (or table) names that are MySQL reserved words. 具有作为MySQL保留字的列(或表)名称通常不是一个好主意。 If you must do this, then use backticks (`) around the name 如果必须这样做,请在名称周围使用反引号(`)

ALTER TABLE buybacks MODIFY `date` date not null default curdate();

EDIT 编辑

However, you can't set a date column to a default of curdate() See this reference from the MySQL buglist for details 但是,您不能将日期列设置为默认的curdate()。有关详细信息,请参见MySQL错误列表中的此参考。

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column. 唯一的例外是您可以将CURRENT_TIMESTAMP指定为TIMESTAMP列的默认值。 This might be a viable alternative to give you that default 这可能是给您默认值的可行选择

EDIT 2 编辑2

Another alternative would be a trigger: 另一种选择是触发:

CREATE TRIGGER buybacks_insert BEFORE INSERT ON `buybacks`
   FOR EACH ROW 
       SET NEW.`date` = CURDATE();

But watch out that you update a trigger when you do change the name of the date column 但是请注意,当您更改日期列的名称时,您将更新触发器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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