表 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_spirits
,US
有 4
,SE
有 3
。我试图一次性更新所有内容,但我认为可行的方法却行不通。我哪里出错了以及如何解决这个问题?
预期结果
| 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/