MySql Update基于逗号分隔值的输入计数

时间:2014-05-24 08:41:17

标签: mysql sql

如果我要为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"

我该怎么做:

例如:如果我提供('美国,英国,加州')

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

1 个答案:

答案 0 :(得分:2)

尝试使用县' CA':

 update table2 
 set total = (

select count(*) from table1 where FIND_IN_SET(country, countries)
)

DEMO

或者由一个国家/地区

 update table2 
 set total = (

  select count(*) from table1 where FIND_IN_SET('CA', countries)
 )
  WHERE country = 'CA'

DEMO

编辑:我不知道你究竟在寻找什么,但如果你需要特殊国家。只需添加一个WHERE子句

   update table2 
 set total = (

 select count(*) from table1 where FIND_IN_SET(country, countries)
 )
 WHERE country IN ('US','UK','CA')

DEMO