Need GROUP BY help

admin

Administrator
Staff member
I am trying to make a query that will find an intersection of two queries and then sort on relevance. I can accomplish both tasks, just not at the same time :(

My problem is easiest to see with the relevance part of the query. Here is an example of a working query (using only the columns needed for this question):

SELECT id,sum(counter) AS relevance
FROM test
GROUP BY id
ORDER BY relevance DESC

The table, test, contains two columns and two rows:
id counter
1 1
1 3

The desired, and actual, output is

id relevance
1 4

However, when I try to combine it with another query which finds a list of id's, I get bad results which can be illustrated by this query:

SELECT DISTINCT b.id, sum(b.counter) AS relevance
FROM test as a, test as b
WHERE a.id=b.id
GROUP BY b.id
ORDER BY relevance DESC

Using the same data as before:
id counter
1 1
1 3

The desired output would be

id relevance
1 4

But instead, counter is 8 because the sum of counter is added twice-- for both rows of table b, intead of one distinct row.

Any ideas how to get only one iteration of test as b? (without breaking it up into two different queries)

Thanks in advance
Tim
 
Back
Top