Learning python and ultimately interact with the database, common database have: MySQL, SQLite, MongoDB, Redis, etc., this is mainly introduce the basic operation of the MySQL database.
Sounds good feeling on the database tall, kind of feeling when you touch suddenly realized, is to not keep our data into a table it. It can be so simple to understand, we all know that the table is the table name consists of several parts, the first table, data and other components of the database with this similar, but not the same name, here called the database names, table names and field. Database brief introduction so much, may not be entirely correct to say the following to say about how to operate the database.
More exciting content , please click on my
A, MySQL field types
Commonly used are: the value (int, float), string (varchar, text), date (date, datetime)
Two, MySQL constraints
Primary key: primary key
Foreign key: foreign key
Default value: default
Unique: unique
Non-empty: not null
Third, the physical and logical delete delete
When using the database, will encounter delete the contents of the database, this time we must be careful, otherwise it will be directly fired by the boss, not the network has a very fire command operation called "How to let programmers execute a command fired by the boss, "so we must be careful when operating the database.
What is said about the physical and logical delete delete, physically remove a piece of data is to be permanently removed from the database, is nowhere to be found can not be restored; tombstone is to give your table add a design (for example: isDelete, set default a value of 0), when you want to delete the data value of this field is set to 1, when you then manipulate the data to isDelete value of screening 1 out on it, so that data is not lost. For important data must be set in this field, for how unimportant data they want to operate on how to operate, big deal delete all and re-build the database.
Fourth, the basic operation of the database (CRUD)
1. Create a database
create database [if not exists] db_name [character set utf8];
Note: [if not exists]: The best plus, to avoid trouble, every time the database operating on one more risk
[Character set utf8] encoding format is provided, may not be specified
2, View data
show databases;
3, check the database creation mode
show create database db_name;
4, modify the database
alter database db_name [character set xxx];
5, delete the database
drop database [if exists] db_name;
Note: [if exists]: If you are not sure whether the database plus there is the best, there is deleted, there is also no error
6, using the database
use db_name;
7, view the current use of the database
select database();
Fifth, database management
1, through the grant command to test the database, add the user ***, password 123456
grant select,insert,update,delete,create,drop on test to ‘***’@’localhost’ identified by ‘123456’;
2, modify user password
grant select,insert,update,delete,create,drop on test to ‘***’@’localhost’ identified by ‘asdfasdf’;
3, displays the user
select user from mysql.user;
4, delete users
drop user ‘***’@’localhost’;
Sixth, the basic operation of the data table (CRUD)
1, view the data table
show tables;
2, create a data table
create table student(
id int primary key auto_increment,
name varchar(20) not null,
age int not null,
gender tinyint(1) default 1,
birthday date,
hobby varchar(20)
);
3, view the data table structure
desc student;
4, create a data table to view the statement
show create table student;
5, to increase the data (columns, fields)
alter table student add address varchar(30);
6, a plurality of data increases
alter table student add address varchar(30),
add age int not null,
add height int not null;
7, modify a column name
alter table student change address addr varchar(20);
8, a modified type of
alter table student modify age tinyint default 20;
9, delete a
alter table student drop height;
10, modify the table name
rename table student to stu;
11, modifying the character set used in the table
alter table student character set utf8;
12, delete the table
drop table student;
create table users(id int not null,
name varchar(10),
age int,
height int
);
13, add a primary key
alter table users add primary key (id);
14, he deletes the primary key
alter table users drop primary key;
15, adding a unique index
alter table users add unique (name);
16, adding a unique index set the index name
alter table users add unique key user_name(name);
17, adding joint index
alter table users add unique index name_age(name,age);
18, delete the index
alter table users drop index name;
create table student( id int primary key auto_increment,
name varchar(20),
birthday varchar(20),
age int
);
19, a data insertion
insert into student(name,birthday,age) values(‘学生1′,’2001-1-1’,11);
20, a plurality of data inserted
insert into student(name,birthday,age) values(‘学生2′,’2001-1-2’,11),
( 'Student 3', '2001-1-3', 11),
( 'Student 4', '2001-1-4', 11);
21, modify the data
update student set birthday=’2001-1-10’ where id=1;
22, the data table may be directly operation
update student set age = age + 5;
23, delete data
delete from student where id = 1;
Note: Be sure to add constraints when deleting data, or whole data tables have been deleted
24, delete all the data in the table
delete from student;
Seven, query data
create table grade( id int primary key auto_increment,
name varchar(20),
js double,
java double,
python double );
insert into grade (name,js,java,python) values (‘Tom’,68,89,87),(‘Jim’,70,91,92),(‘Jake’,71,73,74),(‘Mike’,80,84,85),(‘Jame’,85,88,83);
More exciting content , please click on my
1, select queries
All data query: select * from grade;
Name and js query results: select name, js from grade;
Data duplicate filter table: select distinct js from grade;
Js +5 to all grades and used as an alias: select name, js + 5 as 'js performance' from grade;
2, where the filter query
Inquiry Name XX student information: select * from grade where name = 'Tom';
All students more than 250 points out of a query: select name, js + java + python as 'total score' from grade where js + java + python> 250;
Js scores and student inquiry java score greater than 90: select * from grade where js> 90 and java> 90;
Queries java score of 80 to 90 students: select * from grade where java between 80 and 90;
Queries java score 80 or 90 students: select * from grade where java in (80,90);
/ * Fuzzy query,% indicates more characters _ represents a character * /
J query names beginning with students: select * from grade where name like 'j%';
Eight, order by ordering
/ * Asc: ascending Default desc: descending * /
The score js ascending order: select * from grade order by js;
More total score highest to lowest: select name, (ifnull (js, 0) + ifnull (java, 0) + ifnull (python, 0)) as 'total score' from grade order by 'total score' desc;
Nine, group by group inquiry
create table product_tab( id int primary key auto_increment,
product_name varchar(20),
price float(6,2),
product_date date,
class varchar(20) );
insert into product_tab (product_name,price,product_date,class) values (‘苹果’,10,’20180812′,’水果’),
( 'Banana', 20, '20180826', 'fruit'),
( "Kettle", 120, '20170612', "electrical"),
( 'Quilt', 70, '20170612', "furniture"),
( "Sound", 420, '20171012', "electrical"),
( "TV", 2000, '20170912', "electrical"),
( "Sheets", 55, '20171112', "furniture"),
( "Strawberry", 34, '20170512', "fruit");
Grouped by location: select * from product_tab group by 5;
Classified by product category and shows the average price: select class, avg (price) from product_tab group by class;
Product display by commodity price exceeds the sum of each commodity 200: select class, sum (price) from product_tab group by class having sum (price)> 200;
All products grouped: group_concat select id, group_concat (product_name) from product_tab group by class;
Ten distinction between where and having,
First of all, one thing clear is that we can use can use the place where having; where can only be used to filter data packets before; having only be used after the screening packet data,
And having the function can be used in the polymerization.
Eleven, aggregate functions
Count the number of lines: (column name) COUNT
Statistics Number of students: select count (id) from grade;
(Column name) SUM: total Statistics
All js statistics total score: select sum (js) as 'js total score' from grade;
AVG (column names): average
All statistical average js: select avg (js) as 'js average' from grade;
MAX, MIN (maximum and minimum)
select max (js) as 'js highest score' from grade;
select min (js) as 'js lowest score' from grade;
Twelve, SQL statement execution order
from—-where—-select—-group by—-having—-order by
Thirteen, limit and regular expressions
limit
3 data before query: select * from grade limit 3;
Skip 1, three data query: select * from grade limit 1,3;
Regular Expressions
J query beginning students: select * from grade where name regexp '^ j';
M student appears twice in the name of the query: select * from grade where name regexp 'm {2}';
Fourth, multi-table operations
1, the foreign key constraint
/ * A class corresponds to more than one student, a student can only correspond to a class * /
Main Table: create a class table create table class (id int primary key auto_increment, name varchar (20), stu_nums int);
子表:创建学生表 create table student( id int primary key auto_increment, name varchar(20), class_id int, foreign key(class_id) references class(id) );
NOTE: Be sure to and associated primary key data type as a foreign key consistency
Insert Data: insert into class (name, stu_nums) values ( 'class a', 10), ( 'class two', 12), ( 'class three', 13), ( 'class four', 14), ( ' five classes', 15);
insert into student (name,class_id) values (‘Tom’,1),(‘Jim’,1),(‘Jake’,2),(‘Mike’,3),(‘Jane’,4);
增加外键: alter table student add constraint student_fk_class foreign key(class_id) references class(id);
Remove the foreign key: alter table student drop foreign key student_ibfk_1;
2, INNODB supported on statements
Meaning foreign key constraint pair table: If no candidate key in the parent table, is not allowed in the child table insert
/update
Meaning foreign key constraints on the parent table: Table performed on the parent update
/ delete
to update or delete one or more sub-tables corresponding data,
The behavior of the parent table depends on: the definition specified in the foreign key of the child table on update
/ on delete
statement
ON DELETE CASCADE cascade delete: parent table record is deleted, the corresponding recording sub-table is automatically deleted
foreign key(class_id) references class(id) on delete cascade;
Blanking ON DELETE SET NULL: the parent table update / delete recorded sub-table is set to null
foreign key(class_id) references class(id) on set null;
RESTRICT: refused to delete the parent table
NO ACTION: in mysql same RESTRICT, if there are matching records in the child table is not allowed to the parent table corresponds to a candidate key
3, multi-table queries
/ * Create two tables: Table employees and departments tables and insert data * /
create table employee( emp_id int primary key auto_increment, emp_name varchar(20), age int, dept_id int );
create table department( dept_id int primary key auto_increment, dept_name varchar(100) );
insert into employee(emp_name,age,dept_id) values (‘A’,19,200), (‘B’,26,201), (‘C’,30,201), (‘D’,24,202), (‘E’,20,200), (‘F’,38,204);
insert into department values (200, 'personnel department') (201 'Technology'), (202 'sales'), (203 'MOF');
Cartesian product queries: query result is m * n
select * from employee,department;
En: Query two tables have associated data
select * from employee,department where employee.dept_id=department.dept_ id;
Outer join:
Left outer join: the right to increase the left there is no inner connection on the basis of the results
select * from employee left join department on employee.dept_id=departmen t.dept_id;
Right outer join: the right to increase the results have left no basis for including the connection
select * from employee right join department on employee.dept_id=departme nt.dept_id;
4, multi-criteria query
Discover more than 25-year-old employee of information:
select employee.emp_name,department.dept_name
-> from employee,department
-> where employee.dept_id=department.dept_id and age>25;
Within connection query employee and department tables and displayed in the age field in ascending order:
select employee.emp_id,employee.emp_name,employee.age,department.dept_name
-> from employee,department
-> where employee.dept_id=department.dept_id
-> order by age asc;
Subquery: query employee table, all of the information in the department table dept_id
select * from employee where dept_id in (select dept_id from department);
Subquery:
select * from employee where dept_id in (select dept_id from department where age>25);
Use the keyword EXISTS
Off EXISTS word indicates the presence of the cross key. When using the EXISTS keyword, the inner query does not return records query.
But return a true or false value. Ture or False
When returning Ture, the outer query query; when the return value is False, the outer query is not a query
select * from employee where EXISTS (SELECT dept_name from department where dept_id=205);
select * from employee where EXISTS (SELECT dept_name from department where dept_id=203);