You are on page 1of 10

ExamplesofDIVISIONRELATIONALALGEBRAandSQL

rsisusedwhenwewishtoexpressquerieswithall:
Ex.Whichpersonshavealoyalcustomer'scardatALLtheclothingboutiquesintownX?
WhichpersonshaveabankaccountatALLthebanksinthecountry?
WhichstudentsareregisteredonALLthecoursesgivenbySoini?
WhichstudentsareregisteredonALLthecoursesthataretaughtinperiod1?
WhichboysareregisteredonthosecoursesthataretakenbyALLthegirls?
WhichgirlsareregisteredonALLthecoursestakenbystudentnr.40101?

Inallthesequeriesthedescriptionafter ALL definesasetwithanumberofelements.The


result is composed of those data units (persons, students etc.) who satisfy these
requirements.Thelogicthesesentencesexpressisthatofimplication:forwhichpersonsisit
truethat
IFthereisaclothingboutiqueintownXTHENthepersonhasaloyalcustomer'scardthere,
IFSoinigivesacourseTHENthestudentisregisteredonitor
IF40101isregisteredonacourseTHENthegirlisregisteredonthesamecourse.
Weshallstudythelastexampleindetailhere.Ontheonehandwehavealist(arelation)
withgirlsandthecoursestheyareregisteredon:thiswillbecalledtherelationr.Ontheother
handwehavealist(arelation)ofALLthecoursestakenby40101.Thiswillbetherelations.
NowwewishtoknowwhichofthegirlstakeALLthesecourses.Supposethat40101takes
thefollowingthreecourses:G555,456306and456302.Tobeapartoftheanswerthegirlin
questionmustberegisteredonALLofthesethree.(Inadditiontothatshemayberegistered
onothercoursesnottakenby40101,thesewillnotaffecttheresult.)
In relational algebra the query will be expressed as follows (the example database
kursdatabasisfoundonthehomepageofthiscourse. matr =studentnumber, namn =
name,kurskod=coursecode,kn=sex,kursanmlan=courseregistration):
matr,namn,kurskod(kn='K'(student)|x|kursanmlan)kurskod(

matr = 40101

(kursanmlan))

Theresultwillbearelationwiththeattributesnamnandmatr.Theattributekurskodthatwe
aredividingbywilldisappearinthedivision.
NOTE!WhichpersonshavepassedALLthecoursestheyhaveregisteredon?hasthesame
surfaceform,butadifferentlogic:thesetofcoursesthatistestedwillvaryfromonepersonto
another, depending on which courses the current person has registered on. There is no
commonset ofcoursesthatshouldbetestedforeachperson.TheformulationinSQLwill
oftenbeeasierthanthatusingdivision;toexpresstheexamplequeryitisenoughtocreate

thesetofpersonsregisteredoncoursesandthensubtractthosewhohaveNULLasthevalue
ofsomecoursemark(vitsord,oneoftheattributesin kursanmalan inthesqlcodeofthe
exampledatabase).

WhichfemalestudentstakeALLthecoursesthat40101istaking?
matr,namn,kurskod(kn='K'(student)|x|kursanmlan)

kurskod(

matr namn
up
kn kurskod
================================
40112 Brita
DT
K
456306
40112 Brita
DT
K
456302
40113 AnnHelen DT
K
456304
40113 AnnHelen DT
K
456306
40113 AnnHelen DT
K
456302
40128 Siru
DT
K
G555
40128 Siru
DT
K
456306
40128 Siru
DT
K
456302
40240 Sara
IS
K
456304
40240 Sara
IS
K
456306
40240 Sara
IS
K
456302

matr kurskod
===========
40101 G555
40101 456306
40101 456302

matr,namn,kurskod(kn='K'(student)|x|kursanmlan)kurskod(
matr namn
up
kn kurskod
================================
40112 Brita
DT
K
456306
40112 Brita
DT
K
456302
40113 AnnHelen DT
K
456304
40113 AnnHelen DT
K
456306
40113 AnnHelen DT
K
456302
40128 Siru
DT
K
G555
40128 Siru
DT
K
456306
40128 Siru
DT
K
456302
40240 Sara
IS
K
456304
40240 Sara
IS
K
456306
40240 Sara
IS
K
456302

matr = 40101

matr = 40101

matr kurskod
===========
40101 G555
40101 456306
40101 456302

Wecanseethatonly40128,Siruhasalltherequiredcourses.

(kursanmlan))

(kursanmlan))

