0

我正在开发一个在 MySQL 中的基本搜索引擎。搜索是基于关键字的,每个可搜索的项目都有许多与之关联的关键字。每个关键字都有一个与之关联的权重,以确定关键字对项目的“重要性”程度。表格如下所示:

== table: keyword_item ==      
column: item_id (int)
column: keyword (varchar)
column: weight (float)

== table: item ==
column: id (int)
column: title (varchar)
column: url (varchar)

我想要做的是过滤掉权重足够大的项目,我尝试了以下查询:

SELECT item_id, title, url, sum(weight) as w FROM keyword_item INNER JOIN item ON (w > 3 AND (keyword = 'key1' OR keyword = 'key2' OR keyword = 'key3' ) AND item_id = id) GROUP BY item_id ORDER BY w DESC

但这给了我错误:

#1054 - Unknown column 'w' in 'on clause'

我还尝试将 ON 子句中的“w > 3”更改为“sum(weight) > 3”,但这给了我错误:

#1111 - Invalid use of group function

现在,我对 MySQL 的了解并不多,而且我确信对于为什么这不起作用有一个非常好的解释,但我想知道是否有办法实现我想要的。

谢谢!

4

2 回答 2

0

尝试使用HAVING

SELECT item_id, title, url, sum(weight) as w 
FROM keyword_item 
INNER JOIN item ON item_id = id
WHERE  keyword in ('key1', 'key2', 'key3' )
GROUP BY item_id, title, url
HAVING sum(weight) > 3 
ORDER BY w DESC
于 2011-06-14T17:32:40.470 回答
0

我会使用WHEREandHAVING子句而不是将所有内容都放在ON.

SELECT item_id, title, url, sum(weight) as w
FROM keyword_item INNER JOIN item ON item_id = id
WHERE (keyword = 'key1' OR keyword = 'key2' OR keyword = 'key3')
GROUP BY item_id
HAVING w > 3
ORDER BY w DESC
于 2011-06-14T17:38:16.657 回答