zoukankan      html  css  js  c++  java
  • 数据库——自然连接、内连接、外连接(左外连接、右外连接,全连接)、交叉连接

    1. 创建数据库表

    dep表

    CREATE TABLE `dept` (
      `d_id` int(11) NOT NULL AUTO_INCREMENT,
      `d_name` varchar(20) DEFAULT NULL,
      PRIMARY KEY (`d_id`),
      KEY `d_name` (`d_name`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    

      

    emp表

    CREATE TABLE `emp` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(20) DEFAULT NULL,
      `age` int(11) DEFAULT NULL,
      `dept_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `dept_id` (`dept_id`),
      CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`dept_id`) REFERENCES `dept` (`d_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=32849 DEFAULT CHARSET=utf8;
    

      

     dept表                                                      emp表

      

    1. 自然连接(natural join)

        自然连接是一种特殊的等值连接,他要求两个关系表中进行比较的必须是相同的属性列,无须添加连接条件,并且在结果中消除重复的属性列。

        select * from emp  nature join dept;

    2. 内连接分为:隐式内连接、显示内连接,其查询效果相同。

           隐式和显示的区别:仅仅是写法不同,效果是一样的;

    -- 隐式的内连接
    select * from emp,dept where emp.dept_id = dept.d_id;

    -- 显示的内连接,一般称为内连接
    select * from emp INNER JOIN dept on emp.dept_id = dept.d_id;

    3. 外连接

      -- .左外连接(left join):返回左表中的所有行,如果左表中行在右表中没有匹配行,则结果中右表中的列返回空值;

        select * from emp left JOIN dept on emp.dept_id = dept.d_id;

      -- .右外连接(right join):返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值。

        select * from emp right JOIN dept on emp.dept_id = dept.d_id;

       全连接:返回左表和右表中的所有行。当某行在另一表中没有匹配行,则另一表中的列返回空值。

      mysql不支持全连接。

    4.-- 交叉连接(cross join):相当与笛卡尔积,左表和右表组合。

        select * from emp cross JOIN dept ;

        select * from emp , dept ;

  • 相关阅读:
    1451. Rearrange Words in a Sentence
    1450. Number of Students Doing Homework at a Given Time
    1452. People Whose List of Favorite Companies Is Not a Subset of Another List
    1447. Simplified Fractions
    1446. Consecutive Characters
    1448. Count Good Nodes in Binary Tree
    709. To Lower Case
    211. Add and Search Word
    918. Maximum Sum Circular Subarray
    lua 时间戳和时间互转
  • 原文地址:https://www.cnblogs.com/gshao/p/10538932.html
Copyright © 2011-2022 走看看