Database Introduction_03

SQL overview

SQL stands for Structured Query Language, which is a database application language that uses a relational model and directly deals with data
. It was developed by IBM in the 1970s. Later, the American National Bureau of Standards ANSI began to formulate SQL standards, including SQL-86, SQL-89, SQL-92, SQL-99 and other standards.

  • In 1974, IBM researchers published a paper "SEQUEL: A Structured English Query Language" that unveiled database technology. Until today, this structured query language has not changed much. Compared with other languages, SQL The half-life can be said to be very long
  • SQL has two important standards, namely SQL92 and SQL99, which respectively represent the SQL standards promulgated in 1992 and 1999, and the SQL language used today still follows these standards

Naming rules

  • Database and table names must not exceed 30 characters, and variable names are limited to 29 characters
  • Must only contain A–Z, a–z, 0–9, _ a total of 63 characters
  • Object names such as database names, table names, and field names should not contain spaces
  • In the same MySQL software, databases cannot have the same name; in the same library, tables cannot have the same name; in the same table, fields cannot have the same name
  • It must be ensured that the fields do not conflict with reserved words, database systems, or commonly used methods. If you insist, enclose the SQL statement with
    bullets
  • Keep the field names and types consistent. Be sure to ensure consistency when naming fields and specifying data types for them. If the data type is an integer in one table, don't change it to a character in another table
#以下两句是一样的,不区分大小写
show databases;
SHOW DATABASES;

#创建表格
#create table student info(...); #表名错误,因为表名有空格

create table student_info(...); #其中order使用``飘号,因为order和系统关键字或系统函数名等预定义标识符重名了

CREATE TABLE `order();

select id as "编号", `name` as "姓名" from t_stu; #起别名时,as都可以省略

select id as 编号, `name` as 姓名 from t_stu; #如果字段别名中没有空格,那么可以省
略""

select id as 编 号, `name` as 姓 名 from t_stu; #错误,如果字段别名中有空格,那么不
能省略""

DQL

sample table

create table tb_users(
id bigint primary key auto_increment,
username varchar(20) not null,
password varchar(24) not null,
birth date,
sex boolean default 1,
score numberic(8,2)
)engine=innodb default charset utf8;

grammar:

select [all/distinct] <目标表达式>,<目标表达式>,...
from 表名称或者视图名称,表名称或者视图名称,... -- 在MySQL中允许查询语句中没有from
where 条件语句
group by 分组条件 [having 条件表达式]
order by 排序条件 [asc/desc]
limit ...

1. View all the data in the table select * from tb_users, where the asterisk * is a wildcard, which means to get the values ​​of all columns

Using an asterisk in the query statement means to get all the columns in the table. If you only want to get some of the columns, such as only querying the user’s name
and password, you can write it asselect username,password from tb_users

SQL statements in MySQL are case-insensitive, so SELECT and select have the same function. However, many developers are accustomed
to uppercase keywords and lowercase data columns and table names, so that the written code is easier to read and maintain .

Interview: select *, mandatory rules in Ali's development specification, no asterisks are allowed, and require specifying the column names to be queried.
For exampleselect id,username,password,birth,sex,score from tb_users

  • Using an asterisk increases the parsing cost for the query analyzer
  • If you use a persistence layer framework such as MyBatis, adding and deleting fields is easy to operate and configure inconsistencies
  • Querying useless fields will increase network consumption, especially for large object fields such as text/blob
  • Using an asterisk may lose the covering index strategy optimization in the optimizer

Advantages of using asterisks:

  • To a certain extent, the amount of coding is reduced
  • The field names in the guidance table are not required, which can avoid the tedious writing of specific field names and clerical errors
  • When adding a new field, there is no need to modify the select code, which improves the code reuse rate to a certain extent

2. Query with conditions.
For example, view all user information whose age is greater than 18 in the table select * from tb_users where year(now())- year(birth)>18
For example, view all user information with an id value greater than or equal to 5 in the tableselect * from tb_users where id>=5;

  • Note that the equivalent judgment uses =, not ==. For example, to obtain user information with number 16, select * from tb_users where
    id=5; is a single equal sign, not a double equal sign. Equal judgment =, not equal judgment !=, greater than >, less than <, greater than or equal to >=, less than or equal to
    <=
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2022-04-18 17:00:32 |
+---------------------+
1 row in set (0.00 sec)
mysql> select year(now()); 
-- from子句在mysql中不是必须的,注意不同的数据库系统from要求不一样,
-- 例如在oracle中from不能少。进行一些简单计算时from可以省略,
-- 例如计算1+2的写法为select 1+2;
+-------------+
| year(now()) |
+-------------+
| 2022 |
+-------------+
1 row in set (0.00 sec)

3. Judgment of non-null or null value, note that you cannot use =null or !=null, you should use is null or is not null,
such as querying user information with unknown genderselect * from tb_users where sex is null;

4. String comparison

User loginselect * from tb_users where username='yan1' and password='**********';

Fuzzy query like/not like wildcards_和%

  • Wildcard _ means any character
  • The wildcard % means any number of arbitrary characters

For example, query all user information with the surname Zhangselect * from tb_users where username like '张%';

mysql> select * from c1 where name like 'yan_'; -- 以yan开头并且后面跟一个任意
字符
+------+------+
| id | name |
+------+------+
| 1 | yan1 |
| 2 | yan2 |
+------+------+
2 rows in set (0.00 sec)
mysql> select * from c1 where name like 'yan%'; -- 以yan开头并且后面跟任意个任
意字符
+------+--------+
| id | name |
+------+--------+
| 1 | yan1 |
| 2 | yan2 |
| 5 | yan |
| 5 | yan123 |
+------+--------+
4 rows in set (0.00 sec)

The wildcards _ and % can be anywhere in the string

  • y_ indicates a string containing two characters long and must start with y. For example y1 matches, y12 doesn't match, y doesn't match either

  • y% means a string starting with y followed by any number of arbitrary characters. For example ay does not match, y matches, y123 also matches

  • _y means a string containing two characters long and must end with y, for example, 1y matches, 12y does not match, and y does not match either

  • %y indicates a string ending with y and preceded by any number of any characters. For example ay matches, y matches, 12y1 does not match

  • y represents a string of three characters long, the middle character must be y

  • %y% indicates a string containing the character y, which can be at the beginning, at the end, or in the middle

5. Select several tuples in the table

A tuple is a combination of features of things that can be used to describe a specific thing.
A relationship is a two-dimensional table with a header, each row of data in the table is a tuple, the set of tuples is a relationship, and each column is
an attribute. In a two-dimensional table, tuples can also be called rows, and attributes are columns

  • Field: A feature of something, also known as an attribute or column
  • Table: A combination of record attributes, representing a combination of the same type of thing
  • Primary key: A combination of columns that can uniquely identify a row of data. A table can only have one primary key, but the primary key can be
    composed of multiple columns
  • Domain: the value range of the attribute
  • Relationship mode: It is the description of the relationship, the representation method [relationship name (property list, ...)], such as student (student number, name, gender,
    age)
  • Relationship constraints: entity integrity, referential integrity, user-defined integrity

Writing method: select * from tb_users where (id,name) > (1,'aaa');
select * from tb_users where id>1 and name>'aaa'
and and, or or, not non-operation can be used when using conditional calculations

Exercise question:
student table, including student number, name, gender, age and department

create table if not exists tb_student(
sno bigint primary key auto_increment,
sname varchar(10) not null comment '姓名',
sex boolean default 1 comment '性别',
age tinyint default 18 comment '年龄',
depte varchar(20) default '计算机系' comment '系别'
)engine=innodb default charset utf8;

Insert test data

-- 这里由于粗心,列名称本来时dept,现在写成了 depte
alter table tb_student change depte dept varchar(20) default '计算机系'
comment '系别';
insert into tb_student(sname,age) values('赵小胖',20),('张毅',18),('东方',19);
update tb_student set sex=0 where sno=3;
update tb_student set dept='数学计算机系';
--多插入的学生信息【赵双井】
insert into tb_student(sname,age) values('赵双井',20);
--需要删除姓名为【赵双井】
delete from tb_student where sname='赵双井';

1: Query the student ID and name of all students

select sno,sname from tb_student;

The column name is the displayed name when it is displayed by default, and it is actually allowed to be modified

select sno as 学号, sname 姓名 from tb_student;

2: Query the names, student numbers, and departments of all students

select sname,sno,dept from tb_student;

The exchange position of any two rows in the table will not affect the expressed data, and the exchange position of any two columns in the table will not affect the expressed information. The concept of specific business order comes from the number, not the actual storage location

3: Query the detailed records and corresponding ages of all students

select * from tb_student;
  • In specific applications, the age is generally not directly stored, but the birthday is recorded, through year(now())-year(birth) as age

4: Query students whose age is greater than 20

select * from tb_student where age>20;

Comparison operator >大于 <小于 >=大于等于 <=小于等于 =等于 !=不等于
5: Query all girls whose age is less than 20

select * from tb_student where age<20 and sex=0;
  • Allows to use and, or to connect multiple conditions

6: Obtain the information of students from the Department of Computer Science or surnamed Zhang

select * from tb_student where dept='计算机' or sname like '张%';

7: Query the information of all students who are not girls

select * from tb_student where not (sex=0);

  • not is a non-operation

Import and export operations

Transfer the text data to the database.
The format of the text data is [the data between the fields is separated by the tab key, and one row corresponds to one row of data]

3 Zhang San 1989-2-3
4 Li Si 2020-5-12

Create the corresponding table, the table structure should correspond to the data in the text file

create table tb_users(
id int primary key,
name varchar(20) not null,
birth date
) engine=innodb default charset utf8;

The import statement, since the hard disk file is directly read in sql, will involve security configuration issues

load data infile "d:/users.txt" into table tb_users(id,name,birth);

Back up the database
mysqldump --opt test>test.sql
and restore the database, just create an empty database test
mysql -uroot -p123456 test<test.sql

Summarize

  • It is necessary to ensure that the fields and table names in the table do not conflict with reserved words, database systems or common methods. If it is really the same, please
    use a pair of `` (emphasis marks) in the SQL statement to enclose
  • SELECT queries can also query constants, that is, add a fixed constant column to the SELECT query result. The value of this column is specified, not dynamically fetched from the data table.

Why do we still need to query constants?

  • The SELECT syntax in SQL does provide this function. Generally speaking, you only query data from one table. Usually, you don’t need to add a
    fixed constant column. But if you want to integrate different data sources, use the constant column as the mark of this table. you need to query the constant
  • For example, if you want to query the names of employees in the emp data table, add a column of field corporation at the same time, and the fixed value of this field is
    "Lanou Group"

Supplementary Note

In MySQL, multi-line explanation is /* /, which is the standard of SQL, but MySQL expands the function of explanation. If
an exclamation point is added after the / at the beginning, the statements in this explanation will be executed

mysql> /*! select * from test */;
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
+------+
3 rows in set (0.00 sec)
/*!50001 select * from test */; -- 这里的50001表示,假如数据库是5.00.01以上版本,
--该语句才会被执行。

Guess you like

Origin blog.csdn.net/qq_39756007/article/details/127015018