rsisdefinedasRS(r)RS((RS(r)s)RS,S(r))

r<matr,namn,kurskod(kn='K'(student)|x|kursanmlan)
s<kurskod( matr = 40101 (kursanmlan))

RS(r)isherematr,namn(r)(Noduplicateelementsinsets!)
RS,S(r)isherematr,namn,kurskod(r),inthiscase=r.Theprojectionwillguaranteethatthe
attributescomeintherightorderforthesubtraction.
RS(r)sisherematr,namn(r)x{G555,456306,456302},i.e.allthepossiblecombinations
ofagirlregisteredonsomecourseandthecoursestakenby40101.Fromthisset
weshallsubtractthosetuplesthatrepresentrealelements(actualcourse
registrations).Fromwhatisleft(thecombinationsrepresentingfalse,
unactualizedinformation,weshallprojectthestudentnumber(matr)andthename
(namn),theattributesrepresentedby(RS).Finallythesewillbesubtractedfrom
matr,namn(r).Theansweriswhatisleft.

RS(r)
==============
40112Brita
40113AnnHelen
40128Siru
40240Sara
SVAR:
=====
40128Siru

Thefalse
candidates
havebeenstricken
through.

RS(r)s(tnkbara)
=====================
40112Brita
G555
40112Brita 456306
40112Brita 456302
40113AnnHelen G555
40113AnnHelen 456306
40113AnnHelen 456302
40128SiruG555
40128Siru456306
40128Siru456302
40240Sara
G555
40240Sara 456306
40240Sara 456302

RS,S(r)(verkliga)
=====================
40112Brita
456306
40112Brita
456302
40113AnnHelen 456304
40113AnnHelen 456306
40113AnnHelen 456302
40128Siru
G555
40128Siru
456306
40128Siru
456302
40240Sara
456304
40240Sara
456306
40240Sara
456302

Thetuplesrepresenting
trueinformationhave
beenstrickenthrough.

(Tuplesthatarenotmarkedwith
greenrepresentreal
informationaboutothercourses
thantherelevantones.)

HowtotranslatethisinMySQL?
Problem:Thereisneitherdivision()norsetdifference()iMySQL,soyouareobligedto
findotherwaysaroundthisproblem.Thereare(atleast)threewaystoexpressthesequeries:
1)Notexists()combinedwithnotin():(Theremaynotbeacoursethat40101takes
thatisnotamongthecoursestakenbythegirlinquestion)
selectdistinctmatr,namn
fromstudentasR
wherekon='K'and
notexists(selectkurskod
fromkursanmalan
wherematr=40101and
kurskodnotin(selectkurskod
from kursanmalanasR2
whereR.matr=R2.matr));
+++
|matr|namn|
+++
|40128|Siru|
+++
1rowinset(0.00sec)
Theoutmostselectionwilldecidewhichcolumns(matr,namn)weshallseeintheresult.The
outmostselectfromwherewillcreateatableincludingallthefemalestudentsand
their course registrations. These students will now be tested one by one: for the female
studenttobepartoftheresult,the notexistsclauseforthisstudentmustbetrue(thelist
afterthenotexistsmustremainempty).
Whatdoesthislistconsistof?Firstweputthereallthecoursesthatthestudent40101is
registeredon(3items:G555,456306and456302).Thesearerepresentedbykurskod.Then
these courses are tested one by one against the courses the current female student is
registered on: a set of her courses is created in the innermost select. These are
representedbykurskod.Thissetisthuscomposedofallthecoursesthatthefemalestudent
isregisteredon.Assoonaswefindakurskodamong40101'scoursesthatisnotamongthe
coursecodesofthecurrentgirl,thiskurskodwillpartoftheselectlistinthemiddle,which
accordinglywillnolongerbeempty.Thisinturnleadstothenotexistsbecomingfalse,and
thatmeansthatthefemalestudentinquestiondoesnotsatisfytherequirements(shedoes
nothaveallthecoursesrequired)andshewillnotbepartoftheresult.Ontheotherhand,if
allthe coursecodes inthe select inthemiddlearefoundinthesetofthe coursecodes
taken by the current female student, this select will stay empty and the not exists will
accordinglybetrue.Nowthisstudentwillbepartoftheresult.

