sql / mysql搜索两个关键字的一个字段

时间:2012-02-03 09:08:34

标签: mysql sql

这就是我所拥有的:

SELECT `id`, `names` FROM `screenplays` WHERE `names` LIKE '%joe%mike%'

字段名称包含:

row1: joe
row2: mike
row3: joe,mike

如何返回所有3行?

3 个答案:

答案 0 :(得分:3)

使用

SELECT `id`, `names` 
FROM `screenplays` 
WHERE `names` LIKE '%joe%' 
    OR `names` LIKE '%mike%'

如果用逗号分隔名称,并且在指定joe时不需要像joey这样的名称,则可以扩展查询,如:

SELECT `id`, `names` 
FROM `screenplays` 
WHERE `names` LIKE 'joe'
    OR `names` LIKE '%,joe'
    OR `names` LIKE 'joe,%'
    OR `names` LIKE '%,joe,%'

同样适用于每个关键字

答案 1 :(得分:3)

所有好的答案,但我更喜欢使用MySQL对正则表达式的出色支持:

SELECT `id`, `names` FROM `screenplays` WHERE `names` REGEX 'joe|mike'

要考虑以逗号分隔的名称,以及空白区域使用更高级的正则表达式:

SELECT `id`, `names` FROM `screenplays` WHERE `names` REGEX '(^|,) *(joe|mike) *($|,)'

分解为:

(^|,)       # begin at start of line, or after a comma
 *          # ignore any spaces
(joe|mike)  # names to match
 *          # ignore any spaces
($|,)       # ends at end of line or a comma

请参阅MySQL manual page for REGEX

答案 2 :(得分:2)

SELECT `id`, `names` FROM `screenplays` 
WHERE concat(',', `names`, ',') LIKE '%,mike,%' or concat(',', `names`, ',') LIKE '%,joe,%'

names添加逗号会阻止您在搜索carlton时返回carl

相关问题