首页 > 其他分享 >【WEEK5】 【DAY5】DML Language【English Version】

【WEEK5】 【DAY5】DML Language【English Version】

时间:2024-03-30 15:58:19浏览次数:20  
标签:COMMENT Language -- DAY5 DML foreign table NULL data

2024.3.29 Friday

Contents

3. DML Language

3.1. Foreign Keys (For Understanding)

3.1.1. Concept

  • If a common key is the primary key in one relationship, then this common key is called the foreign key in another relationship. It can be seen that the foreign key represents the correlation between two relationships. The table with the foreign key acting as the primary key is called the primary table, and the table that possesses this foreign key is called the foreign table of the primary table.
  • In practice, a table’s values are placed into a second table to represent the association, using the primary key value(s) of the first table (including composite primary key values when necessary). At this time, the attribute in the second table that stores these values is called a foreign key.

3.1.2. Purpose

Maintains data consistency and integrity, with the main purpose being to control the data stored in the foreign key table, constraining it. It forms an association between two tables, where the foreign key can only refer to the values of columns in the external table or use null values.

3.1.3. Several Methods to Add (Write) Foreign Keys

3.1.3.1. Creating the Table with Direct Reference Inside (the part being referenced of the referenced table)

In this example, grade is the referenced (primary) table, and student is the referencing (foreign) table.

-- Adding a foreign key part 1 --
CREATE TABLE `grade`(
	`gradeid` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'grade id',
	`gradename` VARCHAR(50) NOT NULL COMMENT 'grade name',
	PRIMARY KEY (`gradeid`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

-- Student information table (student number, name, gender, grade, phone, address, birthdate, email, ID number)
CREATE TABLE `student` (
	`studentno` INT(4) NOT NULL COMMENT 'student number',
	`studentname` VARCHAR(20) NOT NULL DEFAULT 'Anonymous' COMMENT 'name',
	`sex` TINYINT(1) DEFAULT '1' COMMENT 'gender',

	# This line is not for linking the 'grade' table, but indicates "to reference"
	`gradeid` INT(10) DEFAULT NULL COMMENT 'grade',

	`phoneNum` VARCHAR(50) NOT NULL COMMENT 'phone',
	`address` VARCHAR(255) DEFAULT NULL COMMENT 'address',
	`borndate` DATETIME DEFAULT NULL COMMENT 'birthday',
	`email` VARCHAR(50) DEFAULT NULL COMMENT 'email',
	`idCard` VARCHAR(18) DEFAULT NULL COMMENT 'ID number',
	PRIMARY KEY (`studentno`),
	
	KEY `FK_gradeid` (`gradeid`),		-- Where FK_ is the default name, the purpose (of defining a foreign key) is to reference grade table's gradeid
	
	CONSTRAINT `FK_gradeid` FOREIGN KEY (`gradeid`) REFERENCES `grade` (`gradeid`)
	# Adds constraint to the foreign key and references a specific field in another table
) ENGINE=INNODB DEFAULT CHARSET=utf8

Opening the student table design view to see the foreign key will show the following
Insert image description here

3.1.3.2. Creating the Table First, Then Modifying It to Add Foreign Keys

Note: Different from the previous method, everything related to the foreign key needs to be retained in the foreign table’s first writing except for the last 2 lines (placed in the later addition).

-- Adding a foreign key part 2 --
CREATE TABLE `grade`(
	`gradeid` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'grade id',
	`gradename` VARCHAR(50) NOT NULL COMMENT 'grade name',
	PRIMARY KEY (`gradeid`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

-- Student information table (student number, name, gender, grade, phone, address, birthdate, email, ID number)
CREATE TABLE `student` (
	`studentno` INT(4) NOT NULL COMMENT 'student number',
	`studentname` VARCHAR(20) NOT NULL DEFAULT 'Anonymous' COMMENT 'name',
	`sex` TINYINT(1) DEFAULT '1' COMMENT 'gender',
	`gradeid` INT(10) DEFAULT NULL COMMENT 'grade',
	`phoneNum` VARCHAR(50) NOT NULL COMMENT 'phone',
	`address` VARCHAR(255) DEFAULT NULL COMMENT 'address',
	`borndate` DATETIME DEFAULT NULL COMMENT 'birthday',
	`email` VARCHAR(50) DEFAULT NULL COMMENT 'email',
	`idCard` VARCHAR(18) DEFAULT NULL COMMENT 'ID number',
	PRIMARY KEY (`studentno`)		-- Cannot add a comma as the last line in brackets
) ENGINE=INNODB DEFAULT CHARSET=utf8

ALTER TABLE `student`
ADD CONSTRAINT `FK_gradeid` FOREIGN KEY(`gradeid`) REFERENCES `grade` (`gradeid`);
3.1.3.3. All the above operations are physical foreign keys, database-level foreign keys, which are not recommended to use excessively -> To avoid too many databases

Best Practice

  • The database is simply a table used for data storage, only containing rows (data) and columns (fields).
  • To use data from multiple tables (foreign keys) --> Switch to implementing with programs

3.1.4. Deletion

When deleting tables with a primary-foreign key relationship, the foreign table must be deleted first, followed by the primary table, otherwise the primary table cannot be deleted.
For example, deleting the grade table mentioned above:
Insert image description here

3.2. DML Language (Data Manipulation Language)

3.2.1. Database Significance

Data storage, data management

3.2.2. Methods to Manage Database Data

  • Through management tools like Navicat, SQLyog, etc., to manage database data
  • Through DML statements to manage database data

3.2.3. DML Language: Data Manipulation Language

  • Used to operate the data contained within database objects
  • Includes:
    • INSERT (Statement to add data)
    • UPDATE (Statement to update data)
    • DELETE (Statement to delete data)

3.2.4. Adding

-- Insert statement (adding) --
INSERT INTO table_name([column_name1, column_name2, column_name3, ...]) VALUES ('value1'), ('value2'), ('value3'), ('value4'), ...) or in the form of ('value1', 'value2', 'value3', ...)
  1. The simplest case: the table has only one column, essentially whether you write (gradename) or not, it will automatically add the value to this column.
INSERT INTO `grade` (`gradename`) VALUES ('undergraduate')

Insert image description here

  1. To add multiple rows of data for the same field simultaneously, each piece of data must be separated by parentheses and commas.
-- To add multiple rows of data for the same field simultaneously, each piece of data must be separated by parentheses and commas
INSERT INTO `grade` (`gradename`) VALUES ('sophomore'), ('junior')

Insert image description here (corresponding to ids 4~5)

  1. If adding data for different fields in the same row simultaneously, you don’t need to separate each piece of data with parentheses, but pay attention to the one-to-one correspondence between data and field names.
-- If adding data for different fields in the same row simultaneously, no need to separate each piece of data with parentheses, but ensure the data matches the field names, as follows
INSERT INTO `student` (`studentname`, `phoneNum`) VALUES ('DL','1234567')
INSERT INTO `student` (`studentno`, `studentname`, `phoneNum`, `borndate`) VALUES ('1','DL','9876','1021')
INSERT INTO `student` (`studentno`, `studentname`, `phoneNum`, `borndate`) VALUES ('2','DL','9876','2222-10-21')

Insert image description here

  1. Notes
  • Separate fields or values with commas.
  • The part ‘field1, field2…’ can be omitted, but the values added must correspond to the table structure, data columns, and their order, and the quantity must be consistent.
  • Multiple pieces of data can be inserted simultaneously, separated by commas after values.

3.2.5. Modification

-- Modification statement --
UPDATE table_name SET column_name=value [,column_name2=value2,...] [WHERE condition];
  1. If no condition is specified, all data in that field will be changed.
-- If no condition is specified, all data in that field will be changed
UPDATE `student` SET `studentname` = 'momo'

Insert image description here

  1. Use a specific field value as a filter to modify the value of that row’s field.
-- Use a specific field value as a filter to modify the value of that row's field
UPDATE `student` SET `studentname` = 'DL' where `studentno` = 1;

Insert image description here

  1. To modify multiple field attributes, just follow SET with multiple assignments.
-- To modify multiple field attributes, just follow SET with multiple assignments
UPDATE `student` SET `studentname` = 'QW', `address` = 'quagmire' where `studentno` = 2;

Insert image description here

  1. Locate data through multiple conditions.
-- Locate data through multiple conditions
UPDATE `student` SET `studentname` = 'dl' WHERE studentno = 0 AND phoneNum = 1234567;

Insert image description here

  1. Insert the current time.
-- Insert the current time
UPDATE `student` SET `borndate` = CURRENT_TIMESTAMP WHERE studentno = 0 OR phoneNum = 1234567;

Insert image description here

  1. Notes
  • column_name is the data column to be changed.
  • value is the data after modification, which can be a variable, specific value, expression, or nested SELECT result.
  • condition is the filtering condition. If not specified, it modifies all column data in the table.
  1. Where condition statement
    Insert image description here
    For example:
UPDATE `student` SET `studentname` = 'as', `address` = 'quagmire' WHERE studentno BETWEEN 0 AND 2;

Insert image description here

3.2.6. Deletion

  1. DELETE
DELETE FROM table_name [WHERE condition];

condition is the filtering condition. If not specified, it deletes all column data in the table.
For example:

-- Delete statement --
-- Not recommended to write like this, it deletes everything
DELETE FROM `student`
-- Selectively delete
DELETE FROM `student` WHERE studentno = 1;

Insert image description here

  1. TRUNCATE
TRUNCATE [TABLE] table_name;

Purpose: Completely clears table data, but table structure, indexes, constraints remain unchanged.
For example:

TRUNCATE `student`
  1. Differences between DELETE and TRUNCATE
  • Similarities: Both can delete data, not the table structure, but TRUNCATE is faster.
  • Differences:
    • Using TRUNCATE TABLE will reset the AUTO_INCREMENT counter.
    • Using TRUNCATE TABLE does not affect transactions.
  1. Test
-- Test
CREATE TABLE `test`(
	`id` INT(4) NOT NULL AUTO_INCREMENT,
	`coll` VARCHAR(20) NOT NULL,
	PRIMARY KEY(`id`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

#Insert test data
INSERT INTO `test`(`coll`) VALUES('row1'),('row2'),('row3');
#Delete table data
DELETE FROM test;
#Insert again, notice id starts from 4 not 1
INSERT INTO `test`(`coll`) VALUES('row1'),('row2'),('row3');

TRUNCATE TABLE test;
#Insert again, notice id starts from 1 not 7
INSERT INTO `test`(`coll`) VALUES('row1'),('row2'),('row3');
Conclusion: Using truncate to delete data resets the auto-increment value to start over; does not log the operation.
Similarly, using DELETE to clear data from tables with different engine types. After restarting the database service, using different data engines:
InnoDB: Auto-increment columns start over from the initial value (stored in memory, lost on power off)
MyISAM: Auto-increment columns continue from the last auto-increment value (stored in files, not lost)

标签:COMMENT,Language,--,DAY5,DML,foreign,table,NULL,data
From: https://blog.csdn.net/2401_83329143/article/details/137160528

相关文章

  • 【WEEK5】 【DAY5】DML语言【中文版】
    2024.3.29Friday目录3.DML语言3.1.外键(了解)3.1.1.概念3.1.2.作用3.1.3.添加(书写)外键的几种方法3.1.3.1.创建表时直接在主动引用的表里写(被引用的表的被引用的部分)3.1.3.2.先创建表后修改表以添加外键3.1.3.3.以上操作都是物理外键,数据库级别的外键,不建议使用->避免数......
  • 云计算第1阶段_Linxu基础知识_day5
    yum补充#yum补充rpm-qa|grepvim#列出服务器已经安装过的包​#如果不合适,查看firewalld和SELinux开关状态getenforce#查看SELinux状态setenfotce0vim/etc/selinux/configSELINUX==>no​#查看防火墙状态systemctlstatusfirewalld#永久关闭防火墙systemct......
  • A Systematic Survey of Prompt Engineering in Large Language Models: Techniques a
    本文是LLM系列文章,针对《ASystematicSurveyofPromptEngineeringinLargeLanguageModels:TechniquesandApplications》的翻译。大型语言模型中提示工程的系统综述:技术与应用摘要1引言2提示工程3结论摘要提示工程已经成为扩展大型语言模型(LLM)和视......
  • Large Language Models As Evolution Strategies
    本文是LLM系列文章,针对《LargeLanguageModelsAsEvolutionStrategies》的翻译。作为进化策略的大型语言模型摘要1引言2相关工作3背景4将LLMS转化为ES算法5LLMS作为零样本进化策略6EVOLLM消融研究7EVOLLM与教师微调8讨论摘要大型Transformer模......
  • MySQL单表操作学习DDL_DML_DQL语句,以及模糊查询
    1.DDL语句CREATETABLE`student`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'学号',`creatDate`datetimeDEFAULTNULL,`userName`varchar(20)DEFAULTNULL,`pwd`varchar(36)DEFAULTNULL,`phone`varchar(11)DEFAULTNULL,`age`tinyi......
  • MySQL学习必备SQL_DDL_DML_DQL
    CREATETABLE`student`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'学号',`createDate`datetimeDEFAULTNULL,`userName`varchar(20)DEFAULTNULL,`pwd`varchar(36)DEFAULTNULL,`phone`varchar(11)DEFAULTNULL,`age`tinyint(3)u......
  • MySQL学习必备SQL_DDL_DML_DQL
    MySQL创建数据库需要自行创建,数据库名称可以为【schoolDB】,字符集【utf8】,排序规则【utf8_general_ci】。1、学生表DDLCREATETABLE`student`( `id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'学号', `createDate`datetimeDEFAULTNULL, `userName`varchar(2......
  • Large Language Models Based Fuzzing Techniques: A Survey
    本文是LLM系列文章,针对《LargeLanguageModelsBasedFuzzingTechniques:ASurvey》的翻译。基于大型语言模型的模糊化技术综述摘要1引言2背景3基于LLM的模糊测试分析4关于未来工作和挑战的讨论5结论摘要在软件发挥关键作用的现代,软件安全和漏洞分析......
  • Stepwise Self-Consistent Mathematical Reasoning with Large Language Models
    本文是LLM系列文章,针对《StepwiseSelf-ConsistentMathematicalReasoningwithLargeLanguageModels》的翻译。基于大型语言模型的逐步自洽数学推理摘要1引言2相关工作3TriMaster100数据集4循序渐进的自洽思维链5实验6结论摘要使用大型语言模型进......
  • MySQL学习必备SQL_DDL_DML_DQL
     MySQL创建数据库需要自行创建,数据库名称可以为【schoolDB】,字符集【utf8】,排序规则【utf8_general_ci】,1.学生表DDLCREATETABLE`student`( `id`INT(11)NOTNULLAUTO_INCREMENTCOMMENT'学号', `createDate`datetimeDEFAULTNULL, `userName`VARCHAR(......