Jump to content


Photo

combining results of two tables together


  • Please log in to reply
2 replies to this topic

#1 blakekr

blakekr
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 20 March 2006 - 04:54 PM

I've never seen this done in code, and I can tell I'm making it way too complicated.

What I want to do (might be?) is simple ...

combine table A with table B, namely:

UPDATE hits in items in table B that have hits in table A -- where items already exist in Table B, with a certain amount of recorded previous hits.

That is, add new hits from Table A to existing ones in Table B.

And then ...

INSERT new items/hits in table B that exist in table A but not B

In other words, feed new items that appear in Table A to Table B, with number of hits intact.

I hope I didn't confuse the issue more than necessary.

Any tips / web sites to look at?

THANKS!

#2 wickning1

wickning1
  • Members
  • PipPipPip
  • Advanced Member
  • 405 posts

Posted 20 March 2006 - 06:31 PM

add new hits from Table A to existing ones in Table B
UPDATE B INNER JOIN A ON B.itemid=A.itemid SET B.hits = B.hits + A.hits

INSERT new items/hits in table B that exist in table A but not B
INSERT INTO B (itemid, hits) 
    SELECT A.itemid, A.hits FROM A LEFT JOIN B ON A.itemid=B.itemid WHERE B.itemid IS NULL

The first solution just uses a join in the update query, which is perfectly legal.

The second solution uses the INSERT ... SELECT syntax. It also uses LEFT JOIN and IS NULL, so that it only selects rows from A that don't have a match in B.

#3 blakekr

blakekr
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 20 March 2006 - 07:24 PM

[!--quoteo(post=356697:date=Mar 20 2006, 01:31 PM:name=wickning1)--][div class=\'quotetop\']QUOTE(wickning1 @ Mar 20 2006, 01:31 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
add new hits from Table A to existing ones in Table B
UPDATE B INNER JOIN A ON B.itemid=A.itemid SET B.hits = B.hits + A.hits

INSERT new items/hits in table B that exist in table A but not B
INSERT INTO B (itemid, hits) 
    SELECT A.itemid, A.hits FROM A LEFT JOIN B ON A.itemid=B.itemid WHERE B.itemid IS NULL

The first solution just uses a join in the update query, which is perfectly legal.

The second solution uses the INSERT ... SELECT syntax. It also uses LEFT JOIN and IS NULL, so that it only selects rows from A that don't have a match in B.
[/quote]


WHEW ... thank you SO much for your help. This is about as different as can be from the ugly pseudo-code I was trying to cobble together.

Awesome ... THANKS again.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users