• mysql(三)多表查询


    Mysql 表与表之间的三种关系

    • 表与表之间一般存在三种关系,即一对一,一对多,多对多关系。
        article_cate 文章分类表
        有id,title,state, 字段
    
        article   文章表
        有id,title,description,cate_id,state 字段
    
        一个分类对应 多个文章
        一条文章只对应 一个分类
        article_cate 表中的ID 关联了 article表中的 cate_id 字段
    
    
    1. 一对一
      查询 所有文章 及其 分类ID

       笛卡尔积连接
       select article.id as id,article.title as title,article_cate.title as cate 
       from article,article_cate 
       Where article.cate_id=article_cate.id;
      
       内连接
       select article.id as id,article.title as title,article_cate.title as cate 
       from article 
       INNER JOIN article_cate ON article_cate.id=article.cate_id;
      
      
    2. 一对多

    返回 分类ID 为 2 的数据
    select * from article where cate_id=2
    
    
    1. 多对多
    多对多的关系需要借助中间表来关联
    三个表 课程表,中间表,学生表 lesson, lesson_student, student 
    表结构字段如下:
    lesson[id,name],
    lesson_student[lesson_id,student_id],
    student[id,number,password,classId,name]
    
    1、查询张三选修了那些课程
        张三的 Id 为 1
    
    普通查询:
        SELECT * FROM lesson where id in (select lesson_id from lesson_student WHERE student_id=1);
    
    笛卡尔积关联查询:
        SELECT * FROM lesson,lesson_student where lesson.id=lesson_student.lesson_id AND lesson_student.student_id=1;
    
    INNER JOIN(内连接查询):
        SELECT * FROM lesson INNER JOIN lesson_student ON lesson.id=lesson_student.lesson_id AND lesson_student.student_id=1;
    
    
    2、查询 Java 程序设计被那些学生选修了
        Java 程序设计的 id 为 2
    普通查询:
        SELECT * FROM student where id in (select student_id from lesson_student WHERE lesson_id=2);
    
    笛卡尔积关联查询:
    SELECT * FROM student,lesson_student 
    where student.id=lesson_student.student_id AND lesson_student.lesson_id=2;
    
    内连接:
    SELECT * FROM student INNER JOIN lesson_student ON student.id=lesson_student.student_id AND lesson_student.lesson_id=2;
    
    左外连接:LEFT JOIN   ON
    
    右外连接:RIGHT JOIN  ON
    
    左右连接 没有匹配上的数据不会返回
    
    
    
  • 相关阅读:
    git stash错误小记
    PHP,Mysql根据经纬度计算距离并排序
    JS~字符串长度判断,超出进行自动截取(支持中文)
    Redis的三种启动方式
    Ubuntu 14.04 LTS下安装Google Chrome浏览器
    PHP-PHPExcel用法详解
    git设置log的别名 for hist log样式格式化
    Ubuntu系统下配置PHP支持SQLServer 2005
    Git命令图片版
    《一线架构师实践指南》读后感(二)
  • 原文地址:https://www.cnblogs.com/kgwei520blog/p/13783003.html
Copyright © 2020-2023  润新知