MySQL查询中SUM函数的约束

时间:2011-06-14 17:30:39

标签: mysql join group-by mysql-error-1111

我正在开发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并不是很了解,我确信有一个非常好的解释,为什么这不起作用,但我想知道是否有办法实现我的目标想。

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我会使用WHEREHAVING条款,而不是将所有内容都放在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