在MySQL问题中搜索多个值

时间:2012-04-18 03:29:53

标签: mysql search

我正在尝试在数据表中搜索两个关键字,但遇到的问题是,即使我知道有大约36个,以下内容也不会返回任何解决方案。

有人可以帮我写一个更好的查询吗?

SELECT user_id, name, value
FROM data
    INNER JOIN fields ON data.field_id = fields.id 
WHERE name IN ('Type', 'Category')
AND value = 'Keyword 1'
AND value = 'Keyword 2'  /* If I use OR it returns 50 records of those +14 are irrelevant*/
GROUP BY user_id
HAVING COUNT(user_id)>1
ORDER BY value

我错过了什么吗?

3 个答案:

答案 0 :(得分:3)

请注意添加括号:

SELECT user_id, name, value
FROM data
INNER JOIN fields ON data.field_id = fields.id 
WHERE name IN ('Type', 'Category')
AND (value = 'Keyword 1'
OR value = 'Keyword 2') 
GROUP BY user_id
HAVING COUNT(user_id)>1
ORDER BY value

SQL从左到右绑定,所以

WHERE name IN ('Type', 'Category') AND value = 'Keyword 1' OR value = 'Keyword 2'

相当于

WHERE (name IN ('Type', 'Category') AND value = 'Keyword 1') OR value = 'Keyword 2'

这样您就可以看到额外记录的来源 - 所有包含value = 'Keyword 2'的记录都会被包含在内,而与name无关。

当然,你也可以写:

WHERE name IN ('Type', 'Category') AND value IN ('Keyword 1', 'Keyword 2')

消除了优先问题。

答案 1 :(得分:0)

您需要对以下条件进行分组:

WHERE name IN ('Type', 'Category')
AND (value = 'Keyword 1'
    OR value = 'Keyword 2' )

否则MySql将返回具有关键字2但其名称不是Type或Category的行。

或者,请查看Full-Text Search

答案 2 :(得分:0)

试试这个 -

SELECT user_id, name, value
FROM data
    INNER JOIN fields ON data.field_id = fields.id 
WHERE name IN ('Type', 'Category')
AND value in( 'Keyword 1','Keyword 2') 
GROUP BY user_id
HAVING COUNT(user_id)>1
ORDER BY value