zoukankan      html  css  js  c++  java
  • 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
    
    左右连接 没有匹配上的数据不会返回
    
    
    
  • 相关阅读:
    ionic3 覆盖主题色
    sublime text 替换功能使用反向引用 replace with using
    mac 10.10.4 下安装xdebug不了的解决办法
    sublime package control 下载不了插件问题解决
    firefox css3 transform样式 位置偏移问题解决
    从ie9上打开httpwatch
    (转)用CSS为英文和中文字体分别设置不同的字体
    几个常用的dos命令
    moodle常用方法及代码片断
    多对多文件复制粘贴
  • 原文地址:https://www.cnblogs.com/kgwei520blog/p/13783003.html
Copyright © 2011-2022 走看看