JOIN,UNION,MERGE?

时间:2012-07-08 04:35:27

标签: php mysql

我正在为Magic the Gathering Cards创建一个库存系统,需要使用主卡信息更新价格。

我有两张桌子,卡片和价格

卡片包含以下列: ID,姓名,编辑,价格

价格包含以下列: 姓名,编辑,价格

我需要Cards.Price替换为Price.Price中的值。

下面是两个不同尝试使这项工作的代码(我知道我可能会使它比它需要的更难......)

尝试#1

    $query = "SELECT * FROM Cards";

    $result = mysql_query($query) or die(mysql_error());
    $row = mysql_fetch_array($result) or die(mysql_error());

    while($row = mysql_fetch_array($result))
    {
    $name=$row['Name'];
    $ed=$row['Ed'];

    $queryb = "SELECT Price FROM Prices WHERE Name='".$name."' AND Ed='".$ed."'";
    $resultb = mysql_query($queryb) or die(mysql_error());
    $rowb = mysql_fetch_array($resultb) or die(mysql_error());
    $newPrice = $rowb['Price'];
    mysql_query("UPDATE Cards SET Price='".$newPrice."'");
    }

尝试#2

    $queryCards = "SELECT * FROM Cards";
    $queryPrices = "SELECT * FROM Prices";
    $dblink = mysql_connect($dbhost, $dbuser, $dbpass);
    mysql_select_db($dbname, $dblink);


    $resultCards = mysql_query($queryCards) or die(mysql_error());
    $resultPrices = mysql_query($queryPrices) or die(mysql_error());
    $rowCards = mysql_fetch_array($resultCards) or die(mysql_error());
    $rowPrices = mysql_fetch_array($resultPrices) or die(mysql_error());



    if ($rowCards['Name']==$rowPrices['Name'] && $rowCards['Ed']==$rowPrices['Ed'])
    {
    $newPrice = $rowPrices['Price'];
    mysql_query("UPDATE Cards SET Price='".$newPrice."' WHERE
    Name='".$rowCards['Name']."' AND Ed='".$rowCards['Ed']."'"); 
    }
    while($rowPrices = mysql_fetch_array($resultPrices))
       {
       if ($rowCards['Name']==$rowPrices['Name'] && 
                    $rowCards['Ed']==$rowPrices['Ed'])
          {
          $newPrice = $rowPrices['Price'];
          mysql_query("UPDATE Cards SET Price='".$newPrice."' WHERE 
                       Name='".$rowCards['Name']."' AND Ed='".$rowCards['Ed']."'");
          }  
       }       

   $rowPrices = mysql_fetch_array($resultPrices) or die(mysql_error());

   while($rowCards = mysql_fetch_array($resultCards))
   {
   while($rowPrices = mysql_fetch_array($resultPrices))
       {
       if ($rowCards['Name']==$rowPrices['Name'] &&
                $rowCards['Ed']==$rowPrices['Ed'])
            {
            $newPrice = $rowPrices['Price'];
                mysql_query("UPDATE Cards SET Price='".$newPrice."' WHERE 
                     Name='".$rowCards['Name']."' AND Ed='".$rowCards['Ed']."'");
                }  
                }      
    }

1 个答案:

答案 0 :(得分:0)

UPDATE Cards 
   JOIN Prices ON Cards.Name = Prices.Name AND Cards.Ed = Prices.Ed 
SET Cards.Price = Prices.Price