MySQL如何获取每个关键字的行数

时间:2014-04-16 21:12:33

标签: mysql

我在table1中有一个名为text的字段。我怎么能算出有多少行有" test"," test2"和" test3"?

到目前为止,我有:

SELECT count(*) FROM table WHERE text LIKE "%test%" OR text LIKE "%test2%" OR text LIKE "%test3%"

但只返回整个计数

我需要类似的东西:

test 100
test2 115
test3 12

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

也许UNION会很适合你:

SELECT
    'test' AS `search_term`,
    COUNT(*) AS `term_count`
FROM table
WHERE text LIKE '%test%'
UNION
SELECT
    'test2' AS `search_term`,
    COUNT(*) AS `term_count`
FROM table
WHERE text LIKE '%test2%'
UNION
SELECT
    'test3' AS `search_term`,
    COUNT(*) AS `term_count`
FROM table
WHERE text LIKE '%test3%'