当前位置:网站首页>SQL statement select summary
SQL statement select summary
2022-06-25 20:08:00 【Fu Zongheng】
introduction
No matter what database you use , With what program to visualize the database , Or programming language query , In essence, it is through SQL Statement SELECT Keyword query . This article will illustrate SELECT Usage method . Use excellent SQL Statement filtering data is much more efficient than getting data to the background through code processing .
Data preparation
This article USES the mySQL database ,DataGrip Database visualization .
You can create your own empty database and execute my exported SQL file .
-- MySQL dump 10.13 Distrib 5.7.11, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: studentinfo
-- ------------------------------------------------------
-- Server version 5.7.11-log
/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @[email protected]@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `class`
--
DROP TABLE IF EXISTS `class`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `class` (
`ID` char(5) NOT NULL,
`headTeacher` char(9) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `class_teacher_ID_fk` (`headTeacher`),
CONSTRAINT `class_teacher_ID_fk` FOREIGN KEY (`headTeacher`) REFERENCES `teacher` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `class`
--
INSERT INTO `class` VALUES ('1','1'),('2','1'),('3','2'),('4','2'),('5','3');
--
-- Table structure for table `student`
--
DROP TABLE IF EXISTS `student`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `student` (
`ID` char(9) NOT NULL,
`name` char(7) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`classID` char(5) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `student_class_ID_fk` (`classID`),
CONSTRAINT `student_class_ID_fk` FOREIGN KEY (`classID`) REFERENCES `class` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `student`
--
INSERT INTO `student` VALUES ('201400001',' Zhang San ',24,'1'),('201400002',' Li Si ',24,'1'),('201500001',' Wang Wu ',23,'2'),('201500002',' Zhao Liu ',23,'2'),('201600001',' Sun Qi ',22,'3'),('201700001',' Tuesday ',21,'4'),('201800001',' Wu Jiu ',20,'5'),('201800002',' Zheng Shi ',20,'5');
--
-- Table structure for table `teacher`
--
DROP TABLE IF EXISTS `teacher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `teacher` (
`ID` char(9) NOT NULL,
`age` int(11) DEFAULT NULL,
`name` char(7) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `teacher`
--
INSERT INTO `teacher` VALUES ('1',40,' Teacher zhang '),('2',38,' Miss li '),('3',29,' Teacher wang ');
/*!40103 SET [email protected]_TIME_ZONE */;
/*!40101 SET [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
/*!40014 SET [email protected]_UNIQUE_CHECKS */;
/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;
/*!40111 SET [email protected]_SQL_NOTES */;
-- Dump completed on 2020-05-27 2:17:24
Select the database and execute the above code to complete the table creation and data insertion required in this article .
Text
Simple query
The database is not case sensitive , But it is recommended that keywords be capitalized
Database to ";" Determine whether the statement ends , Here's what happens SQL Statements can be written in multiple lines , When using the command line, you need to add a semicolon at the end, as shown below :
SELECT
*
FROM student;
The official start of the
Query all the data in the table :
SELECT * FROM student

* Represents all columns ,FROM The name of the table to be queried
Query partial Columns :
SELECT ID,name,age FROM student

Use... For the column to be selected , separate .
Alias the column :
SELECT ID as A,name,age FROM student

( When querying multiple tables , Duplicate fields can be distinguished by aliases ).
Built-in methods , Databases provide many built-in methods , Such as COUNT Count the quantity ,DISTINCT Find a unique value .
SELECT DISTINCT classID FROM student

Conditional inquiry
Find the students in class two :
SELECT * FROM student WHERE classID=2

WHERE The following judgment condition is that you need to add quotation marks when the string is used , Find Zhang San's information :
SELECT * FROM student WHERE name=' Zhang San '
Query support >,< Judge . Range is used BETWEEN 0 AND 60
Use... For multiple conditions OR, perhaps IN. The following two sentences have the same result
SELECT * FROM student WHERE name=' Zhang San ' OR name=' Li Si '
SELECT * FROM student WHERE name IN(' Zhang San ',' Li Si ')

wildcard
When querying a string , Fuzzy matching : Query by name " t " The teacher at the end ,"%“ Match any number of characters .”_" Match a character .
SELECT * FROM teacher WHERE name LIKE "% t "
SELECT * FROM teacher WHERE name LIKE " Li _ t "
keyword AVG, MAX, MIN, The average value can be achieved , Maximum , Calculation of minimum value . Can pass as Take an alias
SELECT AVG(age),MAX(age),MIN(age) FROM student

Group query , Sort , Paging query
Here is the number in the first column ,classID grouping , The result is the number of students in each class .num For the alias :
SELECT count(0)as num,classID FROM student GROUP BY classID

Sort by quantity :
SELECT count(0)as num,classID FROM student GROUP BY classID ORDER BY num

In reverse order “DESC”, The default is "ASC"
SELECT count(0)as num,classID FROM student GROUP BY classID ORDER BY num DESC
Database Paging mainly uses LIMIT and OFFSET keyword , Limit the number of returned data respectively , And offset , Example : lookup 3 strip / page Page 3 of LIMIT To limit the number of pieces 3,OFFSET=( Page number -1)* LIMIT
SELECT * FROM student LIMIT 3 OFFSET 6

Multi-table query
Demonstrate through students id Query the name of the head teacher of the student's class :
SELECT teacher.name FROM student,class,teacher WHERE student.ID='201400001'AND student.classID=class.ID AND class.ID=teacher.ID
Here, first find the corresponding row in the student table by student number , Then through the students' class ID Find the teacher corresponding to the class ID, Then through the teacher ID Identify teacher information , Take out name. Only the teacher's name is selected in the above results . here "*" You can get the information of the associated rows in the three tables .
SELECT * FROM student,class,teacher WHERE student.ID='201400001'AND student.classID=class.ID AND class.ID=teacher.ID

Self connect
Ask students younger than Zhao Liu .
SELECT * FROM student AS A,student AS B WHERE A.name=' Zhao Liu ' AND B.age<A.age
Find out Zhao Liu's information first , Then compare the ages .
It can be seen that , The database compares each row , You can use it. "B.*" Get only the second half of the information .
SELECT B.* FROM student AS A,student AS B WHERE A.name=' Zhao Liu ' AND B.age<A.age
Subquery
The name of the student whose head teacher is Mr. Zhang :
How to connect : First find out the class led by Mr. Zhang , Then find the students in the class
SELECT student.name from student,class,teacher WHERE teacher.name=" Teacher zhang " AND class.headTeacher=teacher.ID AND student.classID=class.ID

Subquery :
Similarly, first find out the class led by Mr. Zhang , Then, as a condition, judge whether the student's class is managed by him .
SELECT student.name
FROM student
WHERE classID IN
(
SELECT class.ID from class,teacher WHERE teacher.name=" Teacher zhang " AND class.headTeacher=teacher.ID
)

Of course keyword ANY It has the same effect
SELECT student.name
FROM student
WHERE classID = ANY
(
SELECT class.ID from class,teacher WHERE teacher.name=" Teacher zhang " AND class.headTeacher=teacher.ID
)
We can continue to use the above results as the conditions for the next query , for example : Judge whether Zhang San is among the above students
SELECT COUNT(0) AS num
FROM student
WHERE name=' Zhang San ' AND name =ANY (
SELECT student.name FROM student WHERE classID = ANY (SELECT class.ID from class,teacher WHERE teacher.name=" Teacher zhang " AND class.headTeacher=teacher.ID)
)

Return results :0 It means no data is found , Not in it ,1 That means we found Zhang San's information .
边栏推荐
- Redis core article: the secret that can only be broken quickly
- Alicloud centos8.0 installing mysql8
- PHP FPM, workman, spoole, golang simple performance test
- Skills of CCF question 2
- Huawei in application review test requirements
- Please do not call Page constructor in files
- Pcl+vs2019 configuration and some source code test cases and demos
- Appearance of object attributes
- Measurement index SSMI
- Profile path and name
猜你喜欢

H5 application conversion fast application

Applet wx Request encapsulation

Yaml configuration

2020-11-14-Alexnet

String since I can perform performance tuning, I can call an expert directly

<C>. Branch and loop statements

Thymleaf template configuration analysis

Swin UNET reading notes

PAT B1086

II Traits (extractors)
随机推荐
C language PTA -- continuity factor
Uniapp waterfall flow, applet waterfall flow, very simple, suitable for the whole platform
JS asynchronism (I. asynchronous concept, basic use of web worker)
LNMP compilation and installation
Mqtt+ardunio+esp8266 development (excluding mqtt server deployment)
<C>. Branch and loop statements
System optimization method
Vulnhub range - the planes:venus
Single chip microcomputer line selection method to store impression (address range) method + Example
Can the stock account opened through qiniu school be used? Is the fund safe?
Now meditation: crash service and performance service help improve application quality
PAT B1081
Jsonp processing non homologous
6、 Configuration resolution of hikariconfig
PAT B1067
PHP little knowledge record
2、 Hikaricp source code analysis of connection acquisition process II
Randomly generate 100 non repeating numbers between 1 and 150 and put them in the array
Validation of TTF font by validator of laravel
Processing method for uniapp or applet onload not receiving parameters