当前位置:网站首页>Basic select statement
Basic select statement
2022-07-26 23:06:00 【Planning Department_ xiao_ cai_ ji】
List of articles
Information
according to 【MySQL Database tutorial ,mysql The installation to mysql senior , strong ! hard !】 Arrangement
The data link :
Baidu SkyDrive :
link :https://pan.baidu.com/s/1KboU_3EZJxrezMWZ2klP6g
Extraction code :1234
Alicloud disk
【MySQL】
1. Query constant calculation
grammar :
SELECT Constant operation expression 1, Constant operation expression 2, ...
[ FROM dual ];
SELECT 1+1, 3*2;
Query constants do not need to be looked up from the table , have access to dual ( False watch ) Complete the structure of the query statement .
SELECT 1+1, 3*2
FROM dual;
2. The basic syntax of a query statement
The basic syntax of a query statement :
SELECT Field 1, Field 2, ...
FROM Table name ;
2.1 Query all fields
grammar :
SELECT *
FROM Table name ;
*Represents all fields in the table .
Inquire about employees All fields in the table :
SELECT *
FROM employees;
In general , Unless you need to use all the field data in the table , Otherwise, it is best not to use wildcards * .
Using wildcards can save Enter the query statement Time for , However, getting unwanted column data often reduces the efficiency of queries and applications used .
The advantage of wildcards is , When you don't know the name of the desired column , You can get them through wildcards .
In production environment , Direct use is not recommended
SELECT *The query .
2.2 Query the specified field
grammar :
SELECT Field 1, Field 2, ...
FROM Table name ;
Specify the fields in the query table , You need to ensure that fields exist in the table , At the same time, make sure that the field name is spelled correctly .
Inquire about employees In the table employee_id、last_name、salary Field :
SELECT employee_id, last_name, salary
FROM employees;
3. Alias of column
When inquiring , You need to rename the queried fields ( Take the alias ), Keywords can be used AS (alias – Alias ).
Inquire about employees In the table employee_id、last_name、salary Field :
SELECT employee_id AS id,
last_name AS lname,
salary AS sal
FROM employees;
AS Keywords can be omitted
SELECT employee_id id,
last_name lname,
salary sal
FROM employees;
Field aliases can use a pair Double quotes Lead up , Don't use single quotes ( because MySQL The grammar is not rigorous , stay MySQL You can't make a mistake , However, errors will be reported in some databases ).
Add : Strings are enclosed in single quotes , Don't use double quotes , Will report a mistake .
SELECT employee_id AS "id",
last_name AS "lname",
salary AS "sal"
FROM employees;
The query results of the three statements are the same :
The alias of the field is enclosed in double quotation marks , In order to Include spaces or special characters in the alias and be case sensitive , If there is a space in the alias, be sure to wrap it in double quotation marks .
SELECT employee_id emp_id,
last_name AS lname,
department_id " department id",
salary * 12 AS "annual sal"
FROM employees;
4. Remove duplicate lines
By default , The query will return all rows , Include repeating lines .
Query which departments are in the employee table id:
No weight loss :
SELECT department_id
FROM employees;
De duplication ( Use keywords DISTINCT ):
SELECT DISTINCT department_id
FROM employees;
SELECT salary,DISTINCT department_id
FROM employees;
salary If there is no weight removal, it will all be displayed , DISTINCT department_id It's going to be weightless , The two clashed , Will report a mistake .
[42000][1064] You have an error in your SQL syntax;
check the manual that corresponds to your MySQL
server version for the right syntax to use
near 'DISTINCT department_id FROM employees'
at line 1
Yes department_id, salary Repeat and de duplicate the query results of both :
SELECT DISTINCT department_id, salary
FROM employees;
Only when department_id, salary Only records with the same values of the two fields will be de duplicated .
DISTINCT In fact, it is to de duplicate the combination of all the following column names .
The end result is 74 strip , Because of this 74 Departments in results id And salary There is no repetition after combination . If you want to see the different departments (department_id), You just need to writeDISTINCT department_idthat will do , There is no need to add other column names after .
5. Null values participate in the operation
Null value :null
stay MySQL in , A null value is not equal to an empty string . An empty string is of length 0 String , A null value means that there is no specific value .
null Not equal to 0 ( Values for 0, Not empty ),''( The length is 0 String , Not empty ),'null'( character string , Not empty ).
SELECT *
FROM employees;
Null values participate in the operation , The result must also be empty .
SELECT employee_id, salary AS " Monthly wages ",
salary*(1+commission_pct)*12 AS " Annual wage ",
commission_pct
FROM employees;
Because some records commission_pct The median value is empty , So the corresponding calculation of this record “ Annual wage ” Also empty .
Solutions to practical problems : introduce IFNULL()
SELECT
employee_id,
salary AS " Monthly wages ",
# If commission_pct It's empty , Use 0 To replace
salary*(1+IFNULL(commission_pct, 0))*12 AS " Annual wage ",
commission_pct
FROM employees;
6. mark of emphasis
mark of emphasis :` ( The top left corner of the keyboard ,1 side )
When the table name or field name is the same as the keyword , You need to use a bullet to quote the table name or field name .

SELECT *
FROM ORDER;
Report errors
[42000][1064] You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near 'ORDER' at line 1
SELECT *
FROM `order`;
We need to ensure that the fields in the table 、 Table names, etc. have no and reserved words 、 Database systems or common methods conflict . If it's really the same , stay SQL A pair of... Is used in the statement `( mark of emphasis ) Lead up .
7. Query constant
Constants will be spliced with each row of the query result .
SELECT
'hello',
123,
employee_id,
last_name
FROM employees;
8. Display table structure
grammar :
DESCRIBE Table name ;
Abbreviation :
DESC Table name ;
Show employees The structure of the table :
DESCRIBE employees;
DESC employees;
Query results , Shows the details of the fields in the table .
- among , The meanings of each field are explained as follows :
- (1) Field: Field name .
- (2) Type: Represents the field type
- (3) Null: Indicates whether the column can store NULL value .
- (4) Key: Indicates whether the column is indexed .PRI Indicates that the column is part of the table primary key ;UNI Indicates that the column is UNIQUE Part of index ;MUL Indicates that a given value is allowed to appear more than once in a column .
- (5) Default: Indicates whether the column has a default value , If there is , So what's the value .
- (6) Extra: Represents additional information about a given column that can be obtained , for example AUTO_INCREMENT etc. .
9. Filtering data
Use WHERE Words and expressions , Filter out rows that do not meet the criteria ,WHERE Clause in the wake of FROM Clause , The filter condition is declared in FROM Behind the structure .
grammar :
SELECT Field 1, Field 2, ...
FROM Table name
WHERE Filter conditions ;
Inquire about 90 Employee information of department No :
SELECT *
FROM employees
WHERE department_id=90;
Inquire about last_name by ‘King’ Employee information :
SELECT *
FROM employees
WHERE last_name='King';
SELECT *
FROM employees
WHERE last_name='king';
The query result of this statement is the same as the above
reason : stay windows In the environment , Case insensitivity leads to MySQL Is not case sensitive , But because of MySQL The imprecision of causes the case in the string to be indistinguishable , So the results of the above two sentences are the same .
This will not happen in other data .
stay windows Environment is not size sensitive , Refers to the field name , Table name , keyword , Exclude strings within quotation marks .
10. Basic SELECT Sentence practice
【 subject 】
# 1. Query employees 12 The sum of monthly wages , It's also called ANNUAL SALARY
# 2. Inquire about employees Remove duplicates from the table job_id Future data
# 3. Query salary greater than 12000 The name and salary of the employee
# 4. The employee number is 176 The name and department number of the employee
# 5. Display table departments Structure , And query all the data
【 answer 】
1. Query employees 12 The sum of monthly wages , It's also called ANNUAL SALARY
# understand 1 : Calculation 12 Monthly basic salary
SELECT
employee_id,
last_name,
salary*12 AS "ANNUAL SALARY"
FROM employees;
# understand 2 : Calculation 12 Monthly basic salary and bonus
SELECT
employee_id,
last_name,
salary*12*(1+IFNULL(commission_pct,0)) AS "ANNUAL SALARY"
FROM employees;
2. Inquire about employees Remove duplicates from the table job_id Future data
SELECT DISTINCT job_id
FROM employees;
3. Query salary greater than 12000 The name and salary of the employee
SELECT
last_name,
salary
FROM employees
WHERE salary>12000;
4. The employee number is 176 The name and department number of the employee
SELECT
last_name,
department_id
FROM employees
WHERE employee_id=176;
5. Display table departments Structure , And query all the data
DESC departments;
DESCRIBE departments;
SELECT *
FROM departments;
边栏推荐
- 你知道磁环电感的常见磁芯类型有哪些吗?
- 基于gRPC编写golang简单C2远控
- Monte Carlo search tree (UCT) based on confidence upper bound to realize four sub chess
- 摩尔定律的新推力,英特尔先进封装技术详解!
- Ribbon负载均衡
- 【flask高级】结合源码分析flask中的线程隔离机制
- Science | 华盛顿大学利用AI和结构预测设计全新蛋白质
- 沟通中经常用到的几个库存术语
- 云原生微服务第一章之服务器环境说明
- Introduction to the use of Jerry downloader forced download tool_ Ac695n696nad14ad15 full range support
猜你喜欢

