Jump to content

combining results of two tables together


blakekr

Recommended Posts

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!
Link to comment
https://forums.phpfreaks.com/topic/5353-combining-results-of-two-tables-together/
Share on other sites

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

INSERT new items/hits in table B that exist in table A but not B
[code]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[/code]

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

INSERT new items/hits in table B that exist in table A but not B
[code]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[/code]

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.