Tải bản đầy đủ (.pdf) (1,236 trang)

Sybex mastering MySQL 4 ISBN jan 2003 0782141625

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.84 MB, 1,236 trang )

MasteringMySQL4
byIanGilfillan
Sybex©2003(729pages)

ISBN:0782141625

Yourone-stopresourceforallthe
informationyouneedtocreate,maintain,
use,andextendaMySQLdatabase.
TableofContents
MasteringMySQL4
Introduction
PartI-UsingMySQL

Chapter1
Chapter2
Chapter3
Chapter4
Chapter5
Chapter6

- QuickstarttoMySQL
- DataTypesandTableTypes
- AdvancedSQL
IndexesandQuery
Optimization
- ProgrammingwithMySQL
- ExtendingMySQL

PartII-DesigningaDatabase


Chapter7
Chapter8
Chapter9

UnderstandingRelational
Databases
- DatabaseNormalization
- DatabaseDesign
-

PartIII-MySQLAdministration

Chapter10 - BasicAdministration
Chapter11 - DatabaseBackups
Chapter12 - DatabaseReplication
ConfiguringandOptimizing
Chapter13 -


MySQL
Chapter14 - DatabaseSecurity
Chapter15 - InstallingMySQL
Chapter16 - MultipleDrives
PartA-Appendixes

AppendixA - MySQLSyntaxReference
MySQLFunctionandOperator
AppendixB Reference
AppendixC - PHPAPI
AppendixD - PerlDBI

AppendixE - PythonDatabaseAPI
AppendixF - JavaAPI
AppendixG - CAPI
AppendixH - ODBCand.NET
Index
ListofFigures
ListofTables
ListofListings
ListofSidebars


BackCover
MySQLhasprovenitcancompetewiththebignames
indatabasemanagement,suchasSQLServerand
Oracle,andwithMySQL4thisistruerthanever.
MasteringMySQL4isyourone-stopresourceforall
theinformationyouneedtocreate,maintain,use,and
extendaMySQLdatabase.It’salsoessentialreading
foranyonedevelopingdatabaseapplicationsina
MySQLenvironment.Ifyou’renewtoMySQL,thisisa
greatwaytogetupandrunning—fast.Ifyou’re
upgrading,itwillhelpyougetallyoucanoutofnew
featuresandsupport.
CoverageIncludes
InstallingMySQL
Adding,removing,andupdatingrecords
Choosingappropriatetabletypes
Choosingappropriatedatatypes
OptimizingMySQLqueries
Designingadatabase

Normalizingtablestructure
Maintainingandrepairingdatabases
Backingupandreplicatingdata
Managinguserpermissionsandsecurity
OptimizingaMySQLserver
ExtendingMySQL
Developingdatabaseapplications
AbouttheAuthor
IanGilfillanisleaddeveloperforSouthAfrica’spremier


newsportal,IndependentOnline.Healsohas
developedandtaughttechnicalcoursesonMySQL,
databases,programming,andwebdevelopment.The
authorofmanyarticlesondatabasesand
programming,andadeveloperofSouthAfrica’sfirst
onlinegrocerystore,IanhasbeenworkingwithMySQL
since1997.


MasteringMySQL4
IanGilfillan
AssociatePublisher:JoelFugazzotto
AcquisitionsandDevelopmentalEditor:TomCirtin
FreelanceEditor:KimWimpsett
ProductionEditor:DonnaCrossman
TechnicalEditor:CharlieHornberger
GraphicIllustrator:TonyJonick
ElectronicPublishingSpecialists:RoziHarris,BillClark,Interactive
CompositionCorporation

