[英]Update a table with count() from another table
Table test_a 表test_a
| genId | country | alcohol_spirits | music |
|-------|---------|-----------------|-------|
| 1 | US | 0 | 0 |
| 2 | IN | 0 | 0 |
| 3 | SE | 0 | 0 |
Table test_b 表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 |
My sql 我的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 */
I'm trying to update table test_a
with the count()
of items from test_b
for each country. 我正在尝试使用来自每个国家的
test_b
项目的count()
更新表test_a
。 It's hard to explain, but you'll see from my expected results. 很难解释,但是您将从我的预期结果中看到。
For alcohol_spirits
, the US
has 4
and SE
has 3
. 对于
alcohol_spirits
, US
为4
, SE
为3
。 I'm trying to update it all at once, but what I thought would work, does not. 我正在尝试一次更新所有内容,但我认为可行,但没有成功。 Where am I going wrong and how to get this right?
我要去哪里错了,如何解决这个问题?
Expected results 预期成绩
| genId | country | alcohol_spirits | music |
|-------|---------|-----------------|-------|
| 1 | US | 4 | 0 |
| 2 | UK | 0 | 0 |
| 3 | SE | 4 | 0 |
You can use a query for this like this 您可以像这样使用查询
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)
)
Try this 尝试这个
update test_a set
alcohol_spirits=(
select alcohol_spirits+count(*) from test_b where headDestinations like '%'+country +'%')
this query will added current alcohol_spirits with every execution you shout alwase update with only count like following query 该查询将在每次喊叫更新时执行的每次执行中添加当前的alcohol_spirits,其计数仅与以下查询类似
update test_a set
alcohol_spirits=(
select count(*) from test_b where headDestinations like '%'+country +'%')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.