我正在尝试使用不同的值更新多行,但是我只想使用一个UPDATE查询以获得快速结果。.下面是我尝试过的操作,但是执行时间很长,有时浏览器出现错误,我无法继续执行代码,有什么解决方案吗?
require_once'db.php';
$ price ='10000';
如果($ _POST){
$sql_query = "SELECT * FROM views_by_user WHERE views > 0";
$db = new database();
$con = $db->dbconnect();
$res = $db->query($con, $sql_query);
if($res){
$total_views = TotalViews();
while($row = mysqli_fetch_assoc($res)){
$email = $row['email'];
$user_views = $row['views'];
$old_balance = UserOldBalance($email);
$percentage = ($user_views / $total_views) * 100;
$percentage = number_format($percentage, 0);
$earned_balance = ($price * $percentage) / 100;
$new_balance = $old_balance + $earned_balance;
$sql_query = "UPDATE users SET balance = '$new_balance' WHERE email = '$email'";
$db = new database();
$con = $db->dbconnect();
$res = $db->query($con, $sql_query);
if($res){
$sql_query = "UPDATE views_by_user SET views = '0' WHERE email = '$email'";
$db = new database();
$con = $db->dbconnect();
$res = $db->query($con, $sql_query);
if($res){
echo "Balance Updated Successfully For " . $email . "<br />";
}
else {
echo "Error Updating Views...";
}
}
else {
echo "Error Updating Balance...";
}
}
}
else {
echo "error";
}
}
}
function TotalViews(){
$sql_query = "SELECT SUM(views) as 'total_views' FROM views_by_user";
$db = new database();
$con = $db->dbconnect();
$res2 = $db->query($con, $sql_query);
if($res2){
while($row2 = mysqli_fetch_assoc($res2)){
$total_views = $row2['total_views'];
}
}
return $total_views;
}
Function UserOldBalance($ email){
$sql_query = "SELECT gems_balance FROM users WHERE email = '$email'";
$db = new database();
$con = $db->dbconnect();
$res3 = $db->query($con, $sql_query);
if($res3){
while($row3 = mysqli_fetch_assoc($res3)){
$old_gems = $row3['gems_balance'];
}
}
return $old_gems;
}
答案 0 :(得分:0)
您当前的代码效率低下,我们可以尝试将其重写为单个MySQL更新查询。例如,您的第一个查询可能被重写为:
UPDATE users u
SET balance = gems_balance + 10000 * ROUND(views / (SELECT SUM(views) FROM views_by_user));
WHERE email = ?;
这样就无需像使用游标那样遍历表。相反,您可以执行一个语句。如果您只想更新给定的电子邮件,则将单个值绑定到上面的?
。如果要更新整个表,则只需删除WHERE
子句。
第二个查询(假设您希望将其应用于整个表)只是一个简单的全局更新:
UPDATE views_by_user
SET views = 0;
答案 1 :(得分:0)
我找到了解决我问题的方法,我必须使用mysql查询,如下所示:
public class RegisterUserController {
public void start(User user){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ChatRoomAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ChatRoomAPI chatRoomAPI = retrofit.create(ChatRoomAPI.class);
Call<User> call = chatRoomAPI.registerUser(user);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Log.d("TAG" , "onResponse" + response.code());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.d("TAG" , "onFailure" + t.getCause()); //
}
});
}
}