当前位置:网站首页>SQL advanced syntax
SQL advanced syntax
2022-07-02 23:08:00 【yiixiou】
Insert data one
INSERT INTO tab_name (col_name) VALUES ( The data to be inserted , Here is the first line of data ), ( The data to be inserted , Here is the second line of data )…( The data to be inserted , The first n Row data )
Example : Insert two users' test papers to answer exam_record In the table ,
(1) user 1001 stay 2021 year 9 month 1 On Tuesday night 10 spot 11 branch 12 Begin to answer the test paper in seconds 9001, And in 50 Submit in minutes , got 90 branch ;
(2) user 1002 stay 2021 year 9 month 4 The morning of 7 spot 1 branch 2 Begin to answer the test paper in seconds 9002, And in 10 Minutes later, he exited the platform .( Be careful , user 1002 Failed to complete the examination paper , therefore submit_time and score The values of the two columns are null)
Method 1 : Specify insert column name
INSERT INTO exam_record (uid, exam_id, start_time, submit_time, score) VALUES
(1001, 9001, '2021-09-01 22:11:12', '2021-09-01 23:01:12', 90),
(1002, 9002, '2021-09-04 07:01:02', NULL, NULL)
Method 2 : hold id Is set to null or 0, Give Way mysql Self increasing
INSERT INTO exam_record VALUES
(NULL, 1001, 9001, '2021-09-01 22:11:12', '2021-09-01 23:01:12', 90),
(NULL, 1002, 9002, '2021-09-04 07:01:02', NULL, NULL)
Method 3 : Fill in directly id value
INSERT INTO exam_record VALUES
(1, 1001, 9001, '2021-09-01 22:11:12', '2021-09-01 23:01:12', 90),
(2, 1002, 9002, '2021-09-04 07:01:02', NULL, NULL)
Insert data 2
Insert method summary :
1、 Normal insert ( Full field ):INSERT INTO table_name VALUES (value1, value2, …)
2、 Normal insert ( Restricted field ):INSERT INTO table_name (column1, column2, …) VALUES (value1, value2, …)
3、 Multiple one-time inserts :INSERT INTO table_name (column1, column2, …) VALUES (value1_1, value1_2, …), (value2_1, value2_2, …), …
4、 Import from another table :INSERT INTO table_name(column1, column2, …) SELECT (column1, column2, …) FROM table_name2 [WHERE key=value]
Topic 1 : Do data backup , take exam_record In the table 2021 Back up the contents of years ago to exam_record_before_2021 In the table .
insert into exam_record_before_2021(uid, exam_id, start_time, submit_time, score)
select uid, exam_id, start_time, submit_time, score from exam_record
where year(submit_time)<'2021'
Topic two : There is a set ID by 9003 High difficulty SQL The examination paper , For an hour and a half , Need to put 2021-01-01 00:00:00 Insert it into the test question information table as the release time , No matter ID Whether it exists or not must be inserted successfully .
Method 1 : Use replace into.replace into First try inserting the data list , If you find that this row of data already exists in the table , Delete this row of data first , Then insert the new data , Otherwise, insert new data directly .
replace into examination_info values
(null,9003,'SQL','hard',90,'2021-01-01 00:00:00')
Method 2 : Use insert into, But need (delete) The priority of deleting user name is 9003 The data of .
delete from examination_info
where exam_id=9003;
insert into examination_info
values(null,9003,'SQL','hard',90,'2021-01-01 00:00:00')
Update data one
Modification method summary :
1、 Set to new value :
UPDATE table_name
SET column_name=new_value
WHERE column_name3=value3
for example , take tag Field PYTHON To Python:
update examination_info
set tag='Python'
where tag='PYTHON'
2、 Replace... With existing values :( It can be replaced by the whole string Substring substitution !)
UPDATE table_name
SET key1=replace(key1, ' Find content ', ' Replace with the content ')
WHERE column_name3=value3
for example , take tag Field PYTHON To Python:( Whole string replacement )
update examination_info
set tag=replace(tag,"PYTHON","Python")
where tag='PYTHON'
Substring substitution , take APYTHON Replace with APython:
update examination_info
set tag=replace(tag,"PYTHON","Python")
where tag like "%PYTHON%"
Delete record
Deletion method summary :
1、 Delete... According to conditions :
DELETE FROM tb_name
WHERE options
ORDER BY fields LIMIT n
2、 Delete all ( The watch is empty , Including self incrementing counter reset ):
TRUNCATE tb_name
Cattle guest . SQL8 Delete record 3
Be careful , Use delete from Deleting a table requires manual auto increment ID, In terms of efficiency , Or delete all (TRUNCATE tb_name) More efficient . Last time I used delete from The solution of deletion is :
delete from exam_record;
alter table exam_record auto_increment=1;
Create a new table
The operation of the table : establish 、 modify 、 Delete .
1、 Create tables directly
Cattle guest . SQL9 Create a new table
2、 Copy the table structure from another table to create a table
3、 Create a table from the query results of another table
4、 Modify table
{ ADD COLUMN < Name > < type > -- Add column
| CHANGE COLUMN < Old column names > < New column names > < New column type > -- Modify the column name or type
| ALTER COLUMN < Name > { SET DEFAULT < The default value is > | DROP DEFAULT } -- modify / Delete Default value of column
| MODIFY COLUMN < Name > < type > -- Modify column type
| DROP COLUMN < Name > -- Delete column
| RENAME TO < The new name of the table > -- Modify the name of the table
| CHARACTER SET < Character set name > -- Modify character set
| COLLATE < Proofreading rule name > } -- Modify proofreading rules ( When comparing and sorting )
Cattle guest . SQL10 Modify table
5、 Delete table
drop table if exists Table name 1, Table name 2....
Cattle guest . SQL11 Delete table
Index creation and deletion
Index creation 、 Delete 、 Use :
1、create How to create an index
CREATE INDEX Index name ON Table name ( Name ); -- If you do not specify a unique or full-text index, it defaults to normal index
CREATE UNIQUE INDEX Index name ON Table name ( Name ); -- unique index
CREATE FULLTEXT INDEX Index name ON Table name ( Name ); -- Full-text index
Cattle guest . SQL12 Create index
2、alter How to create an index
alter Basic format of index creation :
alter table Table name add unique index Index name ( Name ); -- unique index
alter table Table name add fulltext Index name ( Name ); -- Full-text index
alter table Table name add index Index name ( Name ); -- If you do not specify a unique or full-text index, it defaults to normal index
3、drop To delete the index
DROP INDEX < Index name > ON < Table name >
Cattle guest . SQL13 Delete index
Cattle guest . SQL13 Delete index :
DROP INDEX uniq_idx_exam_id ON examination_info;
DROP INDEX full_idx_tag ON examination_info;
4、alter To delete the index
ALTER TABLE < Table name > DROP INDEX < Index name >
Cattle guest . SQL13 Delete index :
alter table examination_info drop index uniq_idx_exam_id;
alter table examination_info drop index full_idx_tag;
Aggregate group query
Cattle guest . SQL16 Not less than the lowest score of the average
Cattle guest . SQL17 Average number of active days and monthly number of active people
SUBSTR(str,pos,len): from pos Starting position , Intercept len Characters .
SUBSTR(str,pos): pos Starting position , Cut it all the way to the end .
Multi-table query
Cattle guest . SQL45 Intercept the long nickname
length function : Calculate the length of the value , but 1 Chinese will count as length 3,1 Numbers or letters count as length 1;
char_length function : Calculate the length of the value , but 1 Chinese or 1 Numbers or letters count as length 1;
边栏推荐
- 门牌制作 C语言
- Introduction and response to high concurrency
- STM32之ADC
- Redis 过期策略+conf 记录
- Mask R-CNN
- 从底层结构开始学习FPGA----Xilinx ROM IP的定制与测试
- Array advanced improvement
- Jerry's prototype will trigger shutdown after multiple touches [chapter]
- Go multithreaded data search
- [leetcode] reverse the word III in the string [557]
猜你喜欢

