Home Database Mysql Tutorial MySQL的连接语法 []

MySQL的连接语法 []

Jun 07, 2016 pm 03:39 PM
mysql meaning grammar connect

MySQL的连接语法 1.内联结、外联结、左联结、右联结的含义及区别: 在讲MySQL的Join语法前还是先回顾一下联结的语法,呵呵,其实连我自己都忘得差不多了,那就大家一起温习吧(如果内容有错误或有疑问,可以来信咨询:陈朋奕chenpengyi#gmail.com),国内关

MySQL的连接语法 


1.内联结、外联结、左联结、右联结的含义及区别:

 

在讲MySQL的Join语法前还是先回顾一下联结的语法,呵呵,其实连我自己都忘得差不多了,那就大家一起温习吧(如果内容有错误或有疑问,可以来信咨询:陈朋奕 chenpengyi#gmail.com),国内关于MySQL联结查询的资料十分少,相信大家在看了本文后会对MySQL联结语法有相当清晰的了解,也不会被Oracle的外联结的(“+”号)弄得糊涂了。

 

在SQL标准中规划的(Join)联结大致分为下面四种:

1.  内联结:将两个表中存在联结关系的字段符合联结关系的那些记录形成记录集的联结。

2.  外联结:分为外左联结和外右联结。

左联结A、B表的意思就是将表A中的全部记录和表B中联结的字段与表A的联结字段符合联结条件的那些记录形成的记录集的联结,这里注意的是最后出来的记录集会包括表A的全部记录。

右联结A、B表的结果和左联结B、A的结果是一样的,也就是说:

Select A.name B.name From A Left Join B On A.id=B.id

和Select A.name B.name From B Right Join A on B.id=A.id执行后的结果是一样的。

3.全联结:将两个表中存在联结关系的字段的所有记录取出形成记录集的联结(这个不需要记忆,只要是查询中提到了的表的字段都会取出,无论是否符合联结条件,因此意义不大)。

4.无联结:不用解释了吧,就是没有使用联结功能呗,也有自联结的说法。

 

这里我有个比较简便的记忆方法,内外联结的区别是内联结将去除所有不符合条件的记录,而外联结则保留其中部分。外左联结与外右联结的区别在于如果用A左联结B则A中所有记录都会保留在结果中,此时B中只有符合联结条件的记录,而右联结相反,这样也就不会混淆了。其实大家回忆高等教育出版社出版的《数据库系统概论》书中讲到关系代数那章(就是将笛卡儿积和投影那章)的内容,相信不难理解这些联结功能的内涵。

 

2.  MySQL联结(Join)的语法

 

MySQL支持Select和某些Update和Delete情况下的Join语法,具体语法上的细节有:

 

table_references:

    table_reference [, table_reference] …

 

table_reference:

    table_factor

  | join_table

 

table_factor:

    tbl_name [[AS] alias]

        [{USE|IGNORE|FORCE} INDEX (key_list)]

  | ( table_references )

  | { OJ table_reference LEFT OUTER JOIN table_reference

        ON conditional_expr }

 

join_table:

    table_reference [INNER | CROSS] JOIN table_factor [join_condition]

  | table_reference STRAIGHT_JOIN table_factor

  | table_reference STRAIGHT_JOIN table_factor ON condition

  | table_reference LEFT [OUTER] JOIN table_reference join_condition

  | table_reference NATURAL [LEFT [OUTER]] JOIN table_factor

  | table_reference RIGHT [OUTER] JOIN table_reference join_condition

  | table_reference NATURAL [RIGHT [OUTER]] JOIN table_factor

 

join_condition:

    ON conditional_expr | USING (column_list)

 

上面的用法摘自权威资料,不过大家看了是否有点晕呢?呵呵,应该问题主要还在于table_reference是什么,table_factor又是什么?这里的table_reference其实就是表的引用的意思,因为在MySQL看来,联结就是一种对表的引用,因此把需要联结的表定义为table_reference,同时在SQL Standard中也是如此看待的。而table_factor则是MySQL对这个引用的功能上的增强和扩充,使得引用的表可以是括号内的一系列表,如下面例子中的JOIN后面括号:

 

SELECT * FROM t1 LEFT JOIN (t2, t3, t4) ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)

 

这个语句的执行结果和下面语句其实是一样的:

 

SELECT * FROM t1 LEFT JOIN (t2 CROSS JOIN t3 CROSS JOIN t4)

                 ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)

 

这两个例子不仅让我们了解了MySQL中table_factor和table_reference含义,同时能理解一点CROSS JOIN的用法,我要补充的是在MySQL现有版本中CROSS JOIN的作用和INNER JOIN是一样的(虽然在SQL Standard中是不一样的,然而在MySQL中他们的区别仅仅是INNER JOIN需要附加ON参数的语句,而CROSS JOIN不需要)。

