반응형

입력 날짜를 자동으로 입력되게 하기 위해서 TIMESTAMP 를 사용 했습니다.
그런데 날짜 필드를 수정 하지 않더라도, 다른 정보를 수정하게 되면 같이 변경 되어 버리네요.
필드가 regidate 인데 속성을 TIMESTAMP 로 잡혀 있습니다.
최초 입력시만 자동 등록되고, 수정하더라도 바뀌지 않게 하려면 어떻게 해야 하는지요?

mssql만 주로 하다보니, 몰랐던 부분이라 당황 스럽네요 ㅠㅠ

 

자답 입니다.
기본값을 current_timestamp  로 변경 하니 되네요.
기본값이 CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 로 되어 있더군요.

 

1. ALTER TABLE `invoices`.`invoices`
    CHANGE
`DateTime` `DateTime` TIMESTAMP NOT NULL DEFAULT 0;

2. ALTER TABLE `invoices`.`invoices`
    CHANGE
`DateTime` `DateTime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

 

 

alter table IPS modify time2 timestamp default current_timestamp;

반응형
반응형

출처: http://ra2kstar.tistory.com/97

http://develop.sunshiny.co.kr/385

 

 

## 각각의 캐릭터 셋을 변경 - 이 변경 방법은 mysql 데몬이 재실행 될경우에 초기화 됨.
mysql> SET character_set_client = utf8;
mysql> SET character_set_results = utf8;
mysql> SET character_set_connection = utf8;
mysql> ALTER DATABASE DB명 DEFAULT CHARACTER SET utf8;
commit;

 

MySQL 기본 패키지는 character set 이 latin1로 설정되어 있다. 따라서 서버에 따라서 세팅을 바꿔줘야 할 필요가 있다. 


나같은 경우에는 UTF-8로 통일하였다. 


우선 현재 mysql의 설정값을 확인해 보자 

 

mysql> show variables like 'c%';

+--------------------------+----------------------------+

| Variable_name         |    | Value                      |

+--------------------------+----------------------------+

| character_set_client      | latin1                     |

| character_set_connection | latin1                     |

| character_set_database   | latin1                     |

| character_set_filesystem | binary                     |

| character_set_results    | latin1                     |

| character_set_server     | latin1                     |

| character_set_system     | utf8                       |

| character_sets_dir       | /usr/share/mysql/charsets/ |

| collation_connection     | latin1_swedish_ci          |

| collation_database       | latin1_swedish_ci          |

| collation_server         | latin1_swedish_ci          |

| completion_type          | 0                          |

| concurrent_insert        | 1                          |

| connect_timeout          | 10                         |

+--------------------------+----------------------------+

14 rows in set (0.02 sec)


역시 latin1으로 되어있다. 


명령어를 통해서도 mysql을 사용할때 변경 할 수 있지만, 이렇게 되면 데몬이 재실행 될때마다 다시 latin1으로 돌아간다. 따라서 고정적으로 바꿔주자. 



  기본 케릭터 셋들을 원하는 값으로 변경 ( UTF-8 로 변경하였다 ) 


$ vi /etc/my.cnf


[mysql]

 

default-character-set = utf8


[mysqld]

character-set-client-handshake=FALSE

init_connect="SET collation_connection = utf8_general_ci"

init_connect="SET NAMES utf8"

default-character-set = utf8

character-set-server = utf8

collation-server = utf8_general_ci


datadir=/var/lib/mysql

socket=/var/lib/mysql/mysql.sock

user=mysql

# Disabling symbolic-links is recommended to prevent assorted security risks

symbolic-links=0


[client]

default-character-set = utf8


[mysqldump]

default-character-set = utf8


[mysqld_safe]

log-error=/var/log/mysqld.log

pid-file=/var/run/mysqld/mysqld.pid



그리고 재시작 
$ service mysqld restart 
Stopping MySQL: [ OK ] 
Starting MySQL: [ OK ] 

이제 최종적으로 status를 통해 서버와 mysql의 인코딩이 통일 되었는지 확인해보자 .

mysql> status
--------------
mysql  Ver 14.14 Distrib 5.1.61, for redhat-linux-gnu (x86_64) using readline 5.1

Connection id:          8
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         5.1.61 Source distribution
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /var/lib/mysql/mysql.sock
Uptime:                 27 min 16 sec

Threads: 1  Questions: 52  Slow queries: 0  Opens: 23  Flush tables: 1  Open tables: 11  Queries per second avg: 0.31
--------------

mysql> show variables like 'c%' ;



반응형
반응형

mysql> SELECT something FROM table
WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 7;

 

 

 

 

반응형
반응형
http://www.epochconverter.com/programming/mysql-from-unixtime.php

 

 

 

그림1

그림1은 unix time을 나타낸다

 

그림2는 Epoch 시간을 나타내며

unix_timestamp() 함수를 써주면 변환이 된다.

 

 

Quick summary

Get current epoch time SELECT UNIX_TIMESTAMP(NOW()) (now() is optional)
Today midnight SELECT UNIX_TIMESTAMP(CURDATE())
Yesterday midnight SELECT UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -1 DAY))
Convert from date to epoch SELECT UNIX_TIMESTAMP(timestring)
Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD
Convert from epoch to date SELECT FROM_UNIXTIME(epoch timestamp, optional output format)
The default output is YYYY-MM-DD HH:MM:SS
FROM_UNIXTIME doesn't work with negative timestamps

 

The Mini-Course

Let's first create a simple logging-table and some sample records.
All queries on this page will work with the following table.

  • -- Table "mytable" DDL
  •  
  • CREATE TABLE `mytable` (
  • `userId` int(11) NOT NULL,
  • `url` varchar(100) NOT NULL,
  • `epoch` int(11) NOT NULL
  • );
  •  
  • INSERT INTO mytable VALUES(1,'homepage',1225540800);
  • # User 1 visited the url homepage on Nov 1, 2008
  • INSERT INTO mytable VALUES(2,'contact',1225886400);
  • # User 2 visited the url contact on Nov 5, 2008
  • INSERT INTO mytable VALUES(3,'contact',1225972800);
  • # User 3 visited the url contact on Nov 6, 2008
  • INSERT INTO mytable VALUES(4,'homepage',1228132800);
  • # User 4 visited the url homepage on Dec 1, 2008

Converting to readable dates

  • SELECT userId, url, FROM_UNIXTIME(epoch) FROM mytable

This query outputs:

1   homepage   2008-11-01 13:00:00
2   contact   2008-11-05 13:00:00
3   contact   2008-11-06 13:00:00
4   homepage   2008-12-01 13:00:00

You can format your date by using specifiers (look below for a list of specifiers).

  • SELECT userId, url, FROM_UNIXTIME(epoch,"%Y-%m-%d") FROM mytable

Output:

1   homepage   2008-11-01
2   contact   2008-11-05
3   contact   2008-11-06
4   homepage   2008-12-01

Grouping Epochs

Let's say you want to get statistics by month. This query groups months, and counts the number of visitor (records) in each month. We order by epoch to get all results in the right order.

  • SELECT DISTINCT FROM_UNIXTIME(epoch,"%M, %Y") AS month, count(*) as numberOfVisits
  • FROM mytable
  • GROUP BY month
  • ORDER BY epoch

This outputs:

November, 2008   3
December, 2008   1

This query can be easily changed to get statistics per year, per day, per day of the week, per hour of the day etc. For example, to get yearly stats change the query to:

  • SELECT DISTINCT FROM_UNIXTIME(epoch,"%Y") AS year, count(*) as numberOfVisits
  • FROM mytable
  • GROUP BY year
  • ORDER BY epoch

Adding a new record to our database

Use the UNIX_TIMESTAMP() function to convert MySQL dates/times (such as now() = current time) to epochs.

  • INSERT INTO mytable VALUES(1,'pagename',UNIX_TIMESTAMP(now()))

or use YYYY-MM-DD HH:MM:SS :

  • INSERT INTO mytable VALUES(1,'pagename',UNIX_TIMESTAMP('2008-12-01 12:00:00'))

Negative Epochs

There's one big problem with MySQL: MySQL cannot convert negative epoch timestamps (dates before 1-1-1970). This creates problems with for example birthdates. But there are workarounds.

When converting from epoch to human readable date use the DATE_ADD function:

  • # converting to MySQL date:
  • SELECT DATE_ADD(FROM_UNIXTIME(0), interval -315619200 second);
  • # converting your epoch to a date string:
  • SELECT DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), interval -315619200 second),'%Y-%m-%d');

Where -315619200 is your negative epoch. This query returns: 1960-01-01 01:00:00

When converting normal dates to epoch use TIMESTAMPDIFF:

  • SELECT TIMESTAMPDIFF(second,FROM_UNIXTIME(0),'1960-01-01 00:00:00' );

Replace the 1960 date with your date in your local timezone (MySQL time_zone).

MySQL date format specifiers

Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal '%' character

 

반응형

+ Recent posts