2014-05-24 31 views
0

的輸入。如果我是提供MySQL中的逗號分隔字符串,像(「美國,英國,CA」)(它通過一個PHP腳本來自於一種形式),我怎麼能讓MySQL通過字符串循環,並做了每個國家代碼的計數在那裏和更新不同的表,其中該表中的國家代碼等於字符串中的國家代碼。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" 

我該怎麼辦:

例如:如果我增刊IED( '美國,英國,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 
+0

你想更新總表B? –

+0

@echo_Me是'table_b'如在我討論的最後一個例子。 – jmenezes

+0

正常化不是一種選擇? – Strawberry

回答

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

+0

糾正這個:) http://www.sqlfiddle.com/#!2/e57dc/1 – Ryx5

+0

@echo_me我需要把整個字符串中有沒有像(「美國,英國,CA」),因爲我已經證明在我的問題中,而不是一次一個,或者像Ryx5所做的那樣。 – jmenezes

+0

嘗試更新答案。 –