You are on page 1of 5

10/6/2016

mysqlImplementingCommentsandLikesindatabaseStackOverflow

signup

login

tour

help

xDismiss

JointheStackOverflowCommunity
Stack Overflow is a community of 4.7 million
programmers, just like you, helping each other.
Join them it only takes a minute:
Signup

ImplementingCommentsandLikesindatabase

I'masoftwaredeveloper.Ilovetocode,butIhatedatabases...Currently,I'mcreatingawebsiteonwhichauserwillbeallowedtomarkanentity
asliked(likeinFB),tagitandcomment.
Igetstuckondatabasetablesdesignforhandlingthisfunctionality.Solutionistrivial,ifwecandothisonlyforonetypeofthing(eg.photos).ButI
needtoenablethisfor5differentthings(fornow,butIalsoassumethatthisnumbercangrow,asthewholeservicegrows).
Ifoundsomesimilarquestionshere,butnoneofthemhaveasatisfyinganswer,soI'maskingthisquestionagain.
Thequestionis,howtoproperly,efficiently andelastically designthedatabase,sothatitcanstorecommentsfordifferenttables ,likes fordifferent
tables andtags forthem.Somedesignpatternasanswerwillbebest)
Detaileddescription:Ihaveatable User withsomeuserdata,and3moretables :
places .Iwanttoenableanyloggeduserto:

Photo

withphotographs ,

Articles

witharticles ,

Places

with

commentonanyofthose3tables
markanyofthemasliked
taganyofthemwithsometag
Ialsowanttocountthenumberoflikesforeveryelementandthenumberoftimesthatparticulartagwasused.
1stapproach:
a)Fortags ,Iwillcreateatable Tag[TagId,tagName,tagCounter] ,thenIwillcreatemanytomany relationshipstables for:
Place_has_tag , Article_has_tag .

Photo_has_tags

b)Thesamecountsforcomments.
c)Iwillcreateatable LikedPhotos[idUser,idPhoto] ,
calculatedbyqueries (which,Iassumeisbad).And...

LikedArticles[idUser,idArticle]

LikedPlace[idUser,idPlace]

.Numberoflikes willbe

Ireallydon'tlikethisdesignforthelastpart,itsmellsbadlyforme)
2ndapproach:
Iwillcreateatable ElementType[idType,TypeName==sometablename] whichwillbepopulatedbytheadministrator(me)withthenamesoftables
thatcanbeliked,commentedortagged.ThenIwillcreatetables :
a) LikedElement[idLike,idUser,idElementType,idLikedElement] andthesameforCommentsandTagswiththepropercolumnsforeach.Now,
whenIwanttomakeaphotolikedIwillinsert:
typeId=SELECTidFROMElementTypeWHERETypeName=='Photo'
INSERT(userid,typeId,photoId)

andforplaces:
typeId=SELECTidFROMElementTypeWHERETypeName=='Place'
INSERT(userid,typeId,placeId)

andsoon...Ithinkthatthesecondapproachisbetter,butIalsofeellikesomethingismissinginthisdesignaswell...

http://stackoverflow.com/questions/8112831/implementingcommentsandlikesindatabase

1/5

10/6/2016

mysqlImplementingCommentsandLikesindatabaseStackOverflow

Atlast,Ialsowonderwhichthebestplacetostorecounterforhowmanytimestheelementwaslikedis.Icanthinkofonlytwoways:
1.inelement(

Photo/Article/Place

)table

2.byselectcount().
Ihopethatmyexplanationoftheissueismorethoroughnow.
mysql database designpatterns databasedesign
editedJun28at12:41

askedNov13'11at16:11

AngelPolitis
3,068

10

Kokos
17

43

345

11

HaveyouconsideredXML?CodyBugsteinApr7'14at16:21

7Answers

Themostextensiblesolutionistohavejustone"base"table(connectedto"likes",tagsand
comments),and"inherit"allothertablesfromit.Addinganewkindofentityinvolvesjustaddinga
new"inherited"tableitthenautomaticallyplugsintothewholelike/tag/commentmachinery.
Entityrelationshiptermforthisis"category"(seetheERwinMethodsGuide,section:"Subtype
Relationships").Thecategorysymbolis:

Assumingausercanlikemultipleentities,asametagcanbeusedformorethanoneentitybuta
commentisentityspecific,yourmodelcouldlooklikethis:

BTW,thereareroughly3waystoimplementthe"ERcategory":
Alltypesinonetable.
Allconcretetypesinseparatetables.
Allconcreteandabstracttypesinseparatetables.
Unlessyouhaveverystringentperformancerequirements,thethirdapproachisprobablythe
best(meaningthephysicaltablesmatch1:1theentitiesinthediagramabove).
editedNov13'11at18:04

answeredNov13'11at16:48

BrankoDimitrijevic
35k

46

92

2 greatanswer,thankyou.Ihope,Iwillmanagetoimplementit...andIwonderhowDjangoORMwillhandle
tomapit(orhowIwilldothatbymyself...but,thatistheotherproblem))But,canyouexplainme,cause

