본문 바로가기
개발언어/SQL

Mysql if exists insert 하기

by 엔돌슨 2011. 12. 1.
반응형
Mysql에서 데이타 존재여부를 확인하여 insert 처리를 하려고 합니다. MSSQL처럼 if exists로 쉽게 처리할 수 있을거라고 생각했지만 고생을 조금하였네요. not exists 의 경우 제약사항이 있어 mssql처럼 if then 문으로 처리는 불가능하지만 where에서 어느정도 처리를 할 수 있었습니다.

MYSQL - IF NOT EXISTS ... INSERT INTO 처리를 하려면 where에 넣어야 합니다.
아래의 쿼리는 제가 작성한 쿼리입니다.

간단히 ofgroupprop 테이블에 '0000007' 이 존재하지 않으면 insert하는 간단한 코드입니다. 

INSERT INTO ofgroupprop (groupName, name, propValue)
SELECT groupName, name, propValue
FROM 
(
select '000007' as groupName, 'sharedRoster.displayName' as name, '' as propValue
union all
select '000007' as groupName, 'sharedRoster.groupList' as name, '' as propValue
union all
select '000007' as groupName, 'sharedRoster.showInRoster' as name, 'onlyGroup' as propValue
) as a
WHERE groupName = '000007'
AND NOT EXISTS (SELECT * FROM ofgroupprop WHERE groupName = '000007');



MYSQL 설명
http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

참고한 사이트 
http://dotnetfish.blogspot.com/2011/11/mysql-if-not-exists-insert-into.html





12.2.9.6. Subqueries with EXISTS or NOT EXISTS

If a subquery returns any rows at all, EXISTS subquery is TRUE, and NOT EXISTS subquery is FALSE. For example:

SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.

For the preceding example, if t2 contains any rows, even rows with nothing but NULL values, the EXISTS condition is TRUE. This is actually an unlikely example because a [NOT] EXISTS subquery almost always contains correlations. Here are some more realistic examples:

  • What kind of store is present in one or more cities?

    SELECT DISTINCT store_type FROM stores
      WHERE EXISTS (SELECT * FROM cities_stores
                    WHERE cities_stores.store_type = stores.store_type);
  • What kind of store is present in no cities?

    SELECT DISTINCT store_type FROM stores
      WHERE NOT EXISTS (SELECT * FROM cities_stores
                        WHERE cities_stores.store_type = stores.store_type);
  • What kind of store is present in all cities?

    SELECT DISTINCT store_type FROM stores s1
      WHERE NOT EXISTS (
        SELECT * FROM cities WHERE NOT EXISTS (
          SELECT * FROM cities_stores
           WHERE cities_stores.city = cities.city
           AND cities_stores.store_type = stores.store_type));

The last example is a double-nested NOT EXISTS query. That is, it has a NOT EXISTS clause within a NOT EXISTS clause. Formally, it answers the question “does a city exist with a store that is not in Stores”? But it is easier to say that a nested NOT EXISTS answers the question “is x TRUE for all y?