How to create mysql table with column timestamp de

2020-05-27 05:04发布

I need to create mysql table with default value on column CURRENT_DATE()

I try

DROP TABLE IF EXISTS `visitors`;
CREATE TABLE `visitors` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` VARCHAR(32) NOT NULL,
  `browser` VARCHAR(500) NOT NULL,
  `version` VARCHAR(500) NOT NULL,
  `platform` ENUM('w','l','m') NOT NULL,
  `date` TIMESTAMP NOT NULL DEFAULT CURRENT_DATE(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

but it is writting an error

Query: CREATE TABLE `visitors` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `ip` VARCHAR(32) NOT NULL, `browser` VARCHAR(500) NO...

Error Code: 1064
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 'CURRENT_DATE() NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1' at line 7

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0.063 sec

what is the problem?

I need to uniques only date not with full time info...

can you help me?

3条回答
Deceive 欺骗
2楼-- · 2020-05-27 05:06

Use CURRENT_TIMESTAMP function instead of CURRENT_DATE() function

Try this:

DROP TABLE IF EXISTS `visitors`;
CREATE TABLE `visitors` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` VARCHAR(32) NOT NULL,
  `browser` VARCHAR(500) NOT NULL,
  `version` VARCHAR(500) NOT NULL,
  `platform` ENUM('w','l','m') NOT NULL,
  `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
查看更多
▲ chillily
3楼-- · 2020-05-27 05:10

This may be a little late but I think it might be helpful to someone else.

My approach has been to use getdate() like this:

[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_myTable_TimeStamp] DEFAULT (getdate()).

Where [TimeStamp] is the column in question.

The result is for example: 2017-11-02 11:58:34.203

To trim this, I use the following

declare @mydate datetime

set @mydate = '2017-11-02 11:58:34.203'

SELECT try_convert(nvarchar(20), @mydate, 120)

This final result is: 2017-11-02 11:58:34

You can actually set this in MSSQL Management Studio

查看更多
女痞
4楼-- · 2020-05-27 05:20

you just have to replace CURRENT_DATE() by NOW() in your query. I tried it and it's look ok.

查看更多
登录 后发表回答