blakekr Posted March 20, 2006 Share Posted March 20, 2006 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 BIn 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! Quote Link to comment https://forums.phpfreaks.com/topic/5353-combining-results-of-two-tables-together/ Share on other sites More sharing options...
wickning1 Posted March 20, 2006 Share Posted March 20, 2006 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 Link to comment https://forums.phpfreaks.com/topic/5353-combining-results-of-two-tables-together/#findComment-19079 Share on other sites More sharing options...
blakekr Posted March 20, 2006 Author Share Posted March 20, 2006 [!--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. Quote Link to comment https://forums.phpfreaks.com/topic/5353-combining-results-of-two-tables-together/#findComment-19113 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.