Proofreaders:AmeyGarber,EmilyHsuan,DaveNash,Laurie
O'Connell,YarivRabinovitch,NancyRiddiough,andMoniquevanden
Berg
Indexer:NancyGuenther
BookDesigner:MaureenForys,HappenstanceType-O-Rama
CoverDesigner:DesignSite
CoverIllustrator:TaniaKac,DesignSite
Copyright©2003SYBEXInc.,1151MarinaVillageParkway,Alameda,
CA94501.Worldrightsreserved.Nopartofthispublicationmaybe
storedinaretrievalsystem,transmitted,orreproducedinanyway,
includingbutnotlimitedtophotocopy,photograph,magnetic,orother
record,withouttheprioragreementandwrittenpermissionofthe
publisher.
LibraryofCongressCardNumber:2002111957
ISBN:0-7821-4162-5
SYBEXandtheSYBEXlogoareeitherregisteredtrademarksor
trademarksofSYBEXInc.intheUnitedStatesand/orothercountries.
MasteringisatrademarkofSYBEXInc.
ScreenshotsproducedwithSnagIt6.Copyright1995–2002TechSmith
Corporation.AllRightsReserved.


TRADEMARKS:SYBEXhasattemptedthroughoutthisbookto
distinguishproprietarytrademarksfromdescriptivetermsbyfollowingthe
capitalizationstyleusedbythemanufacturer.
Theauthorandpublisherhavemadetheirbesteffortstopreparethis
book,andthecontentisbaseduponfinalreleasesoftwarewhenever
possible.Portionsofthemanuscriptmaybebaseduponpre-release
versionssuppliedbysoftwaremanufacturer(s).Theauthorandthe
publishermakenorepresentationorwarrantiesofanykindwithregardto

thecompletenessoraccuracyofthecontentshereinandacceptno
liabilityofanykindincludingbutnotlimitedtoperformance,
merchantability,fitnessforanyparticularpurpose,oranylossesor
damagesofanykindcausedorallegedtobecauseddirectlyorindirectly
fromthisbook.
ManufacturedintheUnitedStatesofAmerica
10987654321
SoftwareLicenseAgreement:TermsandConditions
Themediaand/oranyonlinematerialsaccompanyingthisbookthatare
availablenoworinthefuturecontainprogramsand/ortextfiles(the
"Software")tobeusedinconnectionwiththebook.SYBEXhereby
grantstoyoualicensetousetheSoftware,subjecttothetermsthat
follow.Yourpurchase,acceptance,oruseoftheSoftwarewillconstitute
youracceptanceofsuchterms.
TheSoftwarecompilationisthepropertyofSYBEXunlessotherwise
indicatedandisprotectedbycopyrighttoSYBEXorothercopyright
owner(s)asindicatedinthemediafiles(the"Owner(s)").Youarehereby
grantedasingle-userlicensetousetheSoftwareforyourpersonal,
noncommercialuseonly.Youmaynotreproduce,sell,distribute,publish,
circulate,orcommerciallyexploittheSoftware,oranyportionthereof,
withoutthewrittenconsentofSYBEXandthespecificcopyrightowner(s)
ofanycomponentsoftwareincludedonthismedia.
IntheeventthattheSoftwareorcomponentsincludespecificlicense
requirementsorend-useragreements,statementsofcondition,


disclaimers,limitationsorwarranties("End-UserLicense"),thoseEndUserLicensessupersedethetermsandconditionshereinastothat
particularSoftwarecomponent.Yourpurchase,acceptance,oruseofthe
SoftwarewillconstituteyouracceptanceofsuchEnd-UserLicenses.
Bypurchase,useoracceptanceoftheSoftwareyoufurtheragreeto

