1

この構文エラーが発生し続けますが、他の例と比較しても問題は見つかりません。

if EXISTS (select 1 from City where name = 'Perth')
THEN  Print 'Record exits - Update'
ELSE  Print 'Record doesn''t exist - Insert' 

エラーが見つかりました:

#1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'if EXISTS (select
1 from City where name = 'Perth') THEN Print 'Record e' at line 1

これは、zendクラウドと通常のphpmyadmin mysql 5の両方で取得できます

4

3 に答える 3

2

これは実際には有効な MySQL クエリではありません。クエリが存在するかどうかに基づいて、SQL と出力を表示する方法を混在させようとしているようです。Perthこれを使用して、SQL に存在するかどうかを返すことができます。

SELECT EXISTS(SELECT 1 FROM City WHERE name = 'Perth')

1これはorを返し0、サーバー側のスクリプトで解析できます。構文エラーが発生する理由は、MySQLIFステートメントが(プログラミング言語でよくあるように) orIF(condition, <action if true>, <action if false>)を使用しない形式を取るためです。また、MySQL には明示的なステートメントはありませんが、上記の目的をある程度達成するために使用できます (結果が何も返さない場合は False が暗示されるため、削除できることに注意してください)。THENELSEPRINTSELECTEXISTS

SELECT IF(
      (SELECT 1 FROM City WHERE name = 'Perth'),
      (SELECT 'Record exists - update'),
      (SELECT 'Record does not exist - Insert')
)
于 2012-11-16T02:55:49.097 に答える
1

print次の方法ではなく、「select」を使用する必要があります

select IF((select 1 from city where name='Perth'),
'Record exits - Update','Record does not exist - Insert');

SQLフィドルデモIF以下は、 selectステートメントでの使用を示してい

IF((select 1 from city where name='Perth'),
'Record exits - Update','Record does not exist - Insert');

IF2つのメッセージが含まれています。

最初:'Record exits - Update'2番目:'Record does not exist - Insert'

(select 1 from city where name='Perth')いくつかの結果(EXISTSと同等)がある場合は最初のメッセージが出力され、そうでない場合は2番目のメッセージが表示されます

于 2012-11-17T22:26:37.497 に答える
0

別の方法: グループ化関数を使用すると、常にレコードが返されます。操作するレコードがない場合、group by 関数の結果は になりますNULL。それを決定メカニズムとして使用できます。

postgres=# create table city(name text);
CREATE TABLE
postgres=#
postgres=# select COALESCE( max('Record exists - Update'), 'Record doesn''t exist - Insert' ) as state
postgres-#   from city
postgres-#   where name = 'Perth';
             state
-------------------------------
 Record doesn't exist - Insert
(1 row)


postgres=#
postgres=# insert into city values('Perth');
INSERT 0 1
postgres=#
postgres=# select COALESCE( max('Record exists - Update'), 'Record doesn''t exist - Insert' )  as state
postgres-#   from city
postgres-#   where name = 'Perth';
         state
------------------------
 Record exists - Update
(1 row)
于 2012-11-16T03:47:54.790 に答える