gpt4 book ai didi

php - 根据另一个表的条件更新表

转载 作者:行者123 更新时间:2023-11-29 11:38:45 25 4
gpt4 key购买 nike

我有 2 个数据库表

1-用户

id  points

1 100
2 3
3 1

2- user_pages

user_id  lp_flag

1 0
2 0
3 0

如果用户表中的任何 id 点 < 5,我正在尝试更新 lp_flag = 1。

这是我的代码,我想仅使用 cron 作业运行它。

$Point_row = mysql_query("SELECT * FROM users WHERE points < 5 ");

foreach($Point_row as $val){if($val['points']<5) {

mysql_query("UPDATE user_pages SET lp_flag = '1' WHERE user_id = '$id'")
}else{

mysql_query("UPDATE user_pages SET lp_flag = '0' WHERE user_id = '$id'") }
}
}

预期结果

用户页面

user_id  lp_flag

1 0
2 1
3 1

因为id的2和3点在users表中<5。

最佳答案

您应该在一个查询中执行此操作:

update user_pages up join
users u
on up.user_id = u.id
set up.lp_flag2 = (case when u.points < 5 then 2 else 0 end);

应用程序端不需要循环。

关于php - 根据另一个表的条件更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com