开发者

How to minimize queries

I have 2 tables wthat will need 4 tuples upadated or inserted, for example 开发者_StackOverflow社区Table will have an entry for game and career for each player (2) SO that is 4 tuples. Off the top of my head I can only think to do a SELECT for player1 and game if not exist insert else update, theh for player1 and a career, ....... This seems like a lot of DB queries is there a better way to handle this? In PHP PDO MYSQL existing code:

CREATE TABLE `standings` (  
 `id` int(11) NOT NULL AUTO_INCREMENT,  
 `league_id` int(11) NOT NULL,  
 `season_id` int(11) NOT NULL,  
 `team_id` int(11) NOT NULL,  
 `statistic_type_id` int(11) NOT NULL,  
 `wlt` varchar(30) NOT NULL);    


$sth = $dbh->prepare('Select * from standings   
            where league_id=?  and season_id=? and team_id=? and statistic_type_id=$? ');  

$data = $sth->execute(array($l, $s, $t, $st));  

$data = $sth->fetchAll();  

if ($sth->rowCount() == 0) {    
    $wlt = $w . '," . $lo . ',' . $di;
    $sth = $dbh->prepare('INSERT INTO standings ( id, league_id, season_id,     
                team_id, statistic_type_id, wlt)  
                VALUES( 0, ?, ?, ?, ?, ?); 

         $data = $sth->execute(array( $l, $s, $t, $st, $wlt)); 

} else {  
    foreach ($data as $row) { 
        $wlt = explode(",", $row['wlt']);   
        $wlt[0] = $wlt[0] + $w;   
        $wlt[1] = $wlt[1] + $lo;    
        $wlt[2] = $wlt[2] + $di;   
        $nwlt = implode(",", $wlt);  

        $sth = $dbh->prepare('UPDATE standings SET wlt=?   
            where league_id=?  and season_id=? and team_id=? and statistic_type_id=$? ');  

        $data = $sth->execute(array($nwlt, $l, $s, $t, $st)); 
     }
} 


You can use replace into http://dev.mysql.com/doc/refman/5.0/en/replace.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