0

我正在尝试在数据表中搜索两个关键字,但遇到了以下问题,即使我知道大约有 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

我错过了什么吗?

4

3 回答 3

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')

这消除了优先级问题。

于 2012-04-18T03:33:25.620 回答
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
于 2012-04-18T07:09:19.433 回答
0

您需要对条件进行分组,如下所示:

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

否则 MySql 将返回具有关键字 2 但名称不是类型或类别的行。

或者,查看全文搜索

于 2012-04-18T03:32:45.090 回答