Tải bản đầy đủ (.pdf) (601 trang)

Sams teach yourself MySQL in 10 minutes may 2006 ISBN 0672328631

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 (2.38 MB, 601 trang )

SamsTeachYourselfMySQL®in10Minutes
ByChrisNewman
...............................................
Publisher:Sams
PubDate:May09,2006
PrintISBN-10:0-672-32863-1
PrintISBN-13:978-0-672-32863-3
Pages:288

TableofContents|Index

SamsTeachYourselfMySQLin10Minutesprovidesano-fluff,just-the-answersguideto
buildingandmanagingMySQLdatabases.Itiscarefullyorganizedandthoughtfullywritten
toprovidejusttheinformationthatyouneedinordertogainarapidworkingknowledge
ofMySQL.GetuptospeedquicklywithSamsTeachYourselfMySQLin10Minutes.


SamsTeachYourselfMySQL®in10Minutes
ByChrisNewman
...............................................
Publisher:Sams
PubDate:May09,2006
PrintISBN-10:0-672-32863-1
PrintISBN-13:978-0-672-32863-3
Pages:288

TableofContents|Index
















































Copyright
AbouttheAuthor
Introduction
Part1:MySQLFoundations
Lesson1.IntroducingMySQL
DatabaseBasics
MySQLComponents
Summary
Lesson2.UsingMySQL
ThemysqlClient
ExecutingSQLStatements
CreatingtheSampleTables
Summary
Part2:GettingStartedwithSQL
Lesson3.RetrievingData
TheSELECTStatement
Summary
Lesson4.FilteringandSortingData

TheWHEREClause
TheORDERBYClause
Summary
Lesson5.AdvancedDataFiltering
CombiningWHEREClauses
LimitingtheNumberofRowsReturned



















































































Summary
Lesson6.NumericOperatorsandFunctions
NumericOperators

NumericFunctions
ConditionalFunctions
Summary
Lesson7.StringOperatorsandFunctions
UsingOperatorswithStrings
StringFunctions
Summary
Lesson8.DateOperatorsandFunctions
DateOperators
DateFunctions
Summary
Lesson9.SummarizingData
AggregateFunctions
GroupingData
FilteringSummaryData
Summary
Part3:AdvanceSQL
Lesson10.UsingSubqueries
UnderstandingSubqueries
Summary
Lesson11.JoiningTables
UnderstandingJoins
Summary
Lesson12.CreatingAdvancedJoins
TheJOINKeyword
InnerJoins
JoiningMultipleTables
CrossJoins
Self-Joins
NaturalJoins

OuterJoins
Summary
Lesson13.CombiningQueries
UnderstandingCombinedQueries
OtherCompoundOperations
UsingTemporaryTables



















































































Summary
Part4:CreatingaNewDatabase
Lesson14.CreatingandModifyingTables

CreatingaNewDatabase
CharacterSetsandCollations
AlteringaDatabase
DroppingaDatabase
ManagingTables
TemporaryTables
UsingaQuerytoCreateaTable
StorageEngines
AlteringTables
DroppingTables
Summary
Lesson15.WorkingwithData
TheINSERTStatement
TheDELETEStatement
TheUPDATEStatement
TheREPLACEStatement
LoadingDatafromaFile
WhyUseTransactions?
TransactionsinMySQL
AutocommitMode
RollingBackaTransaction
Summary
Lesson16.DesigningYourDatabase
Relationships
Normalization
NamingTablesandColumns
DataTypes
CHARandVARCHAR
Summary
Lesson17.KeysandIndexes

UnderstandingKeysandIndexes
UsingIndexesinMySQL
Summary
Lesson18.ManagingUserAccess
UnderstandingMySQLAuthentication
UserManagement









































































UsingWildcards
Summary
Part5:NewFeaturesinMySQL5.0
Lesson19.Views
UnderstandingViews
Summary
Lesson20.StoredRoutines
UnderstandingStoredRoutines
Summary
Lesson21.Triggers
UnderstandingTriggers
UsingTriggers
Summary

Part6:InterfacingwithMySQL
Lesson22.UsingODBC
UnderstandingODBC
ConnectingtoMyODBC
Summary
Lesson23.UsingMySQLwithC
TheCLanguageAPI
Summary
Lesson24.UsingMySQLwithPHP
UsingthemysqlAPI
UsingthemysqliAPI
Summary
Lesson25.UsingMySQLwithPerl
ThePerlDBI
UsingtheMySQLDBD
Summary
Part7:Appendix
AppendixA.InstallingMySQL
ObtainingMySQL
Linux/UNIXInstallation
WindowsInstallation
AppendixB.SampleTableScripts
Index


