如果我要向 MySql 提供一个逗号分隔的字符串,如 ('US,UK,CA') (通过 php 脚本来自表单),我怎样才能让 MySql 循环该字符串并进行计数那里的每个国家/地区代码并更新不同的表,其中该表中的国家/地区代码等于字符串中的国家/地区代码。
示例:
表_a
"id" "countries"
"1" "US,CA"
"2" "US,CA"
"3" "US,AU"
"4" "US,UK"
"5" "US"
表_b
"id" "country" "total"
"1" "US" "0"
"2" "CA" "0"
"3" "UK" "0"
"4" "AU" "0"
我该怎么办:
例如:如果我提供 ('US,UK,CA')
update table_b set country = (
select count(id) from table_a where country = (// each country in that string ('US,UK,CA'))
) where country = (country currently selected from the string above)
这样的事情可以做吗?如果只有一个国家,它就可以正常工作。当有更多的时候我该怎么办?
最后,我希望得到这样的结果:
table_b
"id" "country" "total"
"1" "US" "5" // There are 5 in table_a
"2" "CA" "2" // There are 2 in table_a
"3" "UK" "1" // Only 1 in table_a
"4" "AU" "1" // Only 1 in table_a
最佳答案
尝试对“CA”县进行此操作:
update table2
set total = (
select count(*) from table1 where FIND_IN_SET(country, countries)
)
或者按一个国家/地区
update table2
set total = (
select count(*) from table1 where FIND_IN_SET('CA', countries)
)
WHERE country = 'CA'
编辑:我不知道您到底在寻找什么,但如果您需要特殊的国家/地区。只需添加 WHERE 子句
update table2
set total = (
select count(*) from table1 where FIND_IN_SET(country, countries)
)
WHERE country IN ('US','UK','CA')
关于MySql 根据逗号分隔值的输入更新计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23843037/