zoukankan      html  css  js  c++  java
  • mysql联合查询

    班级表:
    CREATE TABLE `join_test_class` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `name` char(15) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
    
    学生表:
    CREATE TABLE `join_test_student` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `name` char(15) DEFAULT NULL,
      `cla_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
    
    • 查询某个学生的班级
    mysql> select a.*,b.* from join_test_student as a left join join_test_class as b on a.cla_id = b.id where a.id = 2;
    +----+-------+--------+----+---------+
    | id | name  | cla_id | id | name    |
    +----+-------+--------+----+---------+
    |  2 | name2 |      2 |  2 | 班级2   |
    +----+-------+--------+----+---------+
    1 row in set (0.00 sec)
    
    • 查询某个班级的学生信息
    mysql> select a.*,b.* from join_test_student as a left join join_test_class as b on a.cla_id = b.id where b.id = 3;
    +----+-------+--------+----+---------+
    | id | name  | cla_id | id | name    |
    +----+-------+--------+----+---------+
    |  3 | name3 |      3 |  3 | 班级3   |
    +----+-------+--------+----+---------+
    1 row in set (0.00 sec)
    
    • 查询所有学生里对应的班级cla_id无效
    mysql> select a.*,b.* from join_test_student as a left join join_test_class as b on a.cla_id = b.id where b.id is null;
    +----+-------+--------+------+------+
    | id | name  | cla_id | id   | name |
    +----+-------+--------+------+------+
    |  4 | name4 |      4 | NULL | NULL |
    +----+-------+--------+------+------+
    1 row in set (0.00 sec)
    
    • 查询所有班级里,没有学生的班级
    mysql> select a.*,b.* from join_test_student as a right join join_test_class as b on a.cla_id = b.id where a.id is null;
    +------+------+--------+----+---------+
    | id   | name | cla_id | id | name    |
    +------+------+--------+----+---------+
    | NULL | NULL |   NULL |  1 | 班级1   |
    +------+------+--------+----+---------+
    1 row in set (0.00 sec)
    
  • 相关阅读:
    oo第二次博客作业
    oo第一次博客作业
    软件工程第3次作业 | 提问回顾与个人总结
    软件工程第2次作业 | 结对项目-最长单词链
    软件工程第1次作业 | 第一次阅读
    软件工程第0次作业 | 热身
    OO第四次博客作业
    OO第三次博客作业
    OO第二次博客作业
    OO第一次博客作业
  • 原文地址:https://www.cnblogs.com/wangweiwen/p/6560824.html
Copyright © 2011-2022 走看看