php - 在 SQL 中从另一个表更新一个表的最佳方法是什么?

标签 php mysql sql inner-join exists

我有 2 个表,第一个是产品页面访问过

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| idproduct  | varchar(128) | YES  |     | NULL    |                |
| logdate    | date         | YES  |     | NULL    |                |
| idmagasin  | int(20)      | YES  |     | NULL    |                |
| idenseigne | int(20)      | YES  |     | NULL    |                |
| commanded  | int(2)       | YES  |     | 0       |                |
+------------+--------------+------+-----+---------+----------------+

第二个是命令

的产品
+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| id          | int(11)      | NO   | PRI | NULL              | auto_increment |
| idproduct   | varchar(255) | NO   |     | NULL              |                |
| idenseigne  | int(11)      | NO   |     | NULL              |                |
| idmagasin   | int(11)      | NO   |     | NULL              |                |
| ingredients | tinytext     | YES  |     | NULL              |                |
| date        | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
+-------------+--------------+------+-----+-------------------+----------------+

如何更新 product_visited 中的 commanded 列,如果 product_visited.idproduct = product_commanded.idproduct 和 product_visited.logdate = product_commanded.date

我对使用inner joinexists 感到困惑

logdateidproduct 的值存在于 product_commanded 中时,我想更新 product_visited.commanded = 1这意味着访问的产品也是命令

最佳答案

我相信这就是您要找的:

Update product_visited pv
    set commanded = 1
    Where exists (Select 1
                  from product_commanded pc
                  where pv.idproduct = pc.idproduct and pv.logdate = pc.date
                 );

关于php - 在 SQL 中从另一个表更新一个表的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41267024/

相关文章:

php - mysql 查询的多个循环

SQL COUNT 返回使用特定属性的项目数

sql - 数据库会读但不会写

php - 使用 PHP 生成 MySQL 数据库的 XML 输出的最佳方法是什么

javascript - 带有融合图的响应式饼图

php - 广告网络基础设施意见? MySQL?内存缓存?数据库?

javascript - 从数据库中获取UTC时间并在浏览器中显示本地时间

mysql - 需要数据库设计方面的建议

sql - Oracle 外连接 "entity"

sql - 有没有办法找到哪些帐户可以执行xp_cmdshell?