Thread Insert Into... On Duplicate Key Update...
(20 answers)
Opened by rosti at 2012-05-25 20:39
Wie versprochen, der Bench:
Code: (dl
)
1 Mit DELETE FROM, Tabellen sind leer Edit: Benchmark wiederholt. So ganz eindeutig sind die Ergebnisse nicht, bei manchen Durchläufen ist es auch andersherum. Wer Lust und Laune hat, kann ja mal den Code kopieren und nachvollziehen. Code zum Nachvollziehen Code (perl): (dl
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 #/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese timethese); use DBI; my $ins = 'abcde'; my $DBH = dbh(); my $STH = { INS_AUTO => $DBH->prepare("INSERT INTO test(text)VALUES(?)"), IS_DRIN => $DBH->prepare("SELECT id FROM test WHERE text=?"), LAST_ID => $DBH->prepare("SELECT LAST_INSERT_ID()"), REDESIGN => $DBH->prepare(q( INSERT INTO redesign(text)VALUES(?) ON Duplicate Key UPDATE text=? )), }; # bisherige Lösung, vorh. Abfrage | Last_Insert_ID sub autoincr{ $DBH->do("DELETE FROM test"); $STH->{IS_DRIN}->execute($ins); my $id = 0; if($id = $STH->{IS_DRIN}->fetchrow_array){ return $id; } else{ $STH->{INS_AUTO}->execute($ins); $id = $STH->{LAST_ID}->execute; $id = $STH->{LAST_ID}->fetchrow_array; return $id; } } # Lösung nach redesign sub redesign{ $DBH->do("DELETE FROM redesign"); $STH->{REDESIGN}->execute($ins, $ins); return $ins; } cmpthese(50_000_000, { 'Redesign' => &redesign, 'AutoIncr' => &autoincr, }); sub dbh{ my %cfg = ( base => 'myweb', host => 'localhost', port => 3306, user => '', pass => '', @_); my $dbh = undef; eval{ $dbh = DBI->connect("DBI:mysql:$cfg{base}:$cfg{host}:$cfg{port}", $cfg{user}, $cfg{pass}, {RaiseError => 1, PrintError => 0} ); }; return $@ ? undef : $dbh; } __END__ mysql> show create table test; CREATE TABLE `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `text` varchar(20) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=99 DEFAULT CHARSET=utf8 mysql> show create table redesign; redesign | CREATE TABLE `redesign` ( `text` varchar(29) NOT NULL DEFAULT '', PRIMARY KEY (`text`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 Last edited: 2012-05-28 09:20:20 +0200 (CEST) |