http://stackoverflow.com/questions/8112831/implementingcommentsandlikesindatabase

2/5

10/6/2016

mysqlImplementingCommentsandLikesindatabaseStackOverflow

IthinkIdonotunderstanditproperlywhatyouhavedrawnforme(thanks!)isthethirdapproachyou
mentioned? Kokos Nov13'11at17:05
1 +1thanksforthegreatexplanationandreferenceson"categories".Iwasgoingtopostaquestioncloseto
thisbutyouansweredithere.andyholaday Jul8'12at4:18
1 @BrankoDimitrijevicWhycan'ttheentitytablesPhoto,Article,PlacehavetheirownPKe.g.PhotoID,
ArticleIDetcbutalsohaveanothercolumnfortheEntity_IDasaFK?Isthisunnecessary?volumeone
Sep17'14at21:03
1 @volumeoneTheycan,butisunnecessary.BrankoDimitrijevic Sep17'14at22:44
2 @OrionThemaximumfor BIGINT is9223372036854775807.Assumingyouinsertoneroweachsecond,
youwillrunoutofavailablevaluesin~300billionyears.Surely,youwillbeabletoportto128bitintegers
bythen!BrankoDimitrijevic Oct16'14at13:14

Sinceyou"hate"databases,whyareyoutryingtoimplementone?Instead,solicithelpfrom
someonewholovesandbreathesthisstuff.
Otherwise,learntoloveyourdatabase.Awelldesigneddatabasesimplifiesprogramming,
engineeringthesite,andsmoothsitscontinuingoperation.Evenanexperiencedd/bdesignerwill
nothavecompleteandperfectforesight:someschemachangesdowntheroadwillbeneededas
usagepatternsemergeorrequirementschange.
Ifthisisaonemanproject,programthedatabaseinterfaceintosimpleoperationsusingstored
procedures:add_user,update_user,add_comment,add_like,upload_photo,list_comments,etc.
Donotembedtheschemaintoevenonelineofcode.Inthismanner,thedatabaseschemacan
bechangedwithoutaffectinganycode:onlythestoredproceduresshouldknowaboutthe
schema.
Youmayhavetorefactortheschemaseveraltimes.Thisisnormal.Don'tworryaboutgettingit
perfectthefirsttime.Justmakeitfunctionalenoughtoprototypeaninitialdesign.Ifyouhavethe
luxuryoftime,useitsome,andthendeletetheschemaanddoitagain.Itisalways betterthe
secondtime.
answeredNov13'11at16:21

wallyk
41.9k

48

98

BecauseIneedtoimplementitbymyself.Atleastfornow...and,Ithoughtthatmaybeitisagood

occasiontostartlikingadatabasesalittlebit)Thankyouaboutyoursuggestionwithstoredprocedure.
Dosomeoneknow,iftheyaremappedbyDjangoORMautomatically? Kokos Nov13'11at16:37
2 cannotupvotethisenough:learntoloveyourdatabasebpgergoNov13'11at21:51
1 IloveyourlastsentenceItisalwaysbetterthesecondtime.TresdinJun26'15at15:26
1 Itisalwaysbetterthesecondtime.YupGammerJan25at16:43

Thisisageneralideapleasedontpaymuchattentiontothefieldnamesstyling,butmoretothe
relationandstructure

http://stackoverflow.com/questions/8112831/implementingcommentsandlikesindatabase

3/5

10/6/2016

mysqlImplementingCommentsandLikesindatabaseStackOverflow

ThispseudocodewillgetallthecommentsofphotowithID5
SELECT*FROMactions
WHEREactions.id_Stuff=5
ANDactions.typeStuff="photo"
ANDactions.typeAction="comment"
ThispseudocodewillgetallthelikesoruserswholikedphotowithID5
(youmayusecount()tojustgettheamountoflikes)
SELECT*FROMactions
WHEREactions.id_Stuff=5
ANDactions.typeStuff="photo"
ANDactions.typeAction="like"
answeredNov15'11at3:25

user964260
127

Ithinkyoumayevenlikecomments,as,clickinga"like"linkinacomment.Thisquerywillgetthelikesof
acomment(action)withID133: SELECT*FROMactionsWHEREactions.id=133ANDactions.typeStuff
="comment"ANDactions.typeAction="like" user964260 Nov15'11at3:35

