Database - simple query & complex query

1.Experimental content and principle

1. Install VMWare virtual machine in Windows system, install Ubuntu system in VMWare, and

Build a LAMP experimental environment in Ubuntu.

2. Use MySQL to perform some basic operations:

(1) Log in to MySQL, create a user in MySQL, and grant permissions to the newly created user.

(2) Create and jump to a new database, displaying all databases and the current database.

(3) Display all tables and view table properties.

(4) Import the two sample databases emp loyees and sakila, and perform integrity checks on these two databases.

Back up, import and export these two databases.

3. SQL DDL usage

(1) Create DDL scripts, including creating and deleting tables, specifying primary keys, candidate keys and foreign keys;

(2) Modify and display the table structure;

(3) Create and delete indexes.

4. SQL DDL & DML usage

(1) Operations such as adding, deleting, checking, and modifying data

(2) Master the creation, deletion and update of views

5. Simple query

(1) Use clauses such as order by, group by, and having;

(2) Use various predicates;

(3) Use aggregate functions;

(4) Query on the time field.

6. Complex queries

(1) Nested subquery;

(2) Multi-table join query, including left join, right join, outer join, and self-join.

7. Create stored procedures, functions and triggers, call the created stored procedures, functions, and trigger triggers.

8. Install and use phpmyadmin.

2. Experimental procedures and analysis

1. Install the VMWare virtual machine in the Windows system by yourself, install the Ubuntu system in VMWare, and

The steps to install LAMP in Ubuntu are as follows (you can also use the installation menu):

sudo apt-get install update

sudo apt-get install apache2

sudo apt-get install mysq l-server

sudo apt-get install php

2. The basic steps to familiarize yourself with MySQL are as follows:

(1) Enter MySQL: mysq l -u root -p

(2) Create a new user: CREATE USER 'newuser'@' localhost' IDENTIFIED BY 'password';

(3) Grant permissions: GRANT ALL PRIVILEGES ON * . * TO 'newuser'@' localhost';

(4) Create a new database: CREATE DATABASE newdbname;

(5) Jump to the newly created database: USE newdbname;3

(6) Display all databases and the current database: SHOW DATABASES; SELECT DATABASE();

(7) Display all tables and view table attributes: SHOW TABLES; DESCRIBE tabname;

(8) Import two sample databases

① Unzip the data package: unzip test_db_master.zip

② Enter the data package directory: cd test_db_master

③ Import the emp loyee database: sudo sudo mysql -t < emp loyees.sql

④ Unzip the data package: unzip sakila-db.zip

⑤ Enter the data package directory: cd sakila-db

⑥ Enter MySQL and import sakila schema data: SOURCE /path/to/sakila-schema.sq l

⑦ Import sakila data: SOURCE /path/to/sakila-data.sq l

(9) Check the integrity of the two imported databases

① Check the foreign key check status: show variables like '%foreign_key_checks% ';

② View the primary key check status: show variables like '%unique_checks% ';

③ View the foreign key check results: select @@foreign_key_checks;

④ View the primary key check results: select @@unique_checks;

(10) Database backup (take employee as an example)

① Do not export any data, only export the database table structure:

mysqldump -u test_02 -p --no-data emp loyees> employees_bak1.sq l

② Only export data without adding CREATE TABLE statement:

mysqldump -u test_02 -p --no-create-info employees> emp loyees_bak2.sq l

③ Export all databases:

mysqldump -u test_02 -p emp loyees> emp loyees_bak3.sq l

(11) Export and import (take sakila as an example)

① Export to TXT file:

select * from country into outfile '/your/file/path/country';

② Import TXT file:

load data infile '/your/file/path/country' into table country;

③ Export to CSV file: 4

select * from country into outfile '/your/file/path/country.csv';

④ Import CSV file:

load data infile '/your/file/path/country.csv' into table country;

⑤ Export to xml file:

mysql  -u  test_02  -p  --xml  -e  'select  *  from  sakila.country'  >

/your/file/path/country.xml

3. SQL DDL usage

(1) Use the create statement to create all tables of the project;

(2) Use the alter command to modify the table structure and delete the "xxx" field in a certain table; modify the

The type of "xxx" field is char(2), this field cannot be empty, and the default value is "m";

(3) Add the 'xxx' field data of type char (2), whether the addition is successful, and analyze if it fails.

Reason for failure and perform necessary operations to successfully add the field;