黑马瑞吉外卖之新增员工

比海豹便宜,造型炸裂空间大,20万左右真没对手?长安全新“王炸”这样选才划算

每周招聘|PostgreSQL数据库研发工程师,年薪60+,名企高薪,挑战自我!

Too busy with scientific research to take care of your family? Chen Ting: life cannot have only one fulcrum

The most classic Nature paper on Alzheimer's disease is suspected of fraud

【flask高级】结合源码分析flask中的线程隔离机制

STM32 how to use serial port

面试:你印象最深的BUG,举个例子

Dao:op token and non transferable NFT are committed to building a new digital democracy

逆袭黑马:数据库全栈工程师(DevDBOps)培训,把最好的课程送给您!
随机推荐
国产DRAM年底将量产,但前路依旧漫漫!
工作一年后,我有些感悟(写于2017年)
After closing the Suzhou plant, Omron Dongguan plant announced its dissolution, and more than 2000 people are facing unemployment!
Monte Carlo search tree (UCT) based on confidence upper bound to realize four sub chess
HCIA-R&S自用笔记(20)VLAN综合实验、GVRP
2019 biometric forum successfully ended: these ten highlights should not be missed!
Counter attack dark horse: devdbops training, give you the best courses!
Science | University of Washington uses AI and structural prediction to design new proteins
APP信息侦察&夜神模拟器Burp抓包配置
[paper reading] logan:membership influence attacks against generative models
Introduction to the use of Jerry downloader forced download tool_ Ac695n696nad14ad15 full range support
[hcip] OSPF external route introduction
Huawei atlas900 reveals the secret: it integrates thousands of shengteng 910 chips, and its computing power is comparable to 500000 PCs!
Will the approval in advance affect the formal approval?
Professor Ashe, a Chinese scientist, made a positive response to the suspected fake Nature paper
数据库全栈工程师(DevDBOps)低首付、高回报,先就业后付款
ZTE: more than 50000 5g base stations have been shipped worldwide!
测试开发是开发吗?
[untitled]
Do you know the common core types of magnetic ring inductors?























