5

我有一个字符串数组和一个带有文本类型列的表。我想列出表中任何行的指定列中出现了多少个字符串。有没有办法用一个查询来做到这一点?

Example;
$strings = array('test', 'sth');

Table;
id | someTextColumn
-------------------
1  | abc tests
2  | sthab
3  | teststh
4  | abcd
5  | sth

Expected result;
str  | occurences
-----------------
test | 2
sth  | 3
4

3 回答 3

0

如果表大小不太大并且列已正确索引:

SELECT 'test', COUNT(id)
FROM tableName
WHERE someTextColumn LIKE '%test%'
UNION ALL
SELECT 'sth', COUNT(id)
FROM tableName
WHERE someTextColumn LIKE '%sth%'
于 2013-05-26T12:41:48.010 回答
0
$query = "select someTextColumn, count(id) from tableName where "
for($i=0; $i < count($Strings); $i++)
{
   if($i != 0)
   $query .= " OR ";
   $query .= "someTextColumn =" . $string[$i];
}
$query .= " group by someTextColumn";

$result = mysql_query($query);

试试这个,我希望这能解决你的问题!!

于 2013-05-26T13:16:11.473 回答
0

您可以使用一系列like语句来做到这一点。

这是一个例子:

select totest.str, count(t.id)
from (select 'test' as str union all
      select 'sth'
     ) totest left outer join
     t
     on t.someTextColumn like concat('%', totest.str, '%')
group by totest.str

如果您的表很大,这不会特别快。如果您有较大的表,您可能需要考虑全文索引。

于 2013-05-26T13:17:49.513 回答