03.20 mysql EXISTS and transactions

The syntax of the EXISTS subquery:

select....from table name where exists(subquery); #return true, false


例1:exists

#Check the most recent exam score for the "Logic Java" course

#If there are scores above 80, display the student numbers and scores of the top 5 students

SELECT r.studentResult,r.`studentNo`,r.`examDate` FROM result r WHERE EXISTS(SELECT s.subjectno FROM subject1 s WHERE subjectname='java' 
AND r.subjectNo=s.subjectno      # 关联
AND examDate=(SELECT MAX(examdate) FROM result WHERE subjectno=(SELECT subjectno FROM subject1 WHERE subjectname='java'))
 AND r.`studentResult`>=80)
 ORDER BY studentResult DESC

 LIMIT 5;



not exists #Not exists-------

Example 2:

Check your most recent exam scores for the Logic Java course

If all the exams are not passed (60 points pass), the exam is considered to be difficult, and the average score of the exam will be calculated plus 5 points # There is no more than 60 points

SELECT AVG(studentresult)+5 AS 平均分 FROM result
WHERE NOT EXISTS (
SELECT * FROM `result`  WHERE `subjectNo` = (
   SELECT `subjectNo` FROM `subject` WHERE `subjectName` = 'Logic Java'
  )  AND `examDate` = (
     SELECT MAX(`examDate`) FROM `result` WHERE `subjectNo` = (     
       SELECT `subjectNo` FROM `subject` 
       WHERE `subjectName` = 'Logic Java') 
  ) AND `studentResult` > 60)
AND `subjectNo` = ( SELECT `subjectNo` FROM `subject` 
WHERE `subjectName` = 'Logic Java') 
AND `examDate` = (
  SELECT MAX(`examDate`) FROM `result` WHERE `subjectNo` = (     
  SELECT `subjectNo` FROM `subject` 

  WHERE `subjectName` = 'Logic Java') );


Example 3:

#If there are S2 students, check the student number, subject number, test score, and test time of the students who participated in the S2 subject test

#First judge the students who have S2, under the judgment

SELECT studentno,subjectno,studentResult,examDate FROM result WHERE EXISTS (SELECT * FROM student1 WHERE gradeid=(SELECT gradeid FROM grade1 WHERE gradename='S2'))
 AND subjectno IN (SELECT subjectno FROM subject1 WHERE gradeid=(SELECT gradeid FROM grade1 WHERE gradename='S2'));



group by implements grouping:

select ......from  表名

where...

group by......


example:

SELECT COUNT(*),studentno,AVG(studentresult) ,subject FROM result 
GROUP BY studentno
ORDER BY AVG(studentresult) desc;

Can also be grouped together:

SELECT `gradeId` AS grade number, `sex` AS gender, COUNT(*) AS number ----------------------------- ------AS can be writable or not ----------------------
 FROM `student`
GROUP BY `gradeId`,`sex`
ORDER BY `gradeId `;


Group filter statement:

SELECT …… FROM  <表名>
WHERE ……
GROUP BY ……
HAVING……                                   #group by 后面跟having


Comparison of where and having:

WHERE clause
Used to filter rows resulting from operations specified in the FROM clause 
GROUP BY clause
Used to group the output of the WHERE clause 
HAVING clause
Used to filter rows from the grouped results 



Inner join (INNER JOIN)-------- fields exist, the two tables match -------------
outer join is divided into:
Left outer join (LEFT JOIN)------------There is a master table, a slave table, the table in front of the left is the master table, and the latter is the slave table------- --Right   
outer join (RIGHT JOIN)----------The back of the right is the main table, and the front is the slave table--------- -



Inner join:

SELECT …… 
FROM Table 1
INNER JOIN Table 2
ON ……


Example: Three tables can be connected first and then connected

SELECT S.studentName AS 姓名,SU.subjectName AS 课程,R.studentResult AS 成绩
FROM student AS S 
INNER JOIN `result` AS R ON  (S.`studentNo` = R.`studentNo`)
INNER JOIN `subject` AS SU ON (SU.subjectNo=R.subjectNo);


Left outer join: change inner to left

Right outer join: change inner to right



Transaction:

1. TRANSACTION is a series of operations performed as a single logical unit of work
2. Multiple operations are submitted to the system as a whole, either all or none of them are performed 
3. A transaction is an inseparable logical unit of work

The transfer process is a whole
. It needs two UPDATE statements to complete. These two statements are a whole.
If any one of them has an error, the entire transfer business should also be cancelled, and the balances in the two accounts should be restored to the original data. Make sure that the balance before and after the transfer remains unchanged, that is, both are 1001 yuan


A transaction must have the following four attributes, referred to as ACID attributes
Atomicity: A transaction is a complete operation, and each step of the transaction is indivisible (atomic), either all executed or none of them are executed
Consistency : When the transaction is completed, the data must be in a consistent state
Isolation (Isolation): It is possible to generate concurrency, independent of each other, similar to threads, and divided into levels:

Dirty read 1, non-repeatability 2, phantom read 3

Level from low to high:

Read uncommitted: 123

Non-repeatable reads: 23

Repeatable reads: 3

Serialize:


Durability: After a transaction completes, its modifications to the database are persisted permanently

example:

BEGIN;
UPDATE result SET studentResult=100 WHERE studentno=2 ;
COMMIT;


Example 2:

/*Insert the scores of ten students who participated in today's "Logic Java" course exam in batches.
If the entered score is greater than 100 points, the operation will be canceled
*/
SET autocommit=0;#---------Turn off transaction autocommit- --------------
BEGIN;#------------------------Start a new transaction, or start transaction- -------------
INSERT INTO result(studentno,subjectno,examDate,studentResult) VALUES (7,2,NOW(),89),(8,2,NOW(),98), (9,2,NOW(),67);
COMMIT;#-------Commit transaction------- #Insert
wrong data
INSERT INTO result(studentno,subjectno,examDate,studentResult) VALUES ( 5,2,NOW(),101);
INSERT INTO result(studentno,subjectno,examDate,studentResult) VALUES (6,2,NOW(),102);
ROLLBACK;#--------rollback transaction -----
SET autocommit=1;#-------Turn on autocommit-------







Homework 1: Transcript

/*Make a transcript of each course for each student during the school period, and require each student to take the last test score of each course as the student's final grade for this course.


Data items of the transcript
Student name The name
of the grade to which the course belongs
Course Name
Exam Date
Exam Score*/


SELECT studentname Name,(SELECT gradename FROM grade1 WHERE gradeid=subject1.`gradeID`) Grade Name, subjectname Course Name, examDate Exam Date, studentResult Grade FROM result r1
INNER JOIN student1 ON student1.`studentNo `=r1.`studentNo`
INNER JOIN subject1 ON subject1.`subjectNo`=r1.`subjectNo`
WHERE r1.`examDate` IN(SELECT MAX(examdate) FROM result r2 WHERE r2.`subjectNo`=r1.`subjectNo` )
ORDER BY subject1.`gradeID`;


Homework two:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325522237&siteId=291194637