Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql - selecting year from a unix timestamp

I am using this:

SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year FROM table_name WHERE year = 2009;

but it gives me an error:

Unknown column 'year' in 'where clause'SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year FROM table_name WHERE year = 2009

Both "my_unix_timestamp_column" and "table_name" are correct, i dont know why it gives me this!!!

I'm using PHP 5.3.0

like image 880
Sam Avatar asked Nov 10 '09 15:11

Sam


People also ask

How do I get epoch in MySQL?

MySQL - UNIX_TIMESTAMP() Function Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time.

Which function returns the Unix timestamp for a date?

unix_timestamp is an internal timestamp value representing seconds since '1970-01-01 00:00:00' UTC, such as produced by the UNIX_TIMESTAMP() function. If format is omitted, this function returns a DATETIME value. If unix_timestamp or format is NULL , this function returns NULL .

How do I read a Unix timestamp?

To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.

How does MySQL store epoch time?

You want to use the TIMESTAMP data type. It's stored as an epoch value, but MySQL displays the value as 'YYYY-MM-DD HH:MM:SS'. Show activity on this post. MySql DateTime data type store the date in format 'YYYY-MM-DD HH:MM:SS' with range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.


2 Answers

I'm not quite sure whether this is due to YEAR being a reserved word in MySQL or because it wants you to do something along the lines of:

SELECT
  FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year
FROM
  table_name
WHERE
  FROM_UNIXTIME(my_unix_timestamp_column, '%Y') = 2009;

Can't remember whether the last issue is only relevant to GROUPings :S

like image 116
jensgram Avatar answered Sep 30 '22 11:09

jensgram


SELECT  FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS `year`
FROM    table_name
HAVING  `year` = 2009

Unlike WHERE clause, HAVING clause can reference the SELECT clause aliases.

More index efficient way would be:

SELECT  FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS `year`
FROM    table_name
WHERE   my_unix_timestamp_column >= UNIX_TIMESTAMP('2009-01-01')
        AND my_unix_timestamp_column < UNIX_TIMESTAMP('2010-01-01')
like image 41
Quassnoi Avatar answered Sep 30 '22 09:09

Quassnoi