2017-04-01 3 views
1

Ich versuche, eine Zeile nur einzufügen, wenn zwei Bedingungen erfüllt sind. Ich möchte das in einer Aussage machen. Meine Tabelle wie folgt aussieht:Verkettung von Mysql-Abfragen für die Einfügung

   [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      

Gibt es eine Möglichkeit, einen SQL-Code, auszuführen:

LIRFU = letzte eingefügte Zeile für User = SELECT * FROM Table WHERE userId = $userId ORDER BY timestamp DESC LIMIT 1.

  • fügt eine Zeile ($userId, $locationId, 1) wenn LIRFU.type = 0.
  • Fügt eine Zeile ($userId, $locationId, 0) ein, wenn .

Antwort

1

Lassen Sie uns Ihren Tisch anrufen, User_Types.

Hier ist die Anweisung eine Zeile mit Beispieldaten einfügen (5,19,1), wenn 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; 

Sie diese in eine vorbereitete Anweisung in PHP machen können, indem die Daten mit ? ersetzen.

$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(); 

Hier ist die Anweisung eine Zeile mit Beispieldaten einfügen (5,19,0), wenn LIRFU.type = 1 AND LIRFU.locationId != 19:

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; 

Die gleiche Idee, wenn es in PHP hergestellt:

$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();