五、多表连接查询——内连接

柔情只为你懂 2023-06-22 13:58 45阅读 0赞

五、多表连接查询——内连接

1.什么是内连接

根据相同的某列把多个表合并。

#

2.等值连接【最常用】

使用等于号(=)运算符比较被连接列的列值。

(1)等值连接语法

<1>格式一:

  1. select 表名.列名
  2. from 表名1 [inner] join 表名2
  3. on 表名1.列名=表名2.列名 [...n]

<2>格式二:

  1. select 表名.列名
  2. from 表名1,表名2 [,...]
  3. where 表名1.列名=表名2.列名 [and...]

(2)将学生表(student)和成绩表(student_score)通过学号(student_id)连接起来。【选择全部数据】

<1>使用inner join的方法

  1. select * from student inner join student_score on student.student_id=student_score.student_id;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzMDY5Nw_size_16_color_FFFFFF_t_70

<2>使用where

  1. select * from student,student_score where student.student_id=student_score.student_id;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzMDY5Nw_size_16_color_FFFFFF_t_70 1

(2)将学生表(student)和成绩表(student_score)通过学号(student_id)连接起来。【选择学号、姓名、成绩三列】

  1. select student.student_id,student.name,student_score.score from student join student_score on student.student_id=student_score.student_id;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzMDY5Nw_size_16_color_FFFFFF_t_70 2

3.不等值连接

在连接条件使用除了等于号(=)之外的其它比较运算符比较被连接的列的列值。

比如:>、>=、<、<=、!=、<>、!>、!<。

(1)示例:将学生表(student)和成绩表(student_score)通过学号(student_id)使用>连接起来。【选择全部数据】

  1. select * from student join student_score on student.student_id>student_score.student_id;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzMDY5Nw_size_16_color_FFFFFF_t_70 3

4.自然连接

自动去除重复的属性列,仅保留所有不重复的属性列。

自然连接中无需指定连接条件,自动匹配列值相同的字段。

(1)示例:将学生表(student)和成绩表(student_score)自然连接。【选择全部数据】

  1. select * from student natural join student_score;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzMDY5Nw_size_16_color_FFFFFF_t_70 4

(2)示例:将学生表(student)和成绩表(student_score)自然连接。【选择部分数据】

  1. select student.student_id,student.name,student_score.student_id,student_score.score
  2. from student natural join student_score;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjgzMDY5Nw_size_16_color_FFFFFF_t_70 5

为什么会有重复值?

虽然说select先写,但是select的操作在这个sql语句中最后执行,首先执行自然连接,然后执行选择数据。在自然连接时得到了一张表,但是这张表的结果被select的操作给覆盖掉了。

发表评论

表情:
评论列表 (有 0 条评论,45人围观)

还没有评论,来说两句吧...

相关阅读

    相关 mysql————连接查询

    内连接查询:可以查询两个或者两个以上的表,当两个表中存在表示相同意义的字段时,可以通过该字段来连接这两个表; 当该字段的值相等时,就查询出该记录。 前期准备两个表: