views:

61

answers:

6

If I am creating temporary tables, that have 2 columns. id and score. I want to to add them together.

The way I want to add them is if they each contain the same id then I do not want to duplicate the id but instead add the scores together.

if I have 2 temp tables called t1 and t2

and t1 had:

id 3 score 4
id 6 score 7

and t2 had:

id 3 score 5
id 5 score 2

I would end up with a new temp table containing:

id 3 score 9
id 5 score 2
id 6 score 7

The reason I want to do this is, I am trying to build a product search. I have a few algorithms I want to use, 1 using fulltext another not. And I want to use both algorithms so I want to create a temporary table based on algorithm1 and a temp table based on algorithm2. Then combine them.

+1  A: 

Perform a full outer join on the ID. Select on the ID and the sum of the two "score" columns after coalescing the values to 0.

pst
Correct - except I don't think MySQL supports full outer joins. You'd have to union a right and a left join.
Alex Humphrey
+4  A: 

How about:

SELECT id, SUM(score) AS score FROM (
  SELECT id, score FROM t1
  UNION ALL
  SELECT id, score FROM t2
) t3
GROUP BY id
Tom
15 seconds ahead of me!
Brendan Bullen
You will need to alias the nested select though and there's a mistake in the brackets
Brendan Bullen
@Brendan: You got the syntax right, but Tom got the UNION ALL right. Go teamwork!
Justin K
@Justin The system works!
Brendan Bullen
Yes the system works, but then who deserves the accepted answer!?!?
John Isaacks
@Brendan the system doesn't really work -- your answer is getting the up votes :-)
Tom
@Tom I voted for you. You were first!
Brendan Bullen
@Brendan you are a gent. Thanks.
Tom
+2  A: 

This is untested but you should be able to perform a union on the two tables and then perform a select on the results, grouping the fields and adding the scores

SELECT id,SUM(score) FROM
(
    SELECT id,score FROM t1
    UNION ALL
    SELECT id,score FROM t2
) joined
GROUP BY id
Brendan Bullen
you must use UNION ALL in case an entry in exists in t1 and t2 with the same id and score.
Tom
excellent point
Brendan Bullen
A: 
select id, sum(score)
from (
 select * from table 1
 union all
 select * from table2
) tables
group by id
umassthrower
hmm, you guys are fast... but mine is correct.Brendan you need to use UNION ALLtom you ahev a syntax error and you need to alias the subquery
umassthrower
p. s. I'm fairly new to S.O, how do you quote code?
umassthrower
@umassthrower you highlight the code, then click the button that looks like binary code.
John Isaacks
excellent, thanks
umassthrower
A: 
SELECT id, SUM(score) FROM
(
    SELECT id, score FROM #t1
    UNION ALL
    SELECT id, score FROM #t2
) AS Temp
GROUP BY id
capn
A: 

You need to create an union of those two tables then You can easily group the results.

SELECT id, sum(score) FROM 

(
 SELECT id, score FROM t1
 UNION 
 SELECT id, score FROM t2
) as tmp
GROUP BY id;
Vash