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

  • 相关阅读:
    IDEA取消自动更新
    string常见面试题
    IDEA不能运行main方法
    GIT: Incorrect username or password
    淘宝技术架构演进之路
    javac编译原理之生死人肉白骨
    this string "--" is not permitted within comments ,(mapper文件)注释中不能使用--
    IE下input的type=file需要双击触发
    解决问题思路
    python
  • 原文地址:https://www.cnblogs.com/liangwh520/p/8306941.html
Copyright © 2011-2022 走看看