2013-03-01 23 views
9

我有一張表,我需要從另一個表中存儲兩個ID。在做一些調試時,我注意到了一些奇怪的SQL行爲。錯SQL的意外的INSERT ... SET查詢行爲

實施例:

INSERT INTO follower_list set `followerUserId` = '3' AND `followingUserid` = '4' 

上述查詢被插入零的像在DB值。我仔細研究了查詢,並意識到我錯誤地將and代替爲,。我需要實現我的目的的真正查詢是:

INSERT INTO table SET col1 = '3' , col2 = '4' 

其中的工作如我所料。我的問題與第一個(不正確的)查詢有關 - 因爲它執行並且在語法上是正確的,那麼查詢會在哪裏使用?

回答

11

爲什麼INSERT語句不會生成語法錯誤的原因,它也在努力是因爲MySQL隱含(有一件事我沒有在MySQL :D等)解析語句布爾表達式。

在你INSERT聲明,只有followerUserId更新,因爲剩下的都是布爾表達式的一部分。查詢被評價爲:

INSERT INTO follower_list SET followerUserId = ('3' and (followingUserid='4')) 

這裏:

followerUserId = ('3' and (followingUserid='4')) // assuming followingUserid <> 4 
followerUserId = ('3' and (0)) 
followerUserId = 0 

另外,

followerUserId = ('3' and (followingUserid='4')) // assuming followingUserid = 4 
followerUserId = ('3' and (1)) 
followerUserId = 1  // will only return zero if one of the values is zero 
+1

你先生是SQL的喬恩斯基特..驚人知識。 – 2013-03-01 10:02:25

+0

謝謝@JW今天我也學習用'SET'和'AND'插入':) – 2013-03-01 10:03:01

+0

@YogeshSuthar它是mysql中'INSERT'的一箇舊語法。 – 2013-03-01 10:03:42