既然说到了ON语句,那就解释一下吧,ON语句其实和WHERE语句功能大致相当,只是这里的ON语句是专门针对联结表的,ON语句后面的条件的要求和书写方式和WHERE语句的要求是一样的,大家基本上可以把ON当作WHERE用。

大家也许也看到了OJ table_reference LEFT OUTER JOIN table_reference这个句子,这不是MySQL的标准写法,只是为了和ODBC的SQL语法兼容而设定的,我很少用,Java的人更是不会用,所以也不多解释了。

那下面就具体讲讲简单的JOIN的用法了。首先我们假设有2个表A和B,他们的表结构和字段分别为:

 

表A:

ID

Name

1

Tim

2

Jimmy

3

John

4

Tom

表B:

ID

Hobby

1

Football

2

Basketball

2

Tennis

4

Soccer

 

1.  内联结:

Select A.Name B.Hobby from A, B where A.id = B.id,这是隐式的内联结,查询的结果是:

Name

Hobby

Tim

Football

Jimmy

Basketball

Jimmy

Tennis

Tom

Soccer

它的作用和 Select A.Name from A INNER JOIN B ON A.id = B.id是一样的。这里的INNER JOIN换成CROSS JOIN也是可以的。

2.  外左联结

Select A.Name from A Left JOIN B ON A.id = B.id,典型的外左联结,这样查询得到的结果将会是保留所有A表中联结字段的记录,若无与其相对应的B表中的字段记录则留空,结果如下:

Name

Hobby

Tim

Football

Jimmy

Basketball,Tennis

John

 

Tom

Soccer

所以从上面结果看出,因为A表中的John记录的ID没有在B表中有对应ID,因此为空,但Name栏仍有John记录。

3.  外右联结

如果把上面查询改成外右联结:Select A.Name from A Right JOIN B ON A.id = B.id,则结果将会是:

Name

Hobby

Tim

Football

Jimmy

Basketball

Jimmy

Tennis

Tom

Soccer

这样的结果都是我们可以从外左联结的结果中猜到的了。

说到这里大家是否对联结查询了解多了?这个原本看来高深的概念一下子就理解了,恍然大悟了吧(呵呵,开玩笑了)?最后给大家讲讲MySQL联结查询中的某些参数的作用:

 

1.USING (column_list):其作用是为了方便书写联结的多对应关系,大部分情况下USING语句可以用ON语句来代替,如下面例子:

 

a LEFT JOIN b USING (c1,c2,c3),其作用相当于下面语句

a LEFT JOIN b ON a.c1=b.c1 AND a.c2=b.c2 AND a.c3=b.c3

 

只是用ON来代替会书写比较麻烦而已。

 

2.NATURAL [LEFT] JOIN:这个句子的作用相当于INNER JOIN,或者是在USING子句中包含了联结的表中所有字段的Left JOIN(左联结)。

 

3.STRAIGHT_JOIN:由于默认情况下MySQL在进行表的联结的时候会先读入左表,当使用了这个参数后MySQL将会先读入右表,这是个MySQL的内置优化参数,大家应该在特定情况下使用,譬如已经确认右表中的记录数量少,在筛选后能大大提高查询速度。

 

最后要说的就是,在MySQL5.0以后,运算顺序得到了重视,所以对多表的联结查询可能会错误以子联结查询的方式进行。譬如你需要进行多表联结,因此你输入了下面的联结查询:

 

SELECT t1.id,t2.id,t3.id

    FROM t1,t2

    LEFT JOIN t3 ON (t3.id=t1.id)

    WHERE t1.id=t2.id;

 

但是MySQL并不是这样执行的,其后台的真正执行方式是下面的语句:

 

SELECT t1.id,t2.id,t3.id

    FROM t1,(  t2 LEFT JOIN t3 ON (t3.id=t1.id)  )

    WHERE t1.id=t2.id;

 

这并不是我们想要的效果,所以我们需要这样输入:

 

SELECT t1.id,t2.id,t3.id

    FROM (t1,t2)

    LEFT JOIN t3 ON (t3.id=t1.id)

    WHERE t1.id=t2.id;


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

Master SQL LIMIT clause: Control the number of rows in a query Master SQL LIMIT clause: Control the number of rows in a query Apr 08, 2025 pm 07:00 PM

SQLLIMIT clause: Control the number of rows in query results. The LIMIT clause in SQL is used to limit the number of rows returned by the query. This is very useful when processing large data sets, paginated displays and test data, and can effectively improve query efficiency. Basic syntax of syntax: SELECTcolumn1,column2,...FROMtable_nameLIMITnumber_of_rows;number_of_rows: Specify the number of rows returned. Syntax with offset: SELECTcolumn1,column2,...FROMtable_nameLIMIToffset,number_of_rows;offset: Skip

See all articles