Theexamplequery:
40101'scourses:
G555
456306
456302

Brita's(40112)courses:

456306
456302

AnnHelen's(40113)courses: 456304
456306
456302

G555
456306
456302

G555
456306
456302

Siru's(40128)courses:
G555
456306
456302

Sara's(40240)courses:

456304
456306
456302

G555
456306
456302

G555
456306
456302

Showswhichcourse(s)arelackinginthegirls'selections.Thesecourseswillbepartof
theselectioninthemiddleandmakenotexistsfalse.Ifallthecoursestakenby40101canbe
foundamongthecourseschosenbythegirl,shewillbepartoftheresult.

2)Twotimesnotexists:(Theremaynotbeacoursethat40101takesthatisnottakenby
thecurrentgirl)
selectdistinctmatr,namn
fromstudentasR
wherekon='K'and
notexists(selectkurskod
fromkursanmalanasS
wherematr=40101and
notexists(selectkurskod
fromkursanmalanasR2
whereR.matr=R2.matrand
S.kurskod=R2.kurskod));
+++
|matr|namn|
+++
|40128|Siru|
+++
1rowinset(0.01sec)
Thissolutionisverysimilartothelastone,butnowthetestwithsetmembershipisreplaced
byanothernotexists.Theouternotexistswillchoosethecoursestakenby40101.Theinner
notexists willcontrolthesecoursesonebyone;willwefindthesamecourseforthegirlin
question?Ifthereisakurskod(amongthecoursestakenbythegirl)equaltothekurskod(of
40101'scourses)thatwearetestingatthemoment,this kurskod willbetheresultofthe
innermostselect.Inthiscasethisselectionwillnotbeempty,andtheinner notexists will
thusbefalse.Nowthekurskodwejusttestedwillnotbeapartoftheselectioninthemiddle.
Each kurskod for40101willbetestedlikethis.Ifwecanfindthem all amongthecourses
takenbythegirl,noneofthemwillbeselectedinthemiddleandtheouternotexistswillthus
betrue.Thismeansthatthegirlinquestionhadallthespecifiedcoursesandthatshewill
accordinglybepartoftheresult.Ontheotherhand,ifthereareoneorseveralcoursecodes
thatwillnotfindtheircounterpartintheinnermostselection,thisselectionwillbeemptyfor
them,makingtheinnernotexiststrue.Thesecoursecodeswillbeapartoftheselectinthe
middle, making the outer not exists false, the girl in question (who did not have these
courses)willnotbeapartoftheresult.
Seethefigureonnextpage!

40101'scourses
G555

Brita's(40112)courses

Can'tbefoundchosenbythemiddleselection

456306

456306
456302

456302
AnnHelen's(40113)courses

G555

Can'tbefoundchosenbythemiddleselection

456306

456306

456304

456302

456302
Siru's(40128)courses

G555

G555

456306

456306

456302

456302
Sara's(40240)courses

G555

Can'tbefoundchosenbythemiddleselection

456306

456306

456304

456302

456302

Nextpage!

3)Countandcompare
Theideabehindthismethodistocounthowmanydifferentvaluesthereareinthedivisor(i.
e.allthevaluesthatoneshouldhavetobeapartoftheresult).Whenthisisappliedtoour
examplewefirstcounthowmanycourses40101takes.Thenwecounthowmanyof these
coursesourfemalestudentstake.Ifwegetthesameresult,thegirlinquestionhasallthe
coursesnecessaryandwillappearintheresult.
mysql>selectmatr,namn
fromkursanmalannaturaljoinstudent
wherekon='K'and
kurskodin(selectkurskod
fromkursanmalan
wherematr=40101)
groupbymatr
havingcount(kurskod)=(selectcount(*)
from(selectkurskod
fromkursanmalan
wherematr=40101)astab);
+++
|matr|namn|
+++
|40128|Siru|
+++
1rowinset(0.00sec)
Hereistheresultofkursanmalannaturaljoinstudentwherekon='K'and
kurskodin(selectkurskodfromkursanmalanwherematr=40101):
+++++++
|matr|kurskod|vitsord|namn|up|kon|
+++++++
|40112|456302|NULL|Brita|DT|K|
|40112|456306|NULL|Brita|DT|K|
|40113|456302|NULL|AnnHelen|DT|K|
|40113|456306|NULL|AnnHelen|DT|K|
|40128|456302|NULL|Siru|DT|K|
|40128|456306|NULL|Siru|DT|K|
|40128|G555|NULL|Siru|DT|K|
|40240|456302|NULL|Sara|IS|K|
|40240|456306|NULL|Sara|IS|K|
+++++++
9rowsinset(0.00sec)Nextpage!

