2017-04-01 138 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();