mysql query - insert data unix_timestamp ( now ( )

2019-02-18 15:04发布

问题:

I have an INT (11) column for storing the current timestamp in seconds. The query looks like:

INSERT INTO `abc` (id, timestamp) VALUES ('', UNIX_TIMESTAMP ( NOW () ) )

I don't know why, but the date isn't changed. It doesn't matter when I send the query, the column value isn't changed. It has 1342692014 value, but I don't know why.

Is there any option or other function for timestamps? I must store dates in seconds.

回答1:

You never refer to the timestamp column in your query. You only have a string:

INSERT INTO `abc` (id, 'timestamp') VALUES ('', UNIX_TIMESTAMP ( NOW () ) )
                       ^^^^^^^^^^^

Edit:

I get this with your updated code:

ERROR 1630 (42000): FUNCTION test.NOW does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual

Assuming it's not still the actual code and after fixing the syntax error, I can't reproduce your results. My educated guess is that id is an auto-incremented integer primary key, your current SQL mode is making MySQL take '' as NULL and inserting a new row... But I haven't really tested this hypothesis.

My working code is this:

CREATE TABLE `abc` (
    `pk` INT(10) NOT NULL AUTO_INCREMENT,
    `id` VARCHAR(10) NULL DEFAULT NULL,
    `timestamp` INT(11) NOT NULL DEFAULT '0',
    PRIMARY KEY (`pk`)
)
ENGINE=InnoDB;

INSERT INTO abc (id, timestamp) VALUES ('', UNIX_TIMESTAMP());
-- Wait a few seconds
INSERT INTO abc (id, timestamp) VALUES ('', UNIX_TIMESTAMP());
-- Wait a few seconds
INSERT INTO abc (id, timestamp) VALUES ('', UNIX_TIMESTAMP());

SELECT timestamp FROM abc WHERE id='';

... and returns this:

+------------+
| timestamp  |
+------------+
| 1342694445 |
| 1342694448 |
| 1342694450 |
+------------+
3 rows in set (0.00 sec)