我只是在两个条件为真时才尝试插入一行。我想在一个声明中这样做。我的表看起来像:
[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)
,则插入行LIRFU.type = 1 AND LIRFU.locationId != $locationId
。答案 0 :(得分:1)
让我们打电话给您,User_Types
。
这里是如果LIRFU.type = 0
插入带有样本数据(5,19,1)的行的语句:
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();