Copyright
SamsTeachYourselfMySQL®in10Minutes
Copyright©2006bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,

electronic,mechanical,photocopying,recording,orotherwise,
withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2005328631
PrintedintheUnitedStatesofAmerica
FirstPrinting:May2006
090807064321

Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.

WarningandDisclaimer


Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.Theauthorand
thepublishershallhaveneitherliabilitynorresponsibilitytoany
personorentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbook.


BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales
1-800-382-3419

ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales

ACQUISITIONSEDITOR
ShelleyJohnston
DEVELOPMENTEDITOR
DamonJordan
MANAGINGEDITOR
CharlotteClapp


PROJECTEDITOR
AndyBeaster
COPYEDITOR
KristaHansing
INDEXER
JuliBess
PROOFREADER
KathyBidwell
TECHNICALEDITOR
AdamDeFields
PUBLISHING

COORDINATOR
VanessaEvans
INTERIORDESIGNER
GaryAdair
COVERDESIGNER
ArenHowell


PAGELAYOUT
NonieRatcliff


AbouttheAuthor
ChrisNewmanisaconsultantprogrammerwhospecializesin
databasedevelopmentwithanInternettwist.Hehasextensive
commercialexperienceinusingPHPtointegratevarious
databasesystems,andhehasproducedawiderangeof
applicationsforaninternationalclientbase.
AgraduateofKeeleUniversity,ChrislivesinStoke-on-Trent,
England,whereherunsLightwoodConsultancy,Ltd.,the
companyhefoundedin1999tofurtherhisinterestinonline
databasedevelopment.
Chrishasservedasatechnicaleditoronseveralbooksfrom
Sams,includingPHPandMySQLWebDevelopment(2004),
SamsTeachYourselfPHP,MySQL,andApacheAllinOne
(2004),andRedHatFedoraUnleashed(2004).Heistheauthor
ofSamsTeachYourselfPHPin10Minutes(2005)andSQLite
(2004),andco-authorofMySQLPhrasebook(2006).
MoreinformationonLightwoodConsultancy,Ltd.,isavailableat
.Chriscanbecontactedat



Acknowledgments
IwouldliketothanktheteamatSamsPublishingforits
ongoingsupportandguidancewhilewritingthisbook.Special
thankstoShelleyJohnston,whohiredmeasatechnicaleditor
andthenonedayaskedifIwantedtowrite.IndeedIdid!After
sixawesomeyearsworkingtogether,Shelleyismovingon,and
Iwishhereveryhappiness.

WeWanttoHearfromYou!


Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.
Youcanemailorwritemedirectlytoletmeknowwhatyoudid
ordidn'tlikeaboutthisbookaswellaswhatwecandotomake
ourbooksstronger.
PleasenotethatIcannothelpyouwithtechnicalproblems
relatedtothetopicofthisbook,andthatduetothehigh
volumeofmailIreceive,Imightnotbeabletoreplytoevery
message.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyournameandphoneoremailaddress.Iwill
carefullyreviewyourcommentsandsharethemwiththeauthor
andeditorswhoworkedonthebook.
E-mail:

Mail:MarkTaber
AssociatePublisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA

ReaderServices
Visitourwebsiteandregisterthisbookat
www.samspublishing.com/registerforconvenientaccesstoany
updates,downloads,orerratathatmightbeavailableforthis
book.


Introduction
MySQLisapowerfulrelationaldatabase-managementsystem
thatsupportsarichlyfeaturedSQLlanguage.It'sfast,easyto
use,andbestofallavailableforfree!
MySQLisaverypopularchoiceforwebdevelopmentbecauseof
itscloserelationshipwithPHP.ManycompaniesprovideMySQL
aspartofastandardweb-hostingdeal,soyoumightalready
haveaccesstoMySQLwithoutneedingtoinstallanysoftware.
SamsTeachYourselfMySQLin10Minutesisdesignedtohelp
yougetahandleonMySQLquicklyandeasilythroughaseries
ofstep-by-steplessons.

WhoIsThisBookFor?
Thisbookisforyouifany(orall)ofthefollowingapply:
You'renewtoMySQL.
Youwanttoquicklylearnhowtobeproductivewitha
MySQLdatabase.

YouwanttolearnhowtouseMySQLforyourown
applications.

HowThisBookWorks
SamsTeachYourselfMySQLin10Minutesisdividedinto25
lessonsthatgraduallybuildononeanother.Bytheendofthe
book,youshouldhaveasolidunderstandingofMySQLand
knowhowtouseitinavarietyofreal-worldsituations.