complywithallexportlawsandregulationsoftheUnitedStatesassuch
lawsandregulationsmayexistfromtimetotime.
ReusableCodeinThisBook
Theauthor(s)createdreusablecodeinthispublicationexpresslyfor
reusebyreaders.Sybexgrantsreaderslimitedpermissiontoreusethe
codefoundinthispublication,itsaccompanyingCD-ROMoravailablefor
downloadfromourwebsitesolongastheauthor(s)areattributedinany
applicationcontainingthereusablecodeandthecodeitselfisnever
distributed,postedonlinebyelectronictransmission,sold,or
commerciallyexploitedasastand-aloneproduct.
SoftwareSupport
ComponentsofthesupplementalSoftwareandanyoffersassociated
withthemmaybesupportedbythespecificOwner(s)ofthatmaterial,but
theyarenotsupportedbySYBEX.Informationregardinganyavailable
supportmaybeobtainedfromtheOwner(s)usingtheinformation
providedintheappropriateread.mefilesorlistedelsewhereonthe
media.
Shouldthemanufacturer(s)orotherOwner(s)ceasetooffersupportor
declinetohonoranyoffer,SYBEXbearsnoresponsibility.Thisnotice
concerningsupportfortheSoftwareisprovidedforyourinformationonly.
SYBEXisnottheagentorprincipaloftheOwner(s),andSYBEXisinno
wayresponsibleforprovidinganysupportfortheSoftware,norisitliable
orresponsibleforanysupportprovided,ornotprovided,bytheOwner(s).
Warranty
SYBEXwarrantstheenclosedmediatobefreeofphysicaldefectsfora
periodofninety(90)daysafterpurchase.TheSoftwareisnotavailable


fromSYBEXinanyotherformormediathanthatenclosedhereinor
postedtowww.sybex.com.Ifyoudiscoveradefectinthemediaduring

thiswarrantyperiod,youmayobtainareplacementofidenticalformatat
nochargebysendingthedefectivemedia,postageprepaid,withproofof
purchaseto:
SYBEXInc.
ProductSupportDepartment
1151MarinaVillageParkway
Alameda,CA94501
Web:
Afterthe90-dayperiod,youcanobtainreplacementmediaofidentical
formatbysendingusthedefectivedisk,proofofpurchase,andacheck
ormoneyorderfor$10,payabletoSYBEX.
Disclaimer
SYBEXmakesnowarrantyorrepresentation,eitherexpressedor
implied,withrespecttotheSoftwareoritscontents,quality,performance,
merchantability,orfitnessforaparticularpurpose.Innoeventwill
SYBEX,itsdistributors,ordealersbeliabletoyouoranyotherpartyfor
direct,indirect,special,incidental,consequential,orotherdamages
arisingoutoftheuseoforinabilitytousetheSoftwareoritscontents
evenifadvisedofthepossibilityofsuchdamage.Intheeventthatthe
Softwareincludesanonlineupdatefeature,SYBEXfurtherdisclaimsany
obligationtoprovidethisfeatureforanyspecificdurationotherthanthe
initialposting.
Theexclusionofimpliedwarrantiesisnotpermittedbysomestates.
Therefore,theaboveexclusionmaynotapplytoyou.Thiswarranty
providesyouwithspecificlegalrights;theremaybeotherrightsthatyou
mayhavethatvaryfromstatetostate.Thepricingofthebookwiththe
SoftwarebySYBEXreflectstheallocationofriskandlimitationson
liabilitycontainedinthisagreementofTermsandConditions.
SharewareDistribution
ThisSoftwaremaycontainvariousprogramsthataredistributedas