(4) Modify a table, add a field of type varchar2(18), and add a check constraint to require the

The length of the field is 18 and can only consist of numbers, and the field is designated as a candidate key;

(5) Set the check constraint of a field in a table to be greater than 0; set the default value of a field to "Not

"Audit", set the check constraint of a "field" to "Not audited", "Audit passed", "Audit failed"

Pass";

(6) Create an index in a table;

(7) Use the describe command to display the table structure.

4. SQL DDL & DML usage

(1) Use the insert statement to insert data into the corresponding table;

(2) Use the delete statement to delete the records corresponding to the externally built related tables in the table. Can the deletion be successful? For example:

If not, please analyze the reason;

(3) Use the update statement to update the foreign key data. Can the modification be successful? If not, please analyze the reason. ;

(4) Create a view;

(5) Query operations on views;

(6) Perform joint query operations on tables;

(7) Update the view and analyze the reasons why the update operation can succeed or fail. 5

5. Simple query

(1) Query the student number, name and class number of all students whose gender is "male"; (simple query in a single table)

(2) Query the xxx table to obtain records with gender "female". The results are sorted in descending order by class ID; (order

by)

(3) Query the xxx table and sort by age from small to large; (get substring function, order by)

(4) Query student information whose student ID starts with "2002". The fields include student ID, name, and class number; (use sub

string function)

(5) Query the information of students whose student ID contains "01". The fields include student ID, name, and class number; (like)

(6) Leave applications whose query status is "Unreviewed" and the application time is after September 4, 2013

Information about the order, including the application form with the application time being September 4th; (single table multi-condition query)

(7) Query the application IDs whose review status is "Unreviewed" and "Approval Passed"; (in)

(8) Query the application ID submitted between August 31, 2013 and September 2, 2013,

Reason for leave; (between, time)

(9) Query the number of students who have chosen the courses taught by Teacher XXX (one person chooses two courses, which is counted as two people);

(10) Query the number of candidates for the course taught by Teacher

(11) Query the reason for the leave and the name of the student who failed to pass the review of the leave application form by teacher XX;

(12) Count the number of students in each course (aggregate function);

(13) Query the course numbers with more than 3 students, and sort them in descending order by course number (group by,

having,order by …desc)。

6. Complex queries

(1) Query the name of the course and the name of the teacher with the largest number of approved students;

(2) Query the name of the course with the largest and second largest number of enrollees and the name of the teacher; (optional)

(3) Query the names of students who have only chosen the course "Algorithm Design";

(4) Query the names of students who have taken all courses;

(5) Query the student number, name, and ID number of students who have taken course 3;

(6) Make a natural connection query between the xxx table and the xxx table based on the student number;

(7) Perform a left join query on the xxx table and the xxx table according to the student number, and explain the business implications of doing so 6

righteous;

(8) Perform a right join query on the xxx table and the xxx table based on the student number, and explain the business implications of doing so.

righteous;

(9) Summarize the differences in the results generated by natural join, left join, and right join queries.

7. Create and call stored procedures, functions and triggers

(1) Create and call the stored query process (take emp loyee as an example)

① Create a query stored procedure:

> delimiter##

> create procedure select_manager(in fname varchar(20), in lname varchar(20))

-> begin

->select * from dept_manager natural join emp loyees where first_name = fname

and

last_name = lname;

->end

> ##

② Call this stored query process: call select_manager('Xiaobin','Spinelli');

(2) Create and call functions (take emp loyee as an example)

① Create function:

> delimiter ##

> create function title_num(title_name varchar(50)) returns int

> begin

> declare num int;

> select count(title) from titles where to_date > curdate() and title =

title_name group

by title into num;

> return num;

> end



> ##

set g lobal log_bin_trust_function_creators=1;

② Call function: select title_num("manager");7

(3) Create and call triggers (take emp loyee as an example)

① View table dept_manager: select * from dept_manager;

② 创建新表 quit:create table quit (emp_no int, depr_no char(4), quit_date

date);

③ Create trigger:

mysql> delimiter ##

mysql> create trigger after_ insert_ quit after insert on quit for each row

-> begin

-> update dept_ manager set to_ date = curdate( ) where emp_ no = 110039;

-> end

-> ##

④ Trigger trigger: insert into quit values ​​(110039, 'd001', curdate());

⑤ View the new table quit: select * from quit;

⑥ Check the table dept_manager again: select * from dept_manager;

8. The steps to install phpmyadmin are as follows:

(1) Install phpmyadmin: sudo apt-get install phpmyadmin

(2) Install php-mbstring: sudo apt-get install php-mbstring

(3)安装 php-gettext:sudo apt-get install php-gettext

(4) Edit php.ini: vim /path/to/php. ini modification; extension=php-mbstring.so

(5) Restart Apache2: sudo /path/to/apache2 restart

(6) Check the IP address: ifconfig

(7) Log in to phpmyadmin: From the browser address your.ip.4.address/phpmyadmin

3.Experimental results and summary

5.  Simple query

Before conducting simple query and complex query experiments, I created a new database named  school  . Contains  4  tables,

The contents of each table are as shown in the figure:

s  table,  the content is the student’s personal information

 Table  l contains the student’s leave application and approval status.

 Table  c contains information about courses and teachers

The s_c  table  contains student course selection and performance information.

Based on the above four tables, I conducted the following two parts of experiments. First is an experiment with simple queries:

(1) Query the student  number, name and class number of all students whose gender is " male "  ; ( simple query in a single table)

(2)  Query the xxx  table to obtain  records with gender "female". The results  are arranged in descending order by class  ID ; ( order  by)

(3) Query the xxx  table and sort by age from small to large ; ( get substring function, order  by )

(query results for the first three questions)

(4) Query student  information whose student ID starts with "2002" . The fields include student ID, name, and class number ; (use substring function)

(5) Query student information containing "01" in the student ID  , the fields include student ID , name, class number ; ( like )

(The fourth and fifth questions are both related to strings, and the query results are as above)

(6)  Query information about leave application forms whose status is "Unapproved " and whose application time  is after September 4, 2013 , including  application forms whose application time is September 4  ; ( single form multi-condition query)

 (7) Query the application IDs whose review status is "Unreviewed " and "  Approval Passed"  ; ( in )

(8)  Query the application ID and           reason for leave submitted between August 31 , 2013 and September 2 , 2013 ; ( between , time) 

(9) Query  the number of students who have chosen courses taught by Teacher XXX (one person chooses two courses, which is counted as two people );

(10)  Query  the number of students who choose the courses taught by Teacher XXX (one person chooses two courses, which is counted as one person ); ( distinct )

(The difference between question 9 and question 10 is whether the calculation is repeated or not. Question 10 needs to exclude duplicates , so distinct is needed  )

(11) Inquire  about the reason for the leave and the name of the student who failed to pass the review of the leave application form by Teacher XX ;

(12)  Count the number of students in each course (aggregate function );

(Just use  the group  by  statement)

(13) Query the  course numbers with more than 3  students enrolled  , and sort them in descending by course number ( group by,      having , order  by  ... desc ).

6.  Complex queries

When conducting this complex query experiment, the database used is also the  school  database created above.

(1) Query the course name and teacher name with the largest number of approved students: counting, subqueries, etc. are required

(2) Query the name of the course with the largest and second largest number of enrollees and the name of the teacher;  ( optional)

(3) Query the names of students who have only chosen the course "Algorithm Design";

(4) Query the names of students who have taken all courses;

If you know the number of courses here, you can directly use group counting. If the number of courses taken by a student is equal to the number of courses (without duplication ), it can be considered that the student has taken all courses. As shown below:

(5) Query  the student ID number, name, and ID number of students who have taken course 3;

 (6) Make a natural connection query between the xxx  table and the  xxx table based on the student number ;

Make a connection query between the student information table (s) and the course selection information table (s_c )

 (7) Perform a left join query on the xxx  table and the xxx table based on the student number , and explain the business implications of doing so;

Make a connection query between the student information table (s) and the course selection information table (s_c )

Meaning: Query completely determined course selection information based on the course list

 (8) Perform a right join query on the xxx  table and the xxx table based on the student number , and explain the business implications of doing so;

Make a connection query between the student information table (s) and the course selection information table (s_c )

Meaning: Query all course selection information based on student information

(9) Summarize  the differences in the results generated by natural join, left join, and right join queries .

The difference between the three types of join queries is that: the information obtained by the natural join query is completely determined, the information obtained by the left join and right join queries are completely determined on the left and right tables respectively, and the information on the table on the other side cannot be completely determined. .

Guess you like

Origin blog.csdn.net/weixin_49816179/article/details/135305106