SQL Joins - W3Schools

文章推薦指數: 80 %
投票人數:10人

(INNER) JOIN : Returns records that have matching values in both tables · LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records ... Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C C++ C# R React    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility Blog DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz KotlinQuiz XMLQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse React.jsCourse Bootstrap3Course Bootstrap4Course XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate Bootstrap5Certificate jQueryCertificate JavaCertificate C++Certificate C#Certificate React.jsCertificate TypeScriptCertificate XMLCertificate CyberSecurityCertificate AccessibilityCertificate ExcelCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro SQLTutorial SQLHOME SQLIntro SQLSyntax SQLSelect SQLSelectDistinct SQLWhere SQLAnd,Or,Not SQLOrderBy SQLInsertInto SQLNullValues SQLUpdate SQLDelete SQLSelectTop SQLMinandMax SQLCount,Avg,Sum SQLLike SQLWildcards SQLIn SQLBetween SQLAliases SQLJoins SQLInnerJoin SQLLeftJoin SQLRightJoin SQLFullJoin SQLSelfJoin SQLUnion SQLGroupBy SQLHaving SQLExists SQLAny,All SQLSelectInto SQLInsertIntoSelect SQLCase SQLNullFunctions SQLStoredProcedures SQLComments SQLOperators SQLDatabase SQLCreateDB SQLDropDB SQLBackupDB SQLCreateTable SQLDropTable SQLAlterTable SQLConstraints SQLNotNull SQLUnique SQLPrimaryKey SQLForeignKey SQLCheck SQLDefault SQLIndex SQLAutoIncrement SQLDates SQLViews SQLInjection SQLHosting SQLDataTypes SQLReferences SQLKeywords ADD ADDCONSTRAINT ALL ALTER ALTERCOLUMN ALTERTABLE AND ANY AS ASC BACKUPDATABASE BETWEEN CASE CHECK COLUMN CONSTRAINT CREATE CREATEDATABASE CREATEINDEX CREATEORREPLACEVIEW CREATETABLE CREATEPROCEDURE CREATEUNIQUEINDEX CREATEVIEW DATABASE DEFAULT DELETE DESC DISTINCT DROP DROPCOLUMN DROPCONSTRAINT DROPDATABASE DROPDEFAULT DROPINDEX DROPTABLE DROPVIEW EXEC EXISTS FOREIGNKEY FROM FULLOUTERJOIN GROUPBY HAVING IN INDEX INNERJOIN INSERTINTO INSERTINTOSELECT ISNULL ISNOTNULL JOIN LEFTJOIN LIKE LIMIT NOT NOTNULL OR ORDERBY OUTERJOIN PRIMARYKEY PROCEDURE RIGHTJOIN ROWNUM SELECT SELECTDISTINCT SELECTINTO SELECTTOP SET TABLE TOP TRUNCATETABLE UNION UNIONALL UNIQUE UPDATE VALUES VIEW WHERE MySQLFunctions StringFunctions: ASCII CHAR_LENGTH CHARACTER_LENGTH CONCAT CONCAT_WS FIELD FIND_IN_SET FORMAT INSERT INSTR LCASE LEFT LENGTH LOCATE LOWER LPAD LTRIM MID POSITION REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPACE STRCMP SUBSTR SUBSTRING SUBSTRING_INDEX TRIM UCASE UPPER NumericFunctions: ABS ACOS ASIN ATAN ATAN2 AVG CEIL CEILING COS COT COUNT DEGREES DIV EXP FLOOR GREATEST LEAST LN LOG LOG10 LOG2 MAX MIN MOD PI POW POWER RADIANS RAND ROUND SIGN SIN SQRT SUM TAN TRUNCATE DateFunctions: ADDDATE ADDTIME CURDATE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATE DATEDIFF DATE_ADD DATE_FORMAT DATE_SUB DAY DAYNAME DAYOFMONTH DAYOFWEEK DAYOFYEAR EXTRACT FROM_DAYS HOUR LAST_DAY LOCALTIME LOCALTIMESTAMP MAKEDATE MAKETIME MICROSECOND MINUTE MONTH MONTHNAME NOW PERIOD_ADD PERIOD_DIFF QUARTER SECOND SEC_TO_TIME STR_TO_DATE SUBDATE SUBTIME SYSDATE TIME TIME_FORMAT TIME_TO_SEC TIMEDIFF TIMESTAMP TO_DAYS WEEK WEEKDAY WEEKOFYEAR YEAR YEARWEEK AdvancedFunctions: BIN BINARY CASE CAST COALESCE CONNECTION_ID CONV CONVERT CURRENT_USER DATABASE IF IFNULL ISNULL LAST_INSERT_ID NULLIF SESSION_USER SYSTEM_USER USER VERSION SQLServerFunctions StringFunctions: ASCII CHAR CHARINDEX CONCAT Concatwith+ CONCAT_WS DATALENGTH DIFFERENCE FORMAT LEFT LEN LOWER LTRIM NCHAR PATINDEX QUOTENAME REPLACE REPLICATE REVERSE RIGHT RTRIM SOUNDEX SPACE STR STUFF SUBSTRING TRANSLATE TRIM UNICODE UPPER NumericFunctions: ABS ACOS ASIN ATAN ATN2 AVG CEILING COUNT COS COT DEGREES EXP FLOOR LOG LOG10 MAX MIN PI POWER RADIANS RAND ROUND SIGN SIN SQRT SQUARE SUM TAN DateFunctions: CURRENT_TIMESTAMP DATEADD DATEDIFF DATEFROMPARTS DATENAME DATEPART DAY GETDATE GETUTCDATE ISDATE MONTH SYSDATETIME YEAR AdvancedFunctions CAST COALESCE CONVERT CURRENT_USER IIF ISNULL ISNUMERIC NULLIF SESSION_USER SESSIONPROPERTY SYSTEM_USER USER_NAME MSAccessFunctions StringFunctions: Asc Chr Concatwith& CurDir Format InStr InstrRev LCase Left Len LTrim Mid Replace Right RTrim Space Split Str StrComp StrConv StrReverse Trim UCase NumericFunctions: Abs Atn Avg Cos Count Exp Fix Format Int Max Min Randomize Rnd Round Sgn Sqr Sum Val DateFunctions: Date DateAdd DateDiff DatePart DateSerial DateValue Day Format Hour Minute Month MonthName Now Second Time TimeSerial TimeValue Weekday WeekdayName Year OtherFunctions: CurrentUser Environ IsDate IsNull IsNumeric SQLQuickRef SQLExamples SQLExamples SQLQuiz SQLExercises SQLCertificate SQLJoins ❮Previous Next❯ SQLJOIN AJOINclauseisusedtocombinerowsfromtwoormoretables,basedon arelatedcolumnbetweenthem. Let'slookataselectionfromthe"Orders"table: OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 Then,lookataselectionfromthe"Customers"table: CustomerID CustomerName ContactName Country 1 AlfredsFutterkiste MariaAnders Germany 2 AnaTrujilloEmparedadosyhelados AnaTrujillo Mexico 3 AntonioMorenoTaquería AntonioMoreno Mexico Noticethatthe"CustomerID"columninthe"Orders"tablereferstothe "CustomerID"inthe"Customers"table.Therelationshipbetweenthetwotablesabove isthe"CustomerID"column. Then,wecancreatethefollowingSQLstatement(thatcontainsan INNERJOIN), thatselectsrecordsthathavematchingvaluesinbothtables: Example SELECTOrders.OrderID,Customers.CustomerName,Orders.OrderDateFROMOrdersINNERJOINCustomersONOrders.CustomerID=Customers.CustomerID; TryitYourself» anditwillproducesomethinglikethis: OrderID CustomerName OrderDate 10308 AnaTrujilloEmparedadosyhelados 9/18/1996 10365 AntonioMorenoTaquería 11/27/1996 10383 AroundtheHorn 12/16/1996 10355 AroundtheHorn 11/15/1996 10278 Berglundssnabbköp 8/12/1996 DifferentTypesofSQLJOINs HerearethedifferenttypesoftheJOINsinSQL: (INNER)JOIN:Returnsrecordsthathavematchingvaluesinbothtables LEFT(OUTER)JOIN:Returnsallrecordsfromthelefttable,andthematchedrecordsfromtherighttable RIGHT(OUTER)JOIN:Returnsallrecordsfromtherighttable,andthematched recordsfromthelefttable FULL(OUTER)JOIN:Returnsallrecordswhenthereisamatchineitherleft orrighttable       TestYourselfWithExercises Exercise: InsertthemissingpartsintheJOINclausetojointhetwotablesOrdersandCustomers, usingtheCustomerIDfieldinbothtablesastherelationshipbetweenthetwotables. SELECT* FROMOrders LEFTJOINCustomers =; SubmitAnswer» StarttheExercise ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?