当前位置:网站首页>SQL learning (1) - table related operations
SQL learning (1) - table related operations
2022-07-27 01:11:00 【Although Beihai is on credit, Fuyao can take it】
Catalog
Link to the original text :https://github.com/datawhalechina/wonderful-sql
course demo:https://tour.pingcap.com/
Video link :https://www.bilibili.com/video/BV1pZ4y117W3/?spm_id_from=333.788&vd_source=7f8a29f8895e96fac156aef0574baa6a
1. Database creation and deletion
-- Create Syntax
CREATE DATABASE < Database name > ;
-- Homework example
create database task01;
-- Delete Syntax
Drop DATABASE < Database name > ;
2. Create and delete tables
2.1. data type
INTEGER type
Used to specify the data type of the column where integers are stored ( Digital ), Can't store decimals .
CHAR type
Used to store fixed length strings , When the length of the string stored in the column does not reach the maximum length , Use half space to complement , Because it wastes storage space , So I don't use .
VARCHAR type
Used to store variable length strings , Fixed length string will be supplemented with half width spaces when the number of characters does not reach the maximum length , But variable length strings are different , Even if the number of characters does not reach the maximum length , I don't use half space to make up .
DATE type
Used to specify the storage date ( Specific date ) The data type of the column of ( Date type ).
2.2. Setting of constraints
Constraints are in addition to data types , The function of restricting or appending conditions to the data stored in a column .
NOT NULL Yes no empty constraint , That is, data must be entered in the column .
PRIMARY KEY It's a primary key constraint , Represents that the column is unique , You can get the data of a specific row through this column .
2.3. Create new table
-- grammar
CREATE TABLE < Table name >
( < Name 1> < data type > < Constraints required for this column > ,
< Name 2> < data type > < Constraints required for this column > ,
< Name 3> < data type > < Constraints required for this column > ,
< Name 4> < data type > < Constraints required for this column > ,
.
< Constraints for this table 1> , < Constraints for this table 2> ,……);
-- Homework example
CREATE TABLE Addressbook
(regist_no INT NOT NULL,
name VARCHAR(128) NOT NULL,
address VARCHAR(256) NOT NULL,
tel_no VARCHAR(20) ,
mail_address VARCHAR(20) ,
PRIMARY KEY (regist_no));
ALTER TABLE Addressbook ADD COLUMN postal_code CHAR(8);
2.4. Delete table
Here's the thing to watch out for , Deleted tables cannot be recovered , It can only be re inserted , Please be very careful when deleting .
Delete table Syntax :
DROP TABLE < Table name > ;
DROP TABLE Addressbook ;
-- Clear table contents
-- advantage : comparison drop / delete,truncate When used to clear data , The fastest .
TRUNCATE TABLE TABLE_NAME;
2.5. Column processing in the table
ALTER TABLE Statement and DROP TABLE The sentence is the same , Cannot recover after execution . Mistakenly added columns can be through ALTER TABLE Statement delete , Or delete all the tables and create them again .
-- Insert new column
ALTER TABLE < Table name > ADD COLUMN < Definition of columns >;
ALTER TABLE Addressbook ADD COLUMN postal_code VARCHAR(8);
-- Delete column
ALTER TABLE < Table name > DROP COLUMN < Name >;
-- Delete a specific row in the table ( grammar )
-- Be sure to add WHERE Conditions , Otherwise, all data will be deleted
DELETE FROM product WHERE COLUMN_NAME='XXX';
3. Data processing in the table
3.1. Insert one line
After the table is created , You can insert data into the table
-- Basic grammar
INSERT INTO < Table name > ( Column 1, Column 2, Column 3, ……) VALUES ( value 1, value 2, value 3, ……);
-- Examples
-- Contains a list of columns
INSERT INTO Addressbook (regist_no,name,address,tel_no,mail_address,postal_code)
VALUES (001,'zxx','DHU',139,'[email protected]',201620);
-- Omit the list
INSERT INTO Addressbook VALUES (001,'zxx','DHU',139,'[email protected]',201620);
3.2. Multi line insertion
INSERT INTO Addressbook VALUES (001,'zxx','DHU',139,'[email protected]',201620),
(002,'zxy','DHU',139,'[email protected]',201620),
(003,'wzy','DHU',139,'[email protected]',201620);
3.3. Copy the data
have access to INSERT … SELECT Statement to copy data from other tables .
-- Copy the data in the address table to the address replication table
INSERT INTO Addressbookcopy (regist_no,name,address,tel_no,mail_address,postal_code)
SELECT regist_no,name,address,tel_no,mail_address,postal_code
FROM Addressbook;
3.4. Update and delete data
3.4.1. Single column update
-- grammar
UPDATE < Table name >
SET < Name > = < expression > [, < Name 2>=< expression 2>...]
WHERE < Conditions > -- Optional , It's very important
ORDER BY Clause -- Optional
LIMIT Clause ; -- Optional
Use update Pay attention to adding where Conditions , Otherwise, all rows will be modified according to the statement
-- Modify all registration numbers
UPDATE Addressbook
SET regist_no = 001;
-- Only modify the number of some people
UPDATE Addressbook
SET regist_no = regist_no * 10
WHERE name = 'zxx';
3.4.2. Multi column update
UPDATE Of the statement SET Clause supports multiple columns as update objects at the same time .
-- Basic writing , One UPDATE Statement updates only one column
UPDATE Addressbook
SET regist_no = regist_no * 10
WHERE name = 'wzy';
UPDATE Addressbook
SET regist_no = regist_no + 10
WHERE name = 'zxy';
This writing can get the correct result , But the code is cumbersome . You can simplify the code by merging .
-- The combined writing
UPDATE Addressbook
SET regist_no = regist_no * 10,
postal_code = postal_code +10
WHERE name = 'zxx';
Update error :Error Code:1175.You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
mysql This error occurs when the delete update statement is executed , Because in mysql stay safe-updates In the pattern , If you where The following condition is not a primary key id, Then there will be such a mistake .
There are two solutions
-- Execute this command to change mysql database schema .
SET SQL_SAFE_UPDATES = 0;
-- stay where Follow the primary key in the judgment condition id
UPDATE Addressbook
SET regist_no = regist_no * 10
WHERE name = 'gyt'and regist_no>0;
4. Exercises Task01
-- 1.1
create database task01;
use task01;
CREATE TABLE Addressbook
(regist_no INT NOT NULL,
name VARCHAR(128) NOT NULL,
address VARCHAR(256) NOT NULL,
tel_no Char(10) ,
mail_address char(10) ,
PRIMARY KEY (regist_no));
-- 1.2
ALTER TABLE Addressbook ADD COLUMN postal_code CHAR(8);
select * from Addressbook;
-- 1.3
-- Please add the following SQL Statement to delete Addressbook surface .
drop table Addressbook;
-- 1.4 Judgment questions
-- Can I write SQL Statement to restore deleted Addressbook surface ?
-- Deleted tables cannot be recovered , It can only be re inserted , Please be very careful when deleting .
边栏推荐
- Flink1.11 多并行度watermark测试
- flink需求之—ProcessFunction(需求:如果30秒内温度连续上升就报警)
- onSaveInstanceState和onRestoreInstanceState方法的调用
- Uni-app开发App和插件以后如何开通广告盈利:uni-AD
- Spark数据倾斜解决办法
- MySQL uses and implements ranking functions rank and deny_ Rank and row_ NUMBER
- Which securities company has a low stock commission and which stock is safe to open an account
- DataNode Decommision
- Redisson working principle - source code analysis
- Tencent upgrades the live broadcast function of video Number applet. Tencent's foundation for continuous promotion of live broadcast is this technology called visual cube (mlvb)
猜你喜欢

