0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

prepared statementからsyntax errorが出て驚いた話

Last updated at Posted at 2019-05-07

##前書
prepared statementなのに値によってsyntax errorが出て混乱したのでメモ

##現象
全く関係ない二列に同じ値を設定するとDuplicate column nameが発生する

-- 実行出来る
select
    'abc'
    , 'abc';

-- 実行出来る
select
    *
from
    (
        select
            'abc'
            , 'xyz'
    ) as temp;

-- 実行出来ない
select
    *
from
    (
        select
            'abc'
            , 'abc'
    ) as temp;

※リテラル部分は実際にはprepared statementから指定して実行した

##対処法
ASを使用し列名を設定する
dual表を使用する

-- 実行出来る
select
    *
from
    (
        select
            'abc' as c1
            , 'abc' as c2
    ) as temp;

-- 多分これが一番正しい
select
    'abc'
    , 'abc'
from
    dual;

-- 次点
select
    'abc'
    , 'abc'
from
    (
        select
            1
    ) as temp;
    

※リテラル部分は実際にはprepared statementから指定して実行した

##因みに
なんでこんな構成が出現したのかというと、insert into valuesにwhere条件を付けたくてinsert into selectに変換
その際from句が必要になったため
MySQLにdualがある(互換性のためらしい)ことを知っていればこんなことには

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?