Eachlessoniswritteninsimplestepssothatyoucanquickly
grasptheoverallconceptandputitintopractice.Thelessons
arealsodesignedtostandalonesothatyoucanjumpdirectly
toparticulartopicsasneeded.

OnlineSupportFilesandAppendixes
ThesampledatabaseusedinSamsTeachYourselfMySQLin10
MinutescanbedownloadedfromtheSamsPublishingwebsite,
atYoucaninstallthis
databaseonyourownMySQLservertofolloweveryexamplein
thebook.Therearealsofourbonusappendixesthatcanbe
downloadedfromtheSamsPublishingwebsite:AppendixC,
"SQLSyntaxReference,"AppendixD,"MySQLDatatype
Reference,"AppendixE,"ConfigurationReference,"and
AppendixF,"MySQLReservedWords."

ConventionsUsedinThisBook
ThisbookusesdifferenttypefacestodifferentiatebetweenSQL
codeandothercontent.
SQLcodeispresentedusingmonospacetype.Boldtext

indicatesuserinput.

ANotepresentspertinentpiecesofinformationrelatedtothe
surroundingdiscussion.


ACautionadvisesyouaboutpotentialproblemsthatinvolve
MySQLoritsimplementation.

ATipoffersadviceordemonstratesaneasierwaytodo
something.


Part1:MySQLFoundations
Lesson1.IntroducingMySQL
Lesson2.UsingMySQL


Lesson1.IntroducingMySQL
Inthislesson,youlearnwhattheMySQLdatabasesystemis
andwhatitcando.




DatabaseBasics
Atitsverysimplest,adatabaseisanorganizedwayofholding
togethervariouspiecesofinformation.Thetermdatabase
actuallyreferstothecollectionofdata,notthemeansbywhich
itisstored.Foracomputerdatabase,thesoftwareusedto

managethedataisknownasadatabase-managementsystem
(DBMS).
Adatabaseneednotbestoredoncomputeralthough,ofcourse,
thatiswhatthisbookisabout!Afilingcabinetandatelephone
directorybothcontaindatabases:Theyholdinformation,
organizedinastructuredmannersothatyoucaneasilyaccess
theindividualitemyouwanttofind.

RelationalDatabases
MySQLisarelationaldatabase-managementsystem(RDBMS).
ThetermrelationalindicatesthatMySQLcanstoreitsdataasa
numberofdifferenttablesthatarerelatedtoeachotherin
someway.
Theadvantageofthistypeofdatabaseoveraflattablesystem
isthatverylargedatabasescanbeconstructedfromdifferent
tables,eachofwhichcontainsonlyinformationrelevanttothat
table.
Muchhasbeenwrittenaboutrelationaldatabasetheory,but
youneedtounderstandonlyalittletocreateefficient
databases.Youdon'tneedtobescaredbywhatappearstobea
veryacademictopicagreatdealoftheprinciplesofrelational
databasedesignaregroundedincommonsense.Youwilllearn
moreaboutthisinLesson16,"DesigningYourDatabase."


WhyUseMySQL?
YoucanchoosefrommanydifferentRDBMSoptions,sowhy
useMySQLoveranothersystem?
OneoftheprimaryfactorswhenchoosinganRDBMSiscost.
MySQLisdistributedasopen-sourcesoftwareundertheGNU

GeneralPublicLicense,soyoucanactuallyuseMySQLfreeof
charge.
AlsoavailableforMySQLisacommerciallicensethatincludes
variouslevelsoftechnicalsupportforuserswithmission-critical
systems.Evenwiththecostofcommercialsupport,MySQL
offersasignificantlylowertotalcostofownershipoverother
enterprise-levelRDBMS.
MySQLisrobust,powerful,andscalable.Itcanbeusedin
applicationsfromtinywebdatabasestoverylargedata
warehouseswithterabytesofdata.YoucanuseMySQL
replicationorclusteringtoguarantee100%availability.A
numberofcasestudiespublishedonMySQL.comgivean
exampleofjustwhatMySQLiscapableof.


CaseStudies
YoucanreadabouthowMySQLhasbeenusedinlargeprojectsat
/>
AnatomyofaDatabase
Adatabaseconsistsofaseriesoftables.Eachtablehasa
name,whichishowitisreferencedintheSQLlanguage.Each
databasealsohasaname,andthesameRDBMScanmanage
manydifferentdatabases.MySQLisamultiuserdatabaseand
canrestrictaccesstoeachdatabasetoonlyspecificusers.
Adatabasetablelookssomewhatlikeaspreadsheet:asetof
rowsandcolumnsthatcancontaindataateachintersection.In
arelationaldatabase,youstoredifferenttypesofdatain
differenttables.Forinstance,thesampledatabaseinthisbook
hasseparatetablesforcustomers,products,andorders.
Eachtablehasadefinedsetofcolumns,whichdeterminethe