SQL学习(2)——表的基础查询与排序

李宏毅机器学习(2017版)_P14:反向传播

FlinkSql多表(三表) join/interval join

flink需求之—SideOutPut(侧输出流的应用:将温度大于30℃的输出到主流,低于30℃的输出到侧流)

吴恩达深度学习系列教学视频学习笔记(一)——用于二分类的logistic回归函数

基于Flink实时计算Demo:用户行为分析(四:在一段时间内到底有多少不同的用户访问了网站(UV))

Doris或StarRocks Jmeter压测

Redis -- cache avalanche, cache penetration, cache breakdown

李宏毅机器学习(2021版)_P7-9:训练技巧

VSCode2015下编译darknet生成darknet.ext时error MSB3721:XXX已退出,返回代码为 1。
随机推荐
SQL学习(2)——表的基础查询与排序
腾讯云直播插件MLVB如何借助这些优势成为主播直播推拉流的神助攻?
李宏毅机器学习(2017版)_P13:深度学习
MYSQL中的行锁升级表锁的原因
Flink1.11 intervaljoin watermark generation, state cleaning mechanism source code understanding & demo analysis
Neo4j Basic Guide (installation, node and relationship data import, data query)
pytorch张量数据基础操作
The shortest way to realize video applets: from bringing goods to brand marketing
李宏毅机器学习(2017版)_P14:反向传播
One of the Flink requirements - sideoutput (Application of side output flow: output the temperature higher than 30 ℃ to the mainstream, and output the temperature lower than 30 ℃ to the side flow)
网站日志采集和分析流程
onSaveInstanceState和onRestoreInstanceState方法的调用
Flink1.11 Jdcb方式写mysql测试用例
MySQL index optimization: scenarios where the index fails and is not suitable for indexing
adb.exe已停止工作 弹窗问题
Zhimi Tencent cloud live mlvb plug-in optimization tutorial: six steps to improve streaming speed + reduce live delay
通过FlinkCDC将MySQL中变更的数据写入到kafka(DataStream方式)
MLVB 云直播新体验:毫秒级低延迟直播解决方案(附直播性能对比)
Flink sliding window understanding & introduction to specific business scenarios
Golang implements AES with five encryption mode functions, encrypt encryption and decryption string output