The first batch of Tencent cloud completed the first cloud native security maturity assessment in China

Start from the bottom structure to learn the customization and testing of FPGA --- Xilinx ROM IP
![[chestnut sugar GIS] ArcScene - how to make elevation map with height](/img/91/f3df0a7633263c6264cb5c27eb149f.png)
[chestnut sugar GIS] ArcScene - how to make elevation map with height
![P7072 [csp-j2020] live broadcast Award](/img/bc/fcbc2b1b9595a3bd31d8577aba9b8b.png)
P7072 [csp-j2020] live broadcast Award

Methods to solve the tampering of Chrome browser and edeg browser homepage

Construction of Hisilicon 3559 universal platform: rotation operation on the captured YUV image

World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection

密码技术---分组密码的模式

数据分析学习记录--用EXCEL完成简单的单因素方差分析
![[NPUCTF2020]ezlogin xPATH注入](/img/6e/dac4dfa0970829775084bada740542.png)
[NPUCTF2020]ezlogin xPATH注入
随机推荐
Strictly abide by the construction period and ensure the quality, this AI data annotation company has done it!
从2022年Q1财报看携程的韧性和远景
ServletContext learning diary 1
AES高級加密協議的動機闡述
分布式监控系统zabbix
AES高级加密协议的动机阐述
深度剖析数据在内存中的存储----C语言篇
【硬件】标准阻值的由来
MySQL queries nearby data And sort by distance
Local dealers play the community group purchase mode and share millions of operations
Lambda表达式:一篇文章带你通透
Antd component upload uploads xlsx files and reads the contents of the files
[npuctf2020]ezlogin XPath injection
Loss function~
xshell配置xforward转发火狐浏览器
Sword finger offer II 099 Sum of minimum paths - double hundred code
[leetcode] number of palindromes [9]
Uniapp wechat login returns user name and Avatar
海思 VI接入视频流程
[leetcode] reverse string [344]