shareware.Copyrightlawsapplytobothsharewareandordinary
commercialsoftware,andthecopyrightOwner(s)retainsallrights.Ifyou
tryasharewareprogramandcontinueusingit,youareexpectedto
registerit.Individualprogramsdifferondetailsoftrialperiods,
registration,andpayment.Pleaseobservetherequirementsstatedin
appropriatefiles.
CopyProtection
TheSoftwareinwholeorinpartmayormaynotbecopy-protectedor
encrypted.However,inallcases,resellingorredistributingthesefiles
withoutauthorizationisexpresslyforbiddenexceptasspecifically
providedforbytheOwner(s)therein.
ForSuperbabeandmyparents!
Acknowledgments
Thisismyfirstbook,buthavingwrittennumerousarticles,Ithoughta
bookwouldbelikeabigarticle.Afewhundredpagesandmanygray
hairslater,Iknowthetruth.Thisbookwouldneverhavebeenpossible
withoutthemanypeoplewhohelpedmealongtheway.First,thanksto
AniquevanderVlugtforinstallingsoftware,testingcode,proofreading
manyofthechapters,andkeepingthebedwarmonthoselong,lonely
nights.Second,thankstoBobMeredithforsettingupatestserveron
shortnoticeandconstantlyaskingformorefromthebook.Thanksalsoto
RushdiSalieandWebFactoryforintroducingmetoMySQLallthose
yearsagoandtoPieterClaassenforhispassionwithLinux,MySQL,
Python,andPerllongbeforeitwasfashionable.Thankstomyemployers
IOLfornotclock-watchingtoomuchwhileIwrotethisbook.Thanksto
TechnicalEditorCharlieHornbergerforsomesuperbcomments,and
thankstoallthoseatSybexwhohelpedmakethebookwhatitis:
DevelopmentalEditorTomCirtin,whowasfirsttobiteandwhoacquired

thebook,ProductionEditorDonnaCrossman,EditorKimWimpsett,
AssociatePublisherJoelFugazzotto,IllustratorTonyJonickformaking
senseofmyscrawlings,CompositionCoordinatorRoziHarris,and
CompositorBillClark,aswellasProofreadersAmeyGarber,Emily
Hsuan,DaveNash,LaurieO'Connell,YarivRabinovitch,Nancy


Riddiough,andMoniquevandenBerg,andIndexerNancyGuenther.
And,ofcourse,thankstoMySQLABforagreatproduct.


Introduction
MySQLhasgrownup.Oncedismissedasalightweighttoyforwebsites,
MySQL4isnowaviablemission-criticaldata-managementsolution.
Whereasbeforeitwastheidealchoiceforwebsites,nowitcontains
manyofthefeaturesneededinotherenvironments,allwhilemaintaining
itsimpressivespeed.Ithaslongbeenabletooutperformmany
commercialsolutionsforrawspeedandhasanelegantandpowerful
permissionssystem,butnowversion4hastheACID-compliantInnoDB
transactionalstorageengine.
MySQL4isfaster,hasonlinebackupfacilities,andhasamultitudeof
newfeatures.ThereislittlereasonnottoconsiderMySQLforyour
databasesolution.MySQLAB,thecompanybehindMySQL,offers
efficientandlow-costsupport,and,likemostopen-sourcecommunities,
you'llfindlotsoffreesupportontheWeb.Standardfeaturesnotyet
includedinMySQL(suchasviewsandstoredprocedures)arecurrently
underdevelopmentandmayevenbereadybythetimeyoureadthis
book.
TherearemanyimportantreasonstochooseMySQLasyourmissioncriticaldata-managementsolution:
CostMySQLisfreeformostpurposes,anditssupportis

inexpensive.
SupportMySQLABoffersinexpensivesupportcontracts,and
there'salargeandactiveMySQLcommunity.
SpeedMySQLoutperformsmostofitsrivals.
FunctionalityMySQLoffersmostofthefeaturesseriousdevelopers
require,suchasfullACIDcompliance,supportformostofANSI
SQL,onlinebackups,replication,SecureSocketsLayer(SSL)
support,andintegrationwithalmostallprogrammingenvironments.
Also,itisbeingdevelopedandupdatedfasterthanmanyofitsrivals,
soalmostallofthe"standard"featuresMySQLdoesnotyethave
areunderdevelopment.


PortabilityMySQLrunsonthevastmajorityofoperatingsystems,
andinmostcasesdatacanbetransferredfromonesystemto
anotherwithoutdifficulty.
EaseofuseMySQLiseasytouseandadminister.Manyolder
databasessufferfromlegacyissues,makingadministration
needlesslycomplex.MySQL'stoolsarepowerfulandflexiblewithout
sacrificingusability.


WhoShouldBuyThisBook?
Thisbookisfordevelopers,databaseadministrators(DBAs),andMySQL
users.Itcontainsthefollowingtopics:
ExploringStructuredQueryLanguage(SQL)asimplementedby
MySQL.
Understandingandusingthedataandtabletypes.
Optimizingyourqueriesandindexes.
Backingupthedatabase.

Managingusersandsecurity.
AdministeringandconfiguringMySQL(andoptimizingthe
configurationforperformance).
ReplicatingMySQLontomultipleservers.
Understandingdatabasedesignanddatabasenormalization,and
walkingyouthroughacompletecasestudy.Knowledgeofthis
topicisvitalifyouplantouseMySQLinseriousapplications.
ProgrammingwithMySQL.
WritingyourownextensionstoMySQL.
InstallingMySQL.
Thebook'sappendixescontainthefollowing:
AthoroughMySQLreference
ReferencescontainingPHP,Perl,C,Java,Python,andODBC
functionsandmethodsforinteractingwithMySQL


WhatNottoExpectfromThisBook
MySQLisavasttopic,andthisbookcoverseverythingyouneedto
becomeaskilledMySQLDBAanddeveloper.However,itcannotexplain
everything,soitdoesnotcontainthefollowingtopics:
Howtoprogram.Thisbookassistsyouinprogrammingwith
MySQL,butitwillnotteachyouhowtoprogramfromthe
beginning.
EmbeddedMySQL.
Thoroughcoverageofhowtocompileandinstalllibraries.Writing
yourownextensionsrequiressomeknowledgeofcompilingand
installinglibrariesonyourplatform.Althoughthistopicis
explained,thebookcannotcoverallpossibleconfigurationson
allplatforms,soifyouplantogettothisadvancedlevel,you'll
needagoodsourceofinformationaboutyourplatform.



WhatDoYouNeed?
You'llneedthefollowingtoworkthroughtheexamplesinthisbook:
Acopyof,oraccessto,aMySQLclientandserver.Youcan
downloadthecurrentversionfromtheMySQLsite:
www.mysql.com.
AsystemonwhichtoinstallMySQL(ifyoudon'thaveaccessto
onealready).MySQLcaninstallonyourdesktopPC,butmore
oftenitrunsonadedicatedserverwhenitisusedinserious
applications.
IfyouplantodevelopapplicationswithMySQL,youmayneedto
downloadthelatestdriversorapplicationprogramminginterfaces
(APIs)foryourdevelopmentenvironment.MySQLintegratesbest
withPHP,Perl,Java,C,C++,andPython,butyoucanuseitin
anyprogrammingenvironment,suchas.NETviaOpenDatabase
Connectivity(ODBC).VisittheMySQLwebsite
(www.mysql.com)todownloadcurrentversionsofthedrivers.


HowtoUseThisBook
Thisbookisdividedintofourparts.Ifyou'renewtodatabases,thebest
placetostartisPartI,"UsingMySQL,"andspecificallyChapter1,
"QuickstarttoMySQL,"whicheasesnoviceusersintotheworldofSQL.
Readersexperiencedinotherdatabasemanagementsystemsmaywant
togiveChapter1aquickreadtofamiliarizethemselveswiththeway
MySQLdoesthings,beforeexploringtheMySQLdataandtabletypesin
detailinChapter2,"DataTypesandTableTypes."Readersofan
intermediatelevelcanstartwithChapter3,"AdvancedSQL,"and
Chapter4,"IndexesandQueryOptimization,"whichlookatadvanced

