SQL statements basic exercises (five)

SQL statements based operations (e) - is still a query

This article recorded the eighth time job
Database using SQL Server, use database management software is the SQL Server Management Studio.
Previous article: SQL statements basic exercises (four)
last when it comes to nested queries, had a left EXISTS remain last. This is because it involves a predicate logic in discrete mathematics, around a bit, I hope this article can be placed carefully and then say something about.

(A) nested query

4. subquery with EXISTS predicate

 EXISTS English word means "presence", the existential quantifier ∃ represented here. In SQL, we can use the EXISTS and NOT EXISTS to logical judgment. EXISTS predicate sub-query returns true and false , rather than data. Nonempty inner query returns true, the inner query returns empty to false , the NOT EXISTS predicate contrary. Target drawn from the inner EXISTS query column expression, we generally use *, because here is the column name is moot.

[Example 3.60] to query all the elective courses student names No. 1
	 SELECT Sname
     FROM 	Student
     WHERE 	EXISTS
           (SELECT *
            FROM SC
            WHERE Sno=Student.Sno AND Cno= '1');

 Obviously this is a correlated subquery, the value of the incoming Student within the sub-queries. Configuration logic here is taken to start a Student table value, Sno, Sno value SC and the table for comparison, returns true if there is a set of data and Cno if they are equal to 1, like the parent query, and then stored in the corresponding relationship table Sname. Repeat this until all values have been checked Sno.
 Here I think EXISTS mainly played the role of a logical judgment, to fill the vacancy on an expression before operator expressions. This title also has other queries can be achieved, such as the use of very simple queries connection can be found.

[Example 3.61] Query student's name is not No. 1 elective courses.

 After clarification on a question, the problem becomes very clear, and just replaced the EXISTS NOT EXISTS. Statement given below:

	SELECT 	Sname
    FROM 	Student
    WHERE 	NOT EXISTS
           (SELECT *
            FROM SC
            WHERE Sno=Student.Sno AND Cno= '1');

 Note: sub with NOT EXISTS EXISTS predicate query and may not be equivalent to other forms of subquery Alternatively, all the sub-queries with IN predicates, comparison operators, the ANY and ALL EXISTS predicates can be used to predicate subqueries replace . That is their host EXISTS alternative, but not necessarily more efficient, it will depend on specific use.
 Example 3.55 as before, to find the same or that student's questions, can be replaced with EXISTS IN.

	SELECT Sno,Sname,Sdept	//例3.55改
    FROM Student S1
    WHERE EXISTS
         (SELECT *
          FROM Student S2
          WHERE S2.Sdept = S1.Sdept AND	//S1中找出和S2刘晨dept相同的
                S2.Sname = '刘晨');
//可以看到相比于原来的语句变得复杂了,所以这里其实没必要替换
[Example 3.62] query enrolled in a full course of student names

 All elective courses, all of this can be translated into ∀, but SQL is not the universal quantifier ∀. But we have the existential quantifier. We can use the existential quantifier to tactfully express the meaning of the universal quantifier. we know:
( x ) P ¬ ( x ( ¬ P ) ) (\forall x)P \equiv \lnot (\exists x(\lnot P))
This is what does that mean? Look to the right of the equation there are two negative, in fact, the whole existence becomes a quantifier quantifier, double negative Table sure thing. Then brought to a specific context, such as this proposition:

  • All elective courses students

It can be converted to

  • No one elective course students are not
    good living! In this way we can use to write SQL statements EXISTS it!
	SELECT Sname
    FROM Student
	WHERE NOT EXISTS
       	     (SELECT *
              FROM Course
              WHERE NOT EXISTS
                   (SELECT *
                    FROM SC
                    WHERE Sno= Student.Sno
                    AND Cno= Course.Cno
                    )
             );

 This inner logic of what is it? We note here is used to select the predicate NOT EXISTS, first remember. Look at the innermost statement can be seen here first ratio is right Sno, that is, student number. When the student number than the success ratio will continue to Cno, that is, course number.
 Student ID is assumed that the first alignment is 001, all elective courses, a total of three courses. So in the Course of queries, each will return more than one Cno Course to query a false (using a NOT EXISTS), then 3 courses is three false, that is,
F F F = F F \ their F \ their F = F
means is returned to the outermost F is a value, then put it NOT EXISTS what became the T value, that is, the students enrolled in all courses. If the student did not have a elective course, on where there will be a T value, be sure it is the last value T, then the outermost layer will become F, meaning students could not elective courses for all.
 If we do not use but NOT EXISTS EXISTS it? Then this does not match with our proposition, and can only say that there is not to say all, so the final result is as long as the election of a class of all jump out.

[Example 3.63] Query students to take at least a full course of elective students number 201 215 122

 For this query, we use to express the logical implication: Queries school students x number of courses for all y, as long as 201 215 122 students enrolled in the course y, then x is also enrolled y.

  • With P predicate "elective courses students 201 215 122 y

  • With q denotes the predicate "x Students enrolled in courses y
    the above query is: ( y ) p q (\forall y)p \to q
    and p q ¬ p q p \to q \equiv \lnot p \lor q
    There ( y ) p q ¬ ( y ( ¬ ( p q ) ) ) ¬ ( y ( ¬ ( ¬ p q ) ) ) ¬ y ( p ¬ q ) (\forall y)p \to q \equiv \lnot (\exists y(\lnot (p \to q)))\equiv \lnot (\exists y(\lnot(\lnot p \lor q))) \equiv \lnot \exists y(p \land \lnot q)
    into semantic means: there is no such course y, 201 215 122 students enrolled y, x and students did not choose.

	SELECT DISTINCT Sno
	FROM SC SCX
	WHERE NOT EXISTS
         (SELECT *
          FROM 	SC SCY
          WHERE SCY.Sno = '201215122'  AND
                NOT EXISTS
               (SELECT *
                FROM SC SCZ
                WHERE SCZ.Sno=SCX.Sno 
                AND   SCZ.Cno=SCY.Cno));

 Because here with three SC table, we take them to SCX, SCY, SCZ three aliases. Obviously this is relevant sub-queries, and general ideas, like the previous question, but more complex. SCX layer to query alignment layer, it conveys a Sno into the innermost, SCY layer role is to pass the innermost course number. In SCZ this layer, a layer of holding a course number obtained for comparison with the election to the lesson, the lesson true if the election had returned to the floor, otherwise false.
 As with the previous question, we assume that all the students were queried courses have been selected once, 201215122 chose three classes. The student then returns the innermost layer are T, it will become the second layer to F, the SELECT in the second layer to meet the criteria as are F, it must be returned outermost T (NOT EXISTS ), the outermost layer of T means that no 201,215,122 selected classes the student is not selected
 if the student chose 201,215,122 class also chose another course, and there are some lessons not selected, then the second layer of those who did not choose Lesson 201,215,122 certainly did not choose, a T (did not choose a class to the second layer becomes T) a F (201215122 did not choose) the result is still F (and here is the relationship, and the second layer on a problem is not the same a), with the final of the situation just the same.
 If the student's class is less than 201215122 selected class, then the second layer becomes T, and finally out of the reaction is F.
 Spent some tongue illustrates the SQL statement is correct, but I really want to write a still difficult Kazakhstan.

Blind bb

(B) a set of query

 There are three kinds of set of the query, and operates UNION, INTERSECT, and difference operations cross operation the EXCEPT . Query result set of operations is a set of tuples, the display is more intuitive.
Note: participating in the operation of the query result set number of columns must be the same type of data corresponding to the item must be the same.

[Example 3.64] Department of Computer Science student inquiry and no older than 19 year-old student.

 This is a union operation, write queries CS lines and age not more than 19 plus a UNION statement like, nothing else.

		SELECT *
        FROM Student
        WHERE Sdept= 'CS'
        UNION	/*若要保留重复元组请使用UNION ALL*/
        SELECT *
        FROM Student
        WHERE Sage<=19;

Query 1

[Example 3.65] query elective courses 1 or 2 of elective courses students.

 Or see the word and it means that we can choose the operation to complete the inquiry. Query Lesson 1 Lesson 2 further inquiry, the two together can be.

		SELECT Sno
        FROM SC
        WHERE Cno='1'
        UNION
        SELECT Sno
        FROM SC
        WHERE Cno= '2';

2

[Example 3.66] Department of Computer Science student inquiry and age not more than 19-year-old student intersection.

 Now that this topic is the intersection point out, it can be directly on the INTERSECT.

	SELECT *
	FROM Student
	WHERE Sdept='CS' 
	INTERSECT
	SELECT *
	FROM Student
	WHERE Sage<=19
	/*又或者可以使用单表查询*/
	SELECT *
	FROM Student
	WHERE Sdept='CS' AND Sage<=19;

3

[Example 3.67] query both elective courses 1 and 2 of elective courses students

 · · · · · · Both and the associated word for this problem is the intersection of the same operation.

	SELECT Sno
    FROM SC
    WHERE Cno='1' 
    INTERSECT
    SELECT Sno
    FROM SC
    WHERE Cno='2';
    /*亦或者选择嵌套查询*/
    SELECT Sno
    FROM SC
    WHERE Cno='1' AND Sno IN
    		(SELECT Sno
    		 FROM SC
    		 WHERE Cno='2');

4

[Example 3.68] Department of Computer Science student inquiry and age not more than 19-year-old student set difference.

 Topic point out that this is a poor set, we do not need more thinking. This problem differencing means is set to be queried students CS lines older than 19 years old.

	SELECT *
    FROM Student
    WHERE Sdept='CS'
    EXCEPT
    SELECT  *
    FROM Student
    WHERE Sage <=19;
    /*Another Version*/
    SELECT *
	FROM Student
	WHERE Sdept='CS' AND Sage>19;

5

Queries (c) based on the derived table

 Subquery not only appear in the WHERE clause,
may also appear in the FROM clause, then the subquery derived table generated temporary target of the query main query.
As described in Example 3.57 and Example 3.60 can be rewritten in the following form:

	/*例3.57 找出每个学生超过他自己选修课程平均成绩的课程号*/
	SELECT Sno, Cno
    FROM SC, (SELECT  Sno, Avg(Grade) FROM SC GROUP BY  Sno)	/*此处将所有的平均成绩按Sno排列,被下面作为临时派生表的基础*/
              AS Avg_sc(avg_sno,avg_grade)	/*建立一个临时派生表Avg_sc,里面有avg_sno,avg_grade两个属性*/
    		  WHERE SC.Sno = Avg_sc.avg_sno   and SC.Grade >=Avg_sc.avg_grade
    /*例3.60 查询所有选修了1号课程的学生姓名*/
    SELECT Sname
    FROM   Student,  
    (SELECT Sno FROM SC WHERE Cno=' 1 ') AS SC1
     /*通过FROM子句生成派生表,AS关键字可以省略掉,但是你必须为派生关系指定别名*/
    WHERE  Student.Sno=SC1.Sno;

 Temporary derived table what does it mean? See Example 3.57 above heavy plate, the second line has established a stored table grade point average and ranks third line is to declare it as a temporary derived table, it can come to be used. The fourth line is an ordinary connection inquired. Overall temporary table is to derive a set of processed data as a temporary table, so that queries more easily.

Epilogue

 In the learning process the query, I feel the most profound is a query only one purpose does not necessarily correspond to the statement. In other words, a lot of statements can achieve a certain operation, you need to select the specific user to determine according to their own habits and efficiency. Different people written statement style is different but the final goal is the same.
 Another is to feel the application of mathematical ideas in computer science. Although this appears to be a SQL statement and no application programming anything to do, it also reflects the mathematical thinking all the time: relational algebra, predicate logic and set pay and poor and so on.
FUUUBUKI!
Next article: SQL statements basic exercises (six)

 

 
References:
[1] Sa Shi Xuan, Wang Shan, An Introduction to Database Systems .5 Beijing: Higher Education Press, 2014.
[2] David teachers PPT.

Released nine original articles · won praise 13 · views 5602

Guess you like

Origin blog.csdn.net/FDR_Enterprise/article/details/105033598