多个用户的更新表

时间:2016-01-31 18:57:41

标签: php mysql

我希望计算次数'是'目前,对于表中的用户,然后将结果发布到该用户的另一个表中。两个表都有用户名。我希望每个用户都这样做。我有以下但它不起作用。

$sql = $item_count = "SELECT SUM(if(strike='yes',1,0)) AS strike_total FROM weekpicks WHERE username = 'username'";
      // execute SQL query and get result
      $sql_result = mysql_query($sql) or die (mysql_error());
      if (!$sql_result) {
          echo "Something has gone wrong!";
      } 
      else {
           //loop through record and get values
           while ($row = mysql_fetch_array($sql_result)) {

        $item_result = ($row = @mysql_query($item_count)) or die(mysql_error());
        $strike_total = ($row = @mysql_result($item_result,"strike_total"));
        $strikes = ($row = $strike_total ['strike_total']);
        $username = $row["username"];


        // the following will insert number of strikes into table for each user.
        $sql = "UPDATE authorize SET strikes  = '($strikes)' WHERE username='$username'";

        //mysql_query(" UPDATE authorize SET " . "strikes = '" . ($strikes) . "' WHERE username='$username' ");
                $result = mysql_query($sql) or die (mysql_error());

1 个答案:

答案 0 :(得分:1)

只需一个查询即可

单用户更新..

UPDATE authorize SET strikes  = (select count(*) from weekpicks WHERE username = '$username' and strike='yes') WHERE username='$username';

批量更新所有用户

UPDATE authorize as A SET strikes  = (select count(*) from weekpicks B WHERE strike='yes' and A.username=B.username group by B.username)

不是那么简单。