valuesitcanstore.Forexample,thetablethatcontains
informationaboutproductsneedstostoreaname,price,and
weightforeveryproduct.Eachrowofdatacancontainvalues
foronlythecolumnsdefinedinthetable.
Inaddition,eachcolumnisdefinedasaparticulardatatype,
whichdeterminesthekindofvaluesitcanstore.Thedatatype
mightrestrictvaluestonumericordatevalues,oritmight
imposeamaximumsize.


WhatIsSQL?
TheStructuredQueryLanguage(SQL)isthemostcommonway
toretrieveandmanagedatabaseinformation.AnSQLquery
consistsofaseriesofkeywordsthatdefinethedatasetyou
wanttofetchfromthedatabase.SQLusesdescriptiveEnglish
keywords,somostqueriesareeasytounderstand.


SQL
SometimesyouwillhearSQLpronouncedasthewordsequel,butit's
alsookaytopronounceitasthelettersS-Q-L.

VirtuallyeveryRDBMSonthemarketusestheSQLlanguage.
TheMySQLimplementationofSQLconformstotheANSISQL
standardsandimplementssomeofitsownextensiontohandle
featuresthatarespecifictoMySQL.

AboutMySQLABandmysql.com
MySQLABistheSwedishcompanythatdevelops,maintains,
andmarketstheMySQLdatabaseserverandtools.



MySQLSource
AlthoughMySQLisdistributedasopen-sourcesoftware,MySQLAB
ownsthesourcecodetoMySQLanddeterminesthetermsunderwhich
itismadeavailable.Currently,MySQLisdistributedundertheGNU
GeneralPublicLicense.

MySQLABprovidestechnicalsupporttouserswithcommercial
supportpackages.ThecompanyalsorunsMySQLtraining
coursesaroundtheworldandissuesMySQLCertificationto
thosewhowanttobecomeaccreditedMySQLDevelopersor
DatabaseAdministrators.
TheMySQLwebsite,containsasection
calledDeveloperZone(whichyoucanaccessdirectlyat
whereyoucanfindonlinesupportin
theformofforums,mailinglists,andusergroups.Consider
joiningoneoftheonlinecommunities;theyareagreatwayto
learnmoreaboutMySQLfromotherusers.
Youcandownloadorviewonline(intheDeveloperZone)a
comprehensivereferencemanualforMySQL.Youcandownload
aprintablePDFversionorbrowseanHTML-formatmanualthat
isfullysearchable.


OnlineManual
YoucanusetheshortcutURLto
searchtheonlinemanualforANYTHING.Ifthereisanexactmatch,you
willbetakenstraighttotheappropriatepage;otherwise,youwillseea
listofpossiblematches.


OtherResources
AnumberofMySQLbookshavebeenpublishedunderthe
MySQLPressbrand.Currently,theseincludeMySQLTutorial
(2004),MySQLLanguageReference(2005),MySQL
Administrator'sGuide(2005),andMySQLCertificationStudy
Guide(2004).
YoucanviewthecurrentrangeofMySQLPresstitlesat
/>

MySQLComponents
Let'stakeamomenttolookatwhereMySQLwillresideonyour
system.IfyoudonotyethaveMySQLinstalled,referto
AppendixA,"InstallingMySQL."

Linux/UNIXSystems
ThelocationofMySQLprograms,libraries,andotherfiles
dependsontheinstallationprefixusedwhenMySQLwas
installed.Typically,theprefixiseither/usr/MySQLor
/usr/local/MySQL.
Inthelocationusedonyoursystem,youwillfindthefollowing
subdirectories:
binContainstheMySQLexecutables,includingthedatabase

serverandalltheclientprograms
libContainsthedevelopmentlibrariesusedtocommunicate

withaMySQLdatabasefromyourownprograms
includeContainstheheaderfilesrequiredtouseMySQLAPIs
dataTheMySQLdatadirectory,containingtheactual


databasefiles
support_filesAnumberofsampleconfigurationfiles

TheMySQLconfigurationfileisnamedmy.cnf.Thefile/etc/my.cnf
containsglobalsettings,butyoucanalsocreateafilenamed
my.cnfinthedatadirectorythatappliesonlytothatMySQL


server;itispossibletohavemultipleMySQLserversonone
machine.


×