Search code examples
mysqljoingroup-bymysql-error-1111

Constraints on SUM function in MySQL query


I'm working on developing a basic search engine in MySQL. the search is based on keywords, and each searchable item has a number of keywords associated with it. Each keyword has a weight associated with it, to determine how "Important" the keyword is for the item. The tables look like this:

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

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

What I want to do is filter out items that has a large anough sum of weights, and I have tried the following query:

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

But that gives me the error:

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

I also tried changing the "w > 3" in the ON clause to "sum(weight) > 3", but then that gives me the error:

#1111 - Invalid use of group function

Now, I don't really know much about MySQL, and I'm sure there is a perfectly good explanation as to why this isn't working, but I would like to know whether there is a way to achieve what I want.

Thanks!


Solution

  • I'd use WHERE and HAVING clauses instead of putting everything in the 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