zoukankan      html  css  js  c++  java
  • MySQL之两张表关系查找例子

    teacher表

    mysql> select * from teacher;
    +-----+--------+-----+---------+----------+
    | tid | tname  | age | address | courseid |
    +-----+--------+-----+---------+----------+
    | 101 | 马云   |  50 | 杭州    | NULL     |
    | 102 | 赵本山 |  52 | 沈阳    | NULL     |
    | 103 | 刘强东 |  45 | 北京    | NULL     |
    +-----+--------+-----+---------+----------+

    students表

    mysql> select * from students;
    +-----+--------+-----+---------+----------+
    | sid | sname  | age | address | courseid |
    +-----+--------+-----+---------+----------+
    |   1 | 小海子 |  23 | 北京    |     1003 |
    |   2 | 小沈阳 |  45 | 沈阳    |     1003 |
    |   3 | 刘阳   |  25 | 山东    |     1002 |
    |   4 | 甘能   |  22 | 广东    |     1002 |
    +-----+--------+-----+---------+----------+

    找出teacher表中在students表中 address相同 的 tname

    1、第一种做法(teacher表中的 address 在students表里面,即可完成本道题)

    mysql> select t.tname
        -> from teacher t 
        -> where t.address in(select address from students);
    +--------+
    | tname  |
    +--------+
    | 刘强东 |
    | 赵本山 |
    +--------+

     2、第二种做法(在students表中是否与teacher表中 存在address相等的情况)

    mysql> select t.tname
        -> from teacher t 
        -> where exists(select* from students s where t.address = s.address);
    +--------+
    | tname  |
    +--------+
    | 赵本山 |
    | 刘强东 |
    +--------+

    mysql> select t.tname
        -> from teacher t ,students s
        -> where t.address = s.address;
    +--------+
    | tname  |
    +--------+
    | 刘强东 |
    | 赵本山 |
    +--------+

     2018年1月18日00:38:29

  • 相关阅读:
    jpa入门案例----使用jpa对数据库进行查询、删除、修改操作
    ssm详细流程和步骤
    Dubbo
    ssm运行BUG
    mybatis 入门
    Linux
    Redis
    maven
    三层架构 开发模式
    转发和重定向的区别
  • 原文地址:https://www.cnblogs.com/liangwh520/p/8306941.html
Copyright © 2011-2022 走看看