Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Apples
Posting Yak Master
146 Posts |
Posted - 2008-10-17 : 17:43:29
|
| Here's my schema and data:------------------------------------------------tblEntries------------------------------------------------EntryID | CommentCount------------------------------------------------1 | 02 | 0------------------------------------------------------------------------------------------------tblComments------------------------------------------------CommentID | EntryID------------------------------------------------1 | 12 | 13 | 2------------------------------------------------I want to update the CommentCount for entries in tblEntries by passing in the CommentID's.Here is my query:UPDATE tblEntriesSET CommentCount = CommentCount + 1WHERE EntryID IN (SELECT EntryIDFROM tblCommentsWHERE CommentID IN (1,2,3))The subquery returns:112But when it goes to update the entries, Entry 1 only gets the CommentCount updated to 1 instead of 2. I assume it is because the 'WHERE EntryID IN (' clause doesn't deal with duplicates? |
|
|
raky
Aged Yak Warrior
767 Posts |
Posted - 2008-10-18 : 01:17:19
|
| Try thisDECLARE @temp TABLE ( cnt INT, entryid int)INSERT INTO @tempSELECT COUNT(CommentID), entryidFROM tblCommentsGROUP BY entryidUPDATE teSET CommentCount = CommentCount + cntFROM tblEntries teinner join @temp tc on ( tc.entryid = te.entryid)SELECT * FROM tblEntries |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-10-18 : 01:54:36
|
or simply without using temp tableUPDATE tSET t.CommentCount=t.CommentCount+c.cntFROM tblEntries tINNER JOIN (SELECT COUNT(CommentID) AS cnt,EntryID FROM tblComments GROUP BY EntryID)cON c.EntryID=t.EntryID |
 |
|
|
|
|
|