Thesetuplesarenowgroupedaccordingtothestudentnumber:
+++++++
|matr|kurskod|vitsord|namn|up|kon|
+++++++
|40112|456302|NULL|Brita|DT|K|
|40112|456306|NULL|Brita|DT|K|
|40113|456302|NULL|AnnHelen|DT|K|
|40113|456306|NULL|AnnHelen|DT|K|
|40128|456302|NULL|Siru|DT|K|
|40128|456306|NULL|Siru|DT|K|
|40128|G555|NULL|Siru|DT|K|
|40240|456302|NULL|Sara|IS|K|
|40240|456306|NULL|Sara|IS|K|
+++++++
havingcount(kurskod) countsthenumberofcoursecodes/group,i.e.thenumberof
courses each of these girls has registered on (note that in this selection we are only
concernedwiththosecoursesthat40101takes;itisquitepossiblethatthegirlsarealso
registeredonothercoursesinadditiontothese).
havingcount(kurskod)=(selectcount(*)
from(selectkurskod
fromkursanmalan
wherematr=40101)astab);
comparesthenumberofcourses/group(thenumberoftherelevantcoursestakenbythegirl
inquestion)withthenumberofcoursestakenby40101(3courses).Ifwegetthe same
number,weknowthatwehavethesamecourses,andthenthegirlwillappearintheresult.
Thishappensintheselectioninthebeginningofthequery:
mysql>selectmatr,namn
fromkursanmalannaturaljoinstudent
wherekon='K'and
kurskodin(selectkurskod
fromkursanmalan
wherematr=40101)
groupbymatr
havingcount(kurskod)=(selectcount(*)
from(selectkurskod
fromkursanmalan

wherematr=40101)astab);
OBS!Herewecanonlyhaveoneregistration/course.Inothercaseswemightneedtouse
countdistincttoeliminateduplicates.
OBS!Itwouldbeanaturalsolutiontouseatemporarytabletorepresentthecoursestakenby

40101.Unfortunately,thesametemporarytablemaynotbeopenedtwiceinMySQL5.1,so
thatsolutionwillonlygiveyouerrormessages.

You might also like