• SQL从表内容条件满足查询


    SQL从表内容中,找出满足条件的主表查询,这个东西还不好说:
    Class表
    ----------
    id   name
    1    班级1
    2    班级2
    3    班级3
    Student表
    id classid  name
    ----------------------------
    1 1  李四
    2 1  李三
    3  1  张三
    4 2  李四
    5 2  张三
    6 3  王五
    7 3  李三
    现在要找出有班上同时有(李四和张三)班级

    --创建表
    CREATE TABLE Class
    (
        id int,
        name nvarchar(200)
    )
    GO
    CREATE TABLE Student
       ( 
        id    int,
        classid int,
        name    nvarchar(100)
       )
    GO
    --插入数据
    INSERT INTO Class(id,name)Values(1,'班级1')
    INSERT INTO Class(id,name)Values(2,'班级2')
    INSERT INTO Class(id,name)Values(3,'班级3')
    INSERT INTO Student(id,classid,name)Values(1,1,'李四')
    INSERT INTO Student(id,classid,name)Values(2,1,'李三')
    INSERT INTO Student(id,classid,name)Values(3,1,'张三')
    INSERT INTO Student(id,classid,name)Values(4,2,'李四')
    INSERT INTO Student(id,classid,name)Values(5,2,'张三')
    INSERT INTO Student(id,classid,name)Values(6,3,'王五')
    INSERT INTO Student(id,classid,name)Values(7,3,'李三')
    --查询
    SELECT Class.name FROM Class INNER JOIN Student ON Class.id = Student.classid
    WHERE EXISTS(SELECT * FROM Student WHERE [name] = '李四' AND  Class.id = Student.classid) 
          AND EXISTS(SELECT * FROM Student WHERE [name] = '张三' AND  Class.id = Student.classid) 
    GROUP BY Class.name
    --删除表
    DROP TABLE Class
    DROP TABLE Student
    
    
     
    EXISTS 是判断是否存在,和in类似,但效率要比in高
    SELECT * FROM  EMP (基础表)  WHERE  EMPNO > 0  AND  EXISTS (SELECT ‘X'  FROM DEPT  WHERE  DEPT.DEPTNO = EMP.DEPTNO  AND  LOC = ‘MELB')
    
    SELECT  * FROM  EMP (基础表)  WHERE  EMPNO > 0  AND  DEPTNO IN(SELECT DEPTNO  FROM  DEPT  WHERE  LOC = ‘MELB')
    
    这两句效果一样
  • 相关阅读:
    【转】backtrack5工具之SQLMAP使用笔记(SQL注入用)
    httpd.conf配置详解
    【转】CodeBlocks+wxWidgets安装教程
    Windows下的Photoshop CS6快捷键
    backtrack常用渗透命令
    Codeforces Round #137 (Div. 2)
    Fedora 17 上安装 AMP 服务(Apache MySQL PHP)
    这几天用linux的体验
    EVO 4G 相机 照相 黑屏
    转载:qsort细节用法,double型的排序我竟然一直用错了~~~
  • 原文地址:https://www.cnblogs.com/xiaocai0923/p/2181984.html
Copyright © 2020-2023  润新知