1 Iwilldefinitelyrememberthissolutionforfurtherreleasesofmysystem:) Kokos Nov19'11at23:09


Ihave2stufftablesstuff1andstuff2...Ifollowedthisdiagrambutthereissqlerrorwhileusingthis...stuff1,

stuff2aretwoindependenttableswiththeirindependentprimarykeys,andactiontablehasacolumn
id_stuffwhichisreferencingtothesetwotabelsstuff1,stuff2.Nowforexamplestuff1has5rows,stuff2
has10rows,whenItrytoaddrowinactiontablewithid_stuffanythinglessthan5letssay'3'itexecutes
querybecausethereexistarowwithid_stuff'3'inbothstuff1andstuff2,butifItrytoaddrowwithid_stuff
greaterthan5...(continuetonextcomment)vikasdevdeApr10'13at11:22
andlessthan10letssay'7'itshowserrorbecauseid_stuffinactiontableisreferencingid_stuffin

stuff1,stuff2andeventhoughstuff2hasarowwithstuff_id'7',stuff1doen'thaveit,andasitisreferencing
tostuff1also,itcreatesanerror,howcanIsolvethisproblem?vikasdevdeApr10'13at11:23
4 Howwillthe id_stuff columncontainuniquevaluesineachofthreetables?volumeoneSep16'14at
14:34

asfarasiunderstand.severaltablesarerequired.Thereisamanytomanyrelationbetween
them.
Tablewhichstorestheuserdatasuchasname,surname,birthdatewithaidentityfield.
Tablewhichstoresdatatypes.thesetypesmaybephotos,shares,links.eachtypemust
hasauniquetable.therefore,thereisarelationbetweentheirindividualtablesandthistable.
eachdifferentdatatypehasitstable.forexample,statusupdates,photos,links.
thelasttableisformanytomanyrelationstoringanid,userid,datatypeanddataid.
answeredNov13'11at16:22

erencan
2,484

18

32

Moreorless...maybeIwillexplainitbetterinthenextpost... Kokos Nov13'11at16:39

http://stackoverflow.com/questions/8112831/implementingcommentsandlikesindatabase

4/5

10/6/2016

mysqlImplementingCommentsandLikesindatabaseStackOverflow

ifyoupostyourdatabasediagram.icandrawtherelation. erencan Nov13'11at16:44

Lookattheaccesspatternsyouaregoingtoneed.Doanyofthemseemtomadeparticularly
difficultorinefficientmyonedesignchoiceortheother?
Ifnotfavourtheonethatrequiresthefewertables
Inthiscase:
1.AddComment:youeitherpickaparticularmany/manytableorinsertintoacommontable
withaknownspecificidentifierforwhatisbeingliked,Ithinkclientcodewillbeslightly
simplerinyoursecondcase.
2.Findcommentsforitem:hereitseemsusingacommontableisslightlyeasierwejusthave
asinglequeryparameterisedbytypeofentity
3.Findcommentsbyapersonaboutonekindofthing:simplequeryineithercase
4.Findallcommentsbyapersonaboutallthings:thisseemslittlegnarlyeitherway.
Ithinkyour"discriminated"approach,option2,yieldssimplerqueriesinsomecasesanddoesn't
seemmuchworseintheotherssoI'dgowithit.
answeredNov13'11at16:34

djna
42.3k

53

83

Considerusingtableperentityforcommentsandetc.Moretablesbettershardingandscaling.
It'snotaproblemtocontrolmanysimilartablesforallframeworksIknow.
Onedayyou'llneedtooptimizereadsfromsuchstructure.Youcaneasilycreateagragating
tablesoverbaseonesandloseabitonwrites.
Onebigtablewithdictionarymaybecomeuncontrollableoneday.
answeredNov13'11at17:01

Oroboros102
1,310

13

32

Definitelygowiththesecondapproachwhereyouhaveonetableandstoretheelementtypefor
eachrow,itwillgiveyoualotmoreflexibility.Basicallywhensomethingcanlogicallybedone
withfewertablesitisalmostalwaysbettertogowithfewertables.Oneadvantagethatcomesto
mymindrightnowaboutyourparticularcase,consideryouwanttodeletealllikedelementsofa
certainuser,withyourfirstapproachyouneedtoissueonequeryforeachelementtypebutwith
thesecondapproachitcanbedonewithonlyonequeryorconsiderwhenyouwanttoaddanew
elementtype,withthefirstapproachitinvolvescreatinganewtableforeachnewtypebutwith
thesecondapproachyoushouldn'tdoanything...
answeredNov13'11at17:20

nobody
7,520

http://stackoverflow.com/questions/8112831/implementingcommentsandlikesindatabase

13

30

5/5

You might also like