search
HomeDatabaseMysql TutorialMySQL(基础篇)之单表查询

MySQL(基础篇)之单表查询

Jun 07, 2016 pm 03:03 PM
createmysqlBasedataInquirestructure

一:表的结构和数据 CREATE TABLE `t_student` ( `id` INT PRIMARY KEY , `stuName` VARCHAR (10) NOT NULL, `age` INT NOT NULL , `sex` VARCHAR (4) , `gradeName` VARCHAR (10) NOT NULL ); INSERT INTO `t_student` (`id`, `stuName`, `age`, `sex`, `gra



一:表的结构和数据

CREATE TABLE `t_student` (

`id` INT PRIMARY KEY ,

`stuName` VARCHAR (10) NOT NULL,

`age` INT NOT NULL ,

`sex` VARCHAR (4) ,

`gradeName` VARCHAR (10) NOT NULL

);

 

INSERT INTO `t_student` (`id`, `stuName`, `age`, `sex`, `gradeName`) VALUES('1','张三',23,'男','一年级'),('2','张三丰',25,'男','二年级'),('3','李四',23,'男','一年级'),

('4','王五',22,'男','三年级'),('5','珍妮',21,'女','一年级'),('6','李娜',26,'女','二年级'),('7','王峰',20,'男','三年级'),('8','黄志浩',21,'男','二年级'),

('9','杨磊',22,'男','一年级'),('10','邹涛',25,'男','二年级'),('11','鲍文杰',21,NULL,'二年级'),('12','朱云芬',23,'男','二年级'),('13','朱云峰','24',NULL,'二年级');

 

这是我为大家练习准备的数据,下面正式开始单表查询.

 

二:单表查询

2.1 查询所有字段

1.       Select 字段1,字段2,字段3……From 表名;

例:SELECT id,stuName,age,sex,gradeName FROM t_student;

2.       Select * from 表名;

例:SELECT * FROM t_student;

两者区别:  前者可以通过改变查询字段的顺序来调整查询结果显示的顺序.

2.2 查询指定字段

Select 字段1,字段2,字段3……From 表名;

例:/*查询t_student表的所有age,sex,gradeName字段*/

SELECT age,sex,gradeName FROM t_student;

 

 

2.3 Where条件查询

1.       Select 字段1,字段2,字段3……From 表名 Where 条件表达式;

例: 查询编号为1的学生

SELECT * FROM t_student WHERE id =1;

 

例: 查询年龄大于22的学生

SELECT * FROM t_student WHERE age>22;

 

例: 查询性别为男的学生

SELECT * FROM t_student WHERE sex='男';

2.4 带IN关键字查询

1.       Select 字段1,字段2,字段3……From 表名 Where 条件表达式 [NOT] IN(元素1,元素2,元素3);

例: 查询年龄为22或者23的学生记录

SELECT * FROM t_student WHERE age IN (22,23);

 

例: 查询编号不为1和9的学生记录

SELECT * FROM t_student WHERE id NOT IN(1,9);

 

2.5 带BETWEEN的范围查询

1.       Select 字段1,字段2,字段3……From 表名 Where 条件表达式 [NOT] BETWEEN 数值1 AND 数值2;

例: 查询编号为1-9的学生记录

SELECT * FROM t_student WHERE id BETWEEN 1 AND 9;

 

例: 查询年龄小于22大于25的学生记录

SELECT * FROM t_student WHERE age NOT BETWEEN 22 AND 25;

 

2.6 带Like的模糊查询

Select 字段1,字段2,字段3……From 表名 Where 条件表达式 [NOT] Like ‘字符串’;

‘%’: 代表任意字符,可以有或者没有

‘_’: 代表单个字符,必须要有

 

例: 查询姓名中包含张的学生记录

SELECT * FROM t_student WHERE stuName LIKE '%张%';

 

例: 查询姓名中第一个字为张的学生记录

SELECT * FROM t_student WHERE stuName LIKE '张%';

 

例: 查询姓名中第一个字为张,并且姓名只有2个字的学生记录

SELECT * FROM t_student WHERE stuName LIKE '张_';

2.7 空值查询

Select 字段1,字段2,字段3……From 表名 Where 条件表达式 IS[NOT] NULL;

例: 查询性别为null的学生记录

SELECT * FROM t_student WHERE sex IS NULL;

 

例: 查询性别不为null的学生记录

SELECT * FROM t_student WHERE sex IS NOT NULL;

2.8     带AND的多条件查询

Select 字段1,字段2,字段3……From 表名 Where 条件表达式1 AND 条件表达式2[...AND 条件表达式N];

例: 查询一年级中性别为男的学生记录

SELECT * FROM t_student WHERE gradeName='一年级' AND sex='男';

 

例: 查询二年级中年龄为22-24的学生记录

SELECT * FROM t_student WHERE gradeName='二年级' AND age BETWEEN 22 AND 24;

 

2.9 带OR的多条件查询

Select 字段1,字段2,字段3……From 表名 Where 条件表达式1 OR 条件表达式2[...OR 条件表达式N];

例: 查询年级为一年级或者年龄为23的学生记录

SELECT * FROM t_student WHERE gradeName='一年级' OR age=23;

 

2.10  DISTINCT去重复查询

Select Distinct 字段名 From 表名;

例子: 查询学生表所有的年级

SELECT DISTINCT gradeName FROM t_student ;

不加DISTINCT会有很多重复记录

 

2.11对查询结果进行排序

Select 字段1,字段2,字段3……From 表名ORDER BY 属性名 [ASC|DESC]

例: 查询所有学生记录并按年龄降序排序

SELECT * FROM t_student ORDER BY age DESC;

 

2.12 GROUP BY 分组查询

Select 字段1,字段2,字段3……From 表名 GROUP BY属性名;[HAVING 条件表达式][WITH ROLLUP];

1.       单独使用(毫无意义);

2.       与GROUP_CONCAT()函数一起使用;

3.       与聚合函数一起使用;

4.       与HAVING一起使用(对查询结果的筛选);

5.       与WITH ROLLUP一起使用(最后加入一个总和行);

例: 查询每个年级的所有学生姓名

SELECT gradeName,GROUP_CONCAT(stuName) FROM t_student GROUP BY gradeName;

 

例: 查询每个年级的学生个数

SELECT COUNT(stuName) AS '学生数量',gradeName AS '年级' FROM t_student GROUP BY gradeName;

 

例: 查询每个年级的学生个数并且选出学生数量大于3的年级

SELECT COUNT(stuName) AS '学生数量',gradeName AS '年级' FROM t_student GROUP BY gradeName HAVING COUNT(stuName)>3;

 

例: 查询每个年级的学生个数并在末尾加入一个总和行

SELECT COUNT(stuName) AS '学生数量',gradeName AS '年级' FROM t_student GROUP BY gradeName WITH ROLLUP;

 

2.13 LIMIT 分页查询

Select 字段1,字段2,字段3……From 表名 LIMIT 初始位置,记录数;

例: 查询所有学生记录的前5条记录

SELECT * FROM t_student LIMIT 0,5;

 

三:总结

单表查询就到此结束,大家要多多练习,谢谢大家,下期为大家带来聚合函数的使用.MySQL(基础篇)之单表查询

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment