2017-04-01 99 views
1

我只想在兩個條件爲真時插入一行。我想在一個聲明中這樣做。我的表如下所示:鏈接Mysql查詢插入

   [Table]     
id, userId, locationId, type, timestamp    
---------------------------------------    
1 5 19 0 2017-03-28 03:05:48     
2 5 19 1 2017-03-29 00:57:57      

是否有執行SQL的方式:

LIRFU =上次插入行對於用戶= SELECT * FROM Table WHERE userId = $userId ORDER BY timestamp DESC LIMIT 1

  • 插入一行($userId, $locationId, 1)如果LIRFU.type = 0
  • 插入一行($userId, $locationId, 0) if 。

回答

1

讓我們打電話給你的表,User_Types

這裏插入樣本數據(5,19,1)如果LIRFU.type = 0一行語句:

INSERT INTO User_Types (userId, locationId, type) 
SELECT @userId:=5, 19, 1 from dual 
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0; 

您可以通過?替換數據製作成一份準備好的聲明這PHP。

$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, ?, 1 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0"); 

$stmt->bind_param('ii', $user_id, $location_id); 
//if LIRFU.type = 0 

$stmt->execute(); 

這裏的插入,如果LIRFU.type = 1 AND LIRFU.locationId != 19與樣本數據的行(5,19,0)聲明:

INSERT INTO User_Types (userId, locationId, type) 
SELECT @userId:=5, @locationId:=19, 0 from dual 
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 
AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId; 

,當它在PHP,準備同樣的想法:

$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, @locationId:=?, 0 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId"); 

$stmt->bind_param('ii', $user_id, $location_id); 
//if LIRFU.type = 1 and LIRFU.locationId != $location_id 

$stmt->execute();