mysql - 使用 count() 从另一个表更新一个表

标签 mysql sql

表 test_a

| genId | country | alcohol_spirits | music |
|-------|---------|-----------------|-------|
|     1 |      US |               0 |     0 |
|     2 |      IN |               0 |     0 |
|     3 |      SE |               0 |     0 |

表 test_b

| itemId |       headAlias | headDestinations |   iTitle |
|--------|-----------------|------------------|----------|
|      1 | alcohol-spirits |            US,SE | Bottle 1 |
|      2 | alcohol-spirits |            US,SE | Bottle 2 |
|      3 | alcohol-spirits |            US,SE | Bottle 3 |
|      4 | alcohol-spirits |               US | Bottle 4 | 

我的sql

update test_a set alcohol_spirits = alcohol_spirits + 
(
    select 
        count(itemId) 
    from test_b 
    where headAlias = 'alcohol-spirits' 
    and headDestinations IN ('US,SE') /* 'US,SE' = user input*/

) where country IN('US,SE') ; /* 'US,SE' = user input */

我正在尝试使用每个国家/地区的 test_b 项目的 count() 更新表 test_a。这很难解释,但你会从我的预期结果中看到。

对于 alcohol_spiritsUS4SE3。我试图一次性更新所有内容,但我认为可行的方法却行不通。我哪里出错了以及如何解决这个问题?

预期结果

| genId | country | alcohol_spirits | music |
|-------|---------|-----------------|-------|
|     1 |      US |               4 |     0 |
|     2 |      UK |               0 |     0 |
|     3 |      SE |               4 |     0 |

最佳答案

您可以像这样使用查询

UPDATE table_a a
SET a.alcohol_spirits = a.alcohol_spirits + 
(SELECT
     count(table_b.itemId)
 FROM table_b
 WHERE headAlias = 'alcohol-spirits' 
 AND country IN('US,SE')
 AND FIND_IN_SET(a.country, table_b.headdestinations)
)

关于mysql - 使用 count() 从另一个表更新一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23807781/

相关文章:

mysql - 关于在 Mac 上设置 mySQL 的一些问题

php - 存储过程 join 转换为 PHP

mysql - 消息 2627 违反 PRIMARY KEY 约束

sql - 在 sqlite 中使用 guid 选择 guid 作为二进制文件存储在 sqlite 数据库中的位置

java - 如何通过 JDBC 使用包含问号 "?"的 PostgreSQL JSON(B) 运算符

java - 构建数据库查询的设计模式

MySQL - 索引在登台服务器上工作,但在生产服务器上不起作用

php - 我可以从 MySQL 数据库中进行选择,但是当我运行此插入时没有任何反应(仅插入到 1 个表中)

mysql - 如何为我的表中的多个代码选择最新行?

sql - 优化查询,使 Order by random 运行得更快