我问过类似的问题,但它已经成为一个更大的问题。
下面的问题迎合了 2 个选项,但如果数据库中存储了一个选项则不行。请参阅:使用 SUBSTRING_INDEX()。 Joyal George 的回答: MYSQL SELECT multiple values between "" in Column
我在 WordPress 中有一个表格,用于捕获有关希望在某些区域接收更新的人的信息。他们可以选择 1 个或多个区域。
然后我有一个报告插件,它只接受 SQL 来检索报告的数据。没有应用层,只有对MYSQL数据库的SQL查询
如果有人只选择了 1 个区域,我只需要提取那个区域。如果他们选择了 1 个以上的区域,我需要提取每个区域并用逗号分隔。他们最多可以选择 9 个区域。
列中数据如下:
1个区域:
Western Cape
多个区域:
a:3:{i:0;s:10:"North-West";i:1;s:12:"Western Cape";i:2;s:13:"Northern Cape";}
我正在使用 case 语句(此数据库结构的先前问题)
select
a.entry_id,
MAX(case when field_id = 74 then entry_value end) as FirstName,
MAX(case when field_id = 75 then entry_value end) as LastName,
MAX(case when field_id = 76 then entry_value end) as Email,
MAX(case when field_id = 78 then entry_value end) as Phone,
MAX(case when field_id = 79 then
(select concat(
SUBSTRING_INDEX(
SUBSTRING_INDEX(
SUBSTRING_INDEX(
entry_value,
'"',
4
),
'"',
2
),
'"',
-1
),
",",
SUBSTRING_INDEX(
SUBSTRING_INDEX(
SUBSTRING_INDEX(
entry_value,
'"',
4
),
'"',
4
),
'"',
-1
)
))
end) as InterestedIn,
MAX(case when field_id = 81 then entry_value end) as Province from ch_arf_entry_values a GROUP BY a.entry_id
我需要调整“as InterestedIn”以仅满足 1 个输入值。
我需要为“作为省份”的最后一个案例找到解决方案
如有任何帮助,我们将不胜感激。
最佳答案
您应该找到一种更好的方式来表示您想要的内容,但我认为以下方式很接近:
select concat_wc(',', substring_index(substring_index(entry_value, '"', 2), '"' -1),
substring_index(substring_index(entry_value, '"', 4), '"' -1),
. . .
)
您可能必须根据字符串中值的数量设置停止条件,结果如下:
select concat_ws(',',
case when num_entry_values >= 1 then substring_index(substring_index(entry_value, '"', 2), '"' -1) end,
case when num_entry_values >= 2 then substring_index(substring_index(entry_value, '"', 4), '"' -1) end,
. . .
)
如果没有这个数,可以通过统计字符串中双引号的个数来计算。
编辑:
要计算条目数,请计算”
:
from (select aev.*,
(length(entry_value) = length(replace(entry_value, '"', '')) ) / 2 as num_entry_values
from ch_arf_entry_values aev
) aev
关于MySQL在一列困惑的文本中选择引号 ""中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26650251/