SQL,indexes,andoptimization.Readerswantingtouseaprogramming
languagewithMySQLshouldreadChapter5,"Programmingwith
MySQL,"andalsolookattheappendixrelevanttotheirlanguage.
Chapter6,"ExtendingMySQL,"isforthosereaderswhounderstand
MySQLandwanttoaddtheirownfunctionstoit.
ReaderswithoutformaldatabasedesignknowledgewillbenefitfromPart
II,"DesigningaDatabase,"whichcoverstheoften-ignoreddatabase
designissuesrequiredfordevelopinglarge-scaledatabases.
AnyreaderswantingtoadministerMySQLwillbenefitfromPartIII,
"MySQLAdministration,"whichprogressesfromthebasicsfornewusers
totheadvancedissuesforoptimizinghigh-performancedatabases.It
alsoexplainsbackups,replication,security,andinstallation.
Finally,youshouldturntotheappendixeswhenyouneedMySQLSQL,
function,andoperatorreferences,aswellasreferencestothedatabase
functionsandmethodsusedbymostpopularprogramminglanguages.
Allsamplecodeisavailablefordownloadatwww.sybex.com.


HowtoContacttheAuthor
Forerrata,pleasechecktheSybexwebsite(www.sybex.com)first.Feel
freetocontacttheauthorwithanyqueriesat
,andI'lldowhatIcantohelpoutorpoint
youintherightdirection.


PartI:UsingMySQL


ChapterList
Chapter1:QuickstarttoMySQL

Chapter2:DataTypesandTableTypes
Chapter3:AdvancedSQL
Chapter4:IndexesandQueryOptimization
Chapter5:ProgrammingwithMySQL
Chapter6:ExtendingMySQL


Chapter1:QuickstarttoMySQL


Overview
So,you'veobtainedacopyofthisbook.Someofyoumaybecompetent
withMySQLalreadyandwanttodiveintothemurkywatersofdatabase
replicationoroptimizingtheservervariables.Ifyou'reanadvanceduser,
feelfreetojumpahead.Thischapterisnotforyou.Butbeginnersneed
notworry.Thisbookalsocontainseverythingyouneedtogetstartedand
eventuallybecomeanadvanceduser.
MySQListheworld'smostpopularopen-sourcedatabase.Opensource
meansthatthesourcecode,theprogrammingcodethatmakesup
MySQL,isfreelyavailabletoanyone.Peopleallovertheworldcanadd
toMySQL,fixbugs,makeimprovements,orsuggestoptimizations.And
theydo.MySQLhasdevelopedfrombeinga"toy"databaseafewyears
agointoagrown-upversion4,havingovertakenmanycommercial
databasesalongtheway—andterrifiedmostoftheotherdatabase
manufacturers.It'sgrownsoquicklybecauseofthecountlessdedicated
peoplewhohavecontributedtotheprojectinsomeway,aswellasthe
dedicationoftheMySQLteam.
Unlikeproprietaryprojects,wherethesourcecodeiswrittenbyafew
peopleandcarefullyguarded,open-sourceprojectsexcludenoonewho
isinterestedincontributingiftheyarecompetentenough.In2000when

MySQLwasayoungupstartoffouryearsold,Michael"Monty"Widenius,
thefounderofMySQL,predictedbigthingsforMySQLasheattended
thefirst-everopen-sourcedatabaseconvention.Manyestablished
databasevendorsscoffedatthetime.Someofthosevendorsareno
longeraround.
Withversion3,MySQLdominatedthelowendoftheInternetmarket.
AndwithMySQL'sreleaseofversion4,theproductisnowappealingtoa
muchwiderrangeofcustomers.Withtheopen-sourceApache
dominatingthewebservermarketandvariousopen-sourceoperating
systems(suchasLinuxandFreeBSD)performingstronglyintheserver
market,MySQL'stimehascomeinthedatabasemarket.


Featuredinthischapter:
Essentialdatabaseconceptsandterminology
ConnectingtoanddisconnectingfromMySQLserver
Creatinganddroppingdatabases
Creating,updating,anddroppingtables
Addingdataintoatable
Returningdataanddeletingdatafromatable
Understandingbasicstatisticalanddatefunctions
Joiningmorethanonetable


UnderstandingMySQLBasics
MySQLisarelationaldatabasemanagementsystem(RDBMS).It'sa
programcapableofstoringanenormousamountandawidevarietyof
dataandservingituptomeettheneedsofanytypeoforganization,from
mom-and-popretailestablishmentstothelargestcommercialenterprises
andgovernmentalbodies.MySQLcompeteswithwell-knownproprietary

RDBMSs,suchasOracle,SQLServer,andDB2.
MySQLcomeswitheverythingneededtoinstalltheprogram,setup
differinglevelsofuseraccess,administerthesystem,andsecureand
backupthedata.Youcandevelopdatabaseapplicationsinmost
programminglanguagesusedtodayandrunthemonmostoperating
systems,includingsomeofwhichyou'veprobablyneverheard.MySQL
utilizesStructuredQueryLanguage(SQL),thelanguageusedbyall
relationaldatabases,whichyou'llmeetlaterinthischapter(seethe
sectiontitled"CreatingandUsingYourFirstDatabase").SQLenables
youtocreatedatabases,aswellasadd,manipulate,andretrievedata
accordingtospecificcriteria.
ButI'mgettingaheadofmyself.Thischapterprovidesabriefintroduction
torelationaldatabaseconcepts.You'lllearnexactlywhatarelational
databaseisandhowitworks,aswellaskeyterminology.Armedwiththis
information,you'llbereadytojumpintocreatingasimpledatabaseand
manipulatingitsdata.

WhatIsaDatabase?
Theeasiestwaytounderstandadatabaseisasacollectionofrelated
files.Imagineafile(eitherpaperorelectronic)ofsalesordersinashop.
Thenthere'sanotherfileofproducts,containingstockrecords.Tofulfill
anorder,you'dneedtolookuptheproductintheorderfileandthenlook
upthestocklevelsforthatparticularproductintheproductfile.A
databaseandthesoftwarethatcontrolsthedatabase,calledadatabase
managementsystem(DBMS),helpswiththiskindoftask.Most
databasestodayarerelationaldatabases,namedsuchbecausethey
dealwithtablesofdatarelatedbyacommonfield.Forexample,Table


1.1showstheProducttable,andTable1.2showstheInvoicetable.As

youcansee,therelationbetweenthetwotablesisbasedonthe
commonfieldstock_code.Anytwotablescanrelatetoeachother
simplybyhavingafieldincommon.
Table1.1:TheProductTable
Stock_code

Description

Price

A416

Nails,box

$0.14

C923

Drawingpins,box

$0.08

Table1.2:TheInvoiceTable
Invoice_code Invoice_line Stock_code Quantity
3804

1

A416


10

3804

2

C923

15

DatabaseTerminology
Let'stakeacloserlookattheprevioustwotablestoseehowtheyare
organized:
Eachtableconsistsofmanyrowsandcolumns.
Eachrowcontainsdataaboutonesingleentity(suchasone
productoroneorder).Thisiscalledarecord.Forexample,the
firstrowinTable1.1isarecord;itdescribestheA416product,
whichisaboxofnailsthatcosts14cents.Toreiterate,theterms
rowandrecordareinterchangeable.
Eachcolumn(alsocalledatuple)containsonepieceofdatathat
relatestotherecord,calledanattribute.Examplesofattributes
arethequantityofanitemsoldorthepriceofaproduct.An
attribute,whenreferringtoadatabasetable,iscalledafield.For
example,thedataintheDescriptioncolumninTable1.1are
fields.Toreiterate,thetermsattributeandfieldare


interchangeable.
Giventhiskindofstructure,thedatabasegivesyouawaytomanipulate
thisdata:SQL.SQLisapowerfulwaytosearchforrecordsormake

changes.AlmostallDBMSsuseSQL,althoughmanyhaveaddedtheir
ownenhancementstoit.ThismeansthatwhenyoulearnaboutSQLin
thischapterandinmoredetailinlaterchapters,youaren'tlearning
somethingspecifictoMySQL.Mostofwhatyoulearncanbeusedon
anyotherrelationaldatabase,suchasPostgreSQL,Oracle,Sybase,or
SQLServer.ButaftertastingthebenefitsofMySQL,youprobablywon't
wanttochange!


×