使用另一个表中的count()更新表

时间:2014-05-22 13:09:21

标签: 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_a的{​​{1}}项为每个国家/地区更新表count()。这很难解释,但是你会从我的预期结果中看到。

对于test_balcohol_spiritsUS4SE。我试图立即更新所有内容,但我认为可行,但事实并非如此。我哪里出错了,如何做到这一点?

预期结果

3

2 个答案:

答案 0 :(得分:3)

您可以像这样使用查询

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)
)

答案 1 :(得分:1)

试试这个

update test_a set 
alcohol_spirits=(
select alcohol_spirits+count(*) from test_b where headDestinations like '%'+country +'%')

这个查询会添加当前的alcohol_spirits,每次执行你喊的alwase更新,只计算如下查询

update test_a set 
alcohol_spirits=(
select count(*) from test_b where headDestinations like '%'+country +'%')