사용자 도구

사이트 도구


database:mysql:functions

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

다음 판
이전 판
database:mysql:functions [2012/08/10 20:15]
kwon37xi 새로 만듦
database:mysql:functions [2015/11/15 18:36] (현재)
kwon37xi [마지막 Insert ID]
줄 1: 줄 1:
 ====== MySQL Functions ====== ====== MySQL Functions ======
 ===== 마지막 Insert ID ===== ===== 마지막 Insert ID =====
-  * [[http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id|LAST_INSERT_ID()]] : 마지막 생성된 ID를 SELECT할 수 있다. +  * [[https://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id|LAST_INSERT_ID()]] : 마지막 생성된 ID를 SELECT할 수 있다.<code sql>
-<code sql>+
 SELECT LAST_INSERT_ID(); SELECT LAST_INSERT_ID();
 </code> </code>
 +  * 이 함수는 기본적으로 insert 문을 실행하여 ''AUTO_INCREMENT'' 컬럼의 값이 변경되면 그 값을 리턴해주는 역할을 한다.
 +  * 만약 ''AUTO_INCREMENT'' 컬럼에 ''0''과 ''null''이외의 값을 명시적으로 넣으면 ''last_insert_id()''는 변경되지 않는다. 따라서 ''AUTO_INCREMENT'' PK에 값을 직접 넣을 때는 last_insert_id()를 믿어서는 안된다.<code sql>
 +-- 아래와 같은 형태로 하면 0, null 이외의 PK 값에 대해서도 last_insert_id()를 믿을 수 있게 된다.
 +INSERT INTO some_table (primary_key) values(last_insert_id(직접지정_PK값));
 +SELECT last_insert_id(); --> '직접지정_PK값' 을 리턴한다.
 +</code>
 +  * 단일 insert 문에서 여러 row를 insert하면, 첫번째 insert에서 생성된 PK로 값이 설정된다.<code sql>
 +INSERT INTO t VALUES (NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa');
 +SELECT last_insert_id(); --> 'Mary' 가 속한 row의 PK가 리턴된다.
 +</code>
 +  * ''last_insert_id(expr)'' 형태로 사용하여 ''expr''을 지정하면 이 함수 자체는 ''expr''을 리턴하고, 또한 그 다음 ''SELECT last_insert_id()''에서 리턴할 값도 ''expr''로 설정한다.
  
 +===== 조건적 count =====
 +count 함수는 null이면 세지 않고 null 이외의 값이면 1씩 더하는 특징이 있다. if 문과 조합하여 조건적 count를 할 수 있다.
 +<code sql>
 +select name, count(1) as total, count(if(age < 20, 1, null)) as YOUNG from users
 +group by name
 +</code>
  
database/mysql/functions.1344597322.txt.gz · 마지막으로 수정됨: 2012/08/10 20:15 저자 kwon37xi