mysql learning foundation and function

A: The basic idea of the database
English word database: Database abbreviation: DB
database is a repository for storing and managing data
features:
1. persistent data is actually stored in the database is a file system.
2. convenience store and manage data
3. Use a unified way to operate the database - SQL
common database software,
Oracle (surcharge), MySQL (open source free), Microsoft SQL Server (Microsoft), DB2

Two: Install and Uninstall MySQL database software
1. Installation
2. Uninstall
installation directory 1. mysql to find my.ini file
copy = datadir "C: / ProgramData / MySQL / MySQL Server 5.5 / the Data /"
2. Uninstall mysql
3 delete C: / mysql directory files in the folder ProgramData
3. configure
mysql service starts (three ways)
1. manual ==> service Manager starts
2. cmd -> services.msc to open the services window
3. use management member of the open cmd
* NET start mysql: mysql start service
* net stop mysql: mysql shut down service
*
mysql login
1. mysql -uroot -p password
2. mysql -h (ip address) -uroot -p connected directory password
3. mysql --host = ip address --uroot = root --password = password connection target

mysql退出	: exit/quit ;

Three: SQL
SQL: Structured Query Language ==> Structured Query Language
SQL syntax General
1. SQL statement can be written in single or multiple rows, end with a semicolon.
2. can use spaces and indentation to enhance the readability of the statement.
3 . mysql database SQL statements are not case sensitive, use uppercase keyword suggestions.
4. Notes ways:
1) single-line comment
- comment content
# footnotes
2) multi-line comments:
/ * comment * content /

Four: SQL Classification
1. DDL (Data Definition Language) data definition language
for defining database objects: databases, tables, columns, etc. Keywords:. Create, drop, alter, etc.
2. DML (Data Manipulation Language) data manipulation language
used to the data tables in the database additions and deletions to the keyword:. insert, delete, update, etc.
3. DQL (data query language) data query language:
used to query the database table records keywords:. select, where, etc.
4. DCL (data control language) data control language
used to define security levels and access the database, and create a user. keyword GRANT, REVOKE, etc.

Five: the DDL
1. Operation database
(Create) Create
Create database: create database database name;
create a database, it is determined not exist, then create: create database if not exists database name.
Create a database, and specify the character set: ==> create database the name of the database character set UTF-8;
use the database:
querying the database name currently in use
select database ();
using the database
use the database name;
show the presence of all database systems
show databases;

  1. Operating Table
    Create a table
    1. Syntax
    create table table name (
    column name Data type 1,
    column names 2 data type 2,
    ...
    );
    Note: The last one does not need a comma (,)

     		数据库常用类型有如下几种:
     			1) int : 整数类型
     			2) double : 小数类型
     			3) date : 日期,只包含年月日 yyyy-MM-dd
     			4) datetime : 日期 , 包含年月日时分秒 yyyy-MM-dd HH:mm:ssr
     			5) timetamp : 时间错类型 包含年月日时分秒 yyyy-MM-dd HH:mm:ss	=> 如果将来不给这个字段赋值,或者赋值为null,则默认使用当前的系统时间,来自动赋值
     			6) varchar : 字符串
     				例如 name varchar : 姓名最大的字符为20
     	复制表
     		create table 表名 like 被复制的表名
     	
     	2. 查询 
     		查询当前数据库中所有的表名称	=>  show tables;
     		查询表结构: 	==> desc 表名;
     		查询创建表时的字符集: show create table 表名;
     	
     	3. 修改
     		1. 修改表名 	==> alter table 表名 rename to 新的表名;
     		2. 修改表的字符集  	==> alter table 表名 character set utf8;
     		3. 添加一列		==> alter table 表名 add 列名 数据类型;
     		4. 添加列名称 类型 		=> alter table 表名 change 列名 新列名 新数据类型;
     				==> alter table 表名 modify 列名 新数据类型;
     		5. 删除列 	==> alter table 表名 drop 列名;
     	
     	4. 删除
     		drop 表名;
     		drop table if exists 表名;
    

Six: the DML: deletions in the data table changes
1. Add Data
Syntax: (value or values may be written)
INSERT INTO table name (name column 1, column name 2, ...) values (value 1, value 2, ...);
Note matters: a name and a value to one correspondence
2. If, after the table name, column name is not defined, it defaults to all columns add value ==> insert into table values (value 1, value 2, ...)
3. In addition to data type, other types require the use of quotation marks (single or double can be) cause to

2. 删除数据:
	语法: 
		delete form 表名 where 条件;
	注意事项: 
		1. 如果不加条件,则删除表中所有记录
		2. 如果要删除所有记录
			方法1: delete from 表名;  ==> 不推荐使用。有多少条记录就会执行多少次删除操作
			方法2: truncate table 表名; ==> 推荐使用,效率更高 先删除表,然后再创建一张一样的表。

3. 修改数据
	语法:
		update 表名 set 列名1=值1,列名2=值2,... where 条件;
		注意:1. 如果不加任何条件,则会将表中所有记录全部修改。

Lookup table records: Seven: single-table queries => DQL
single-table query
; searching the entire contents of the table ==> select * from table
1. grammar
select
field list
from
table
where
conditions list
group by
group field
having
after grouping conditions
order by
sorting
limit
tab defined

  1. Underlying query
    multiple fields of inquiry 1.
    select field name 1, field name 2 ... from table name;
    Note: If the query all the fields, you can use * instead of the field list.
    2. deduplication query: DISTINCT
    SELECT DISTINCT field names 1, 2 ... from the field name table;
    3. Compute columns
    generally use four operations a series of values. (Usually only for numerical calculation)
    IFNULL (Expression 1, Expression 2): null involved calculation results are null
    of formula 1: which determines whether the required field is null
    if the field is null after replacement value.
    select a column name, column name 2, column name 1 + ifnull (column name 2,0) from table;

     4. 起别名: as(as 也可以省略)
     	select 列名1,列名2,列名1 + ifnull(列名2,0) as 总分  from 表名;
     	select 列名1,列名2,列名1 + ifnull(列名2,0) 总分  from 表名;
    
    1. Conditions inquiry

      1. where clause followed by the condition

      2. Operators

        , <, <=,> =, = (Equal), <> (not equal) = (not equal)!
        Columns such as:
        - Query older than all of the information age of 20
        select * from table name the WHERE Age> 20;
        - inquiry Age does not mean 20-year-old
        select * from table name Age = 20 the WHERE;!
        select * from table where age <> 20;

        between ... and between the two ends of the data includes
        columns such as: - Query older than or equal to 20 or less 30
        SELECT * from table where age> = 20 && Age <= 30;
        SELECT * from table where age> = 20 Age and <= 30;
        SELECT * from table where age between 20 and 30;

        IN (collection):
        For example: - Query the age of 22 years old, 18 years old, 25-year-old information
        selcet * from table name = 22 or Age Age the WHERE = Age = 18 or 25;
        selcet * from table where age in (22,18 , 25);

        IS NULL: is null
        - English results for the query null
        the SELECT * from table where english is null;

        like: Fuzzy query
        placeholders:
        _ any single character
        more than any single character or%
        - all the information query named Ma
        select * from table where name like "Ma%";

        and or &&
        or or ||
        not or!
        - English query result is not null
        the SELECT * from table where english is not null;

    2. Sort query
      syntax: order by clause to
      order by sort field Sort 1 ... 1
      order by sort field 1 Sort 1, Sort field 2 Sort 2 ...
      ==> Multiple sort fields, represents the first field in accordance with the sort of 1 then 2 Sort Sort field (2 sorted on the basis of the sort 1)
      * when there are a plurality of sorting criteria, the current condition value when the same side, only the second determination condition.
      Sort by
      asc: Ascending (default ascending)
      desc: descending
      example:
      According to math scores sorted in ascending order
      select * (column names ...) from table name order by math (asc);
      in accordance with math scores in ascending order, such as math same again in accordance with the English results descending row
      select * from table name order by math, english desc;

    3. Aggregation function: a column data as a whole, longitudinally calculations

      1. count: count the number of
        1. Generally selected non-null columns: primary key
        2. COUNT ( )
          Example: calculating the total number of
          SELECT COUNT (
          ) from table;
          SELECT COUNT (name) from name;
          Note: no non-null columns selected calculated
      2. max: maximum value is calculated
        e.g.: Computational Mathematics maximum score;
      3. min: minimum value Calculation
      4. sum: computing and
      5. AVG: calculating an average value
        Note: polymerization calculation function, excluding the null value.
        solution:
        1. Select does not contain non-null columns calculated
        2. IFNULL function
    4. Grouping queries

      1. Syntax: group by grouping field;
      2. note:
        1. After the query packet fields: packet fields, aggregate functions
        2. where and having a difference? (Frequently Asked Interview)
          1. where before the packets are defined, if the condition is not satisfied, it is not involved in the packet. After having defined in the group, if not the result, it will not be check out
          2. where not function with the polymerization, having a polymerization function can be determined.
            For example: - grouped by gender. Queries were male and female students of mathematics average
            select sex, avg (math) from the table name by Sex Group;
            - grouped according to gender. Queries were male and female students of mathematics average, the number of requirements: Score 70 points lower than people who do not participate in packet after packet. 2 is greater than the number of individuals
            select sex, avg (math), count (id) from table where math> 70 group by sex having count (id)> 2;
    5. Paging query

      1. Syntax: index limit the beginning, the number of queries per page
        - per page 3 records
        select * from table limit 0,3; ==> First
        select * from table limit 3,3; ==> first page two

      2. * The number of display per page - starting index = (current 1 page): Formula

      3. mysql is a limit of "dialect"

Eight: multi-table query ==> DQL
1. constraint
concept: The data in the table limit, to ensure the accuracy, validity and integrity of data

Categories:
1. primary key constraint: Primary Key
2. non-empty constraint: Not null
3. The only constraint: UNIQUE
4. foreign key constraint: foreign key

  1. Non-null constraints: not null, not be null
    1. Create a table, to add a non-null constraints
    example: Create Table STU (
    ID int,
    name VARCHAR (20 is) Not null - non-null constraint name
    );
    2. Create a table End after addition of non-null constraints
    ALTER Modify Table STU name VARCHAR (20 is) Not null;
    3. remove non-empty constraint
    alter table stu modify name varchar (20 );

  2. The only constraint: unique, not repeated value
    1. When creating the table, add a unique constraint
    Create Table STU (
    ID int,
    PHONE_NUMBER VARCHAR (20 is) UNIQUE - a uniqueness constraint
    );
    Note mysql, the value of the column can have unique constraints defined more null
    2. after creating the table, add a unique constraint
    the ALTER the Modify the table STU PHONE_NUMBER VARCHAR (20) uNIQUE;
    3. Drop the unique constraints
    alter table stu modify phone_number varchar (20 );

  3. Primary key constraint: Primary Key
    1. Note:
    1. The meaning: The only non-empty and
    2. A table can have only one primary key field
    3. The primary key is to uniquely identify records in the table
    2. When you create a table, add a primary key constraint
    create STU Table (
    id int primary key, - id is added to the primary key constraint
    name VARCHAR (20 is)
    );
    3. drop primary
    alter table stu drop primary key;

     4. 创建完表后,添加主键约束
     	alter table stu modify id int primary key;
     5. 自动增长
     	1.  概念:如果某一列是数值类型的,使用 auto_increment 可以来完成值得自动增长
     	2. 在创建表时,添加主键约束,并且完成主键自增长
     		create table stu(
     			id int primary key auto_increment,-- 给id添加主键约束,并且自动增长
     			name varchar(20)
     		);
     	3. 删除自动增长
     		ALTER TABLE stu MODIFY id INT;
     	4. 添加自动增长
     		ALTER TABLE stu MODIFY id INT AUTO_INCREMENT;	
    
  4. Foreign key constraint: foreign key, so that the relationship between the table and the table generation, so as to ensure the correctness of the data.
    1. Create a table, add a foreign key
    syntax:
    the Create the Table table name (
    ...
    foreign key column
    constraint foreign key name foreign key (foreign key column name) references the name of the primary table (the primary table column names)
    );
    2. delete the foreign key
    alter table table name drop foreign key foreign key;

     3. 创建表之后,添加外键	
     	allter table 表名 add constraint 外键名称 foreign key (外键字段名称) references 主表名称(主表列名称);
    

Nine: database design
relationship between 1. Multi-Table
1. Classification:
1. one-
2-many (many) => employee and department relation
3. to-many => relationship between students and courses
2. Achieving
1. achieve many relationship: establishing a foreign key in a multi-party, one point of a primary key
2. realize many relationship: need to use third intermediate table, the intermediate table comprising at least two fields , these two fields third table as a foreign key, the two tables point to the primary key

  1. Classification query of tables:
    1. Inside join query:
    1. Implicit within the connector:
    example: SELECT t1.name, t2.name from EMP T1, T2 WHERE Dept t1.'dept_id '= t2.'id';
    2. explicit inner connecting
    syntax:
    SELECT field list from table 1 (inner) join table 2 on condition;
    inner may be omitted

     2. 外连接查询
     	1. 左外连接
     		语法:
     			select 字段列表 from 表1 left [outer] join 表2 on 条件;
     			查询的是左表所有数据以及其交集部分.
     	2. 右外连接
     		语法: selcet 字段列表 from 表1 right [outer] join 表2 on 条件;
     			查询的是右表所有数据以及其交集部分.
     			
     3. 子查询
     	概念: 查询中嵌套查询,称嵌套查询为子查询.
     	例如:
     		--1. 查询最高的工资是多少?
     			select max(salary) from emp ;  ==> 9000
     		--2. 查询工资最高的员工信息;
     			selcet * from emp where emp.'salary' = (select max(salary) from emp);
     	
     	子查询的不同情况
     		1. 子查询的结果是单行单列:
     			子查询可以作为条件,使用运算符去判断.运算符:> >= < <=
     			例如:
     				-- 查询员工工资小于平均工资的人
     				selcet * from emp where emp.salary < (selcet avg(salary) from emp);
     		
     		2. 子查询的结果是多行单列的:
     			子查询可以作为条件,使用运算符in来判断.
     			例如:
     			-- 查询'财务部'和'市场部'所有员工信息
     			select id from dept where name = '财务部' or name = '市场部';
     			-- 子查询
     			selcet * from emp where dept_id in (select id from dept where name = '财务部' or name = '市场部';);
     				
     		3. 子查询的结果是多行多列的:
     			子查询可以作为一张虚拟表来查询.
    

Expand a: In MySQL, there is no similar rank in such as SQL Server or Orcal () function to get rankings; so we need to manually write this rank function (5.6 or later can support)

Basics: 1. sql statement, using the @ define a variable such as:. @Abc, you need to use the variables need to prepend @
2. SQL statement, use: = to assign values to variables, such as @abc: = 123, abc value of the variable 123
3. SQL statement, if (a, B, C ) , said condition is satisfied if a, B is executed, otherwise, execute C, such as:
@abc: IF = (2>. 1 the results 100, 200) is a value of abc 100
4. case ... when ... then statement
case ... when ... then two cases, there are two
cases 1: (rear case no expression)
case the WHEN experssion 1 THEN operating
the WHEN experssion THEN operation 2
...
the eLSE operator n-
the END
NOTE: top to bottom, one of which usually go away or else when the other does not go any farther. Must end with the end

Case 2: (CASE later with an expression, the latter case is the expression WHEN possible values)
CASE expression The
value of an expression The WHEN 1 THEN operation
value of 2 expression The WHEN 2 THEN operation
...
the ELSE operator n-
the END
NOTE: Since down on those who go or when one is gone else, the other is not leavin.

MySQL中,rank实例
create table person(
id int,
name varchar(32),
age int);
insert into person value(1,“张三”,67);
insert into person value(2,“李四”,67);
insert into person value(3,“王五”,90);
insert into person value(4,“赵本山”,80);
insert into person value(5,“赵丽颖”,18);
insert into person value(6,“李逍遥”,24);
insert into person value(7,“Krs”,25);
insert into person value(8,“Wil”,26);
insert into person value(9,“Gee”,23);
insert into person value(10,“Per”,19);
insert into person value(11,“Tom”,20);
insert into person value(12,“Ae”,20);
insert into person value(13,“Vio”,20);

ascending age (age are the same, the ranking continues to increase) ,:
the SELECT A *, @ Rank: = + 1'd @rank.
the FROM (the SELECT *
the FROM Person the ORDER BY age) A,
(the SELECT @rank: = 0) B;

Note: Here (SELECT @curRank: = 0) q action is: assign an initial value to a variable in the same curRank a select statement. Effects
same as the two sql statement, first the first assignment, then the second SELECT:
the SET @rank: = 0;
the SELECT ID, name, Age, @ Rank: Rank = @rank the AS + 1'd the ORDER BY the FROM Person age;

age ascending order (same age, same rank; age, but to the next is not the same, the ranking is not skip, continue +1) Examples:
(Case ... When the then ...):
. * the SELECT A, the CASE
the WHEN THEN age = @prerank @rank: = @rank
the WHEN @prerank: Age = @rank THEN: = + 1'd @rank
the END sort the AS
FROM person a, (SELECT @rank: = 0, @ prerank: = NULL) b ORDER BY a.age;

age ascending order (same age, same rank; age, but to the next is not the same, the ranking level jump + n) Example:
the SELECT a.id, a.name, a.age,
@curRank: = the IF (= @preRank age, @curRank, @ inRank) Rank the AS,
@inRank: = @ inRank + 1'd,
@preRank: Age =
the FROM Person A, (the SELECT @curRank: = 0, @ preRank: = NULL, @inRank: =. 1) the ORDER BY B a.age;

Two extensions:
1. based on the date function
now () function returns the current date when, for example, every second time: select now (); => 2019-11-23 17:01:24
is SYSDATE () function returns when the current date and time in minutes and seconds now () consistent
curdate (date) function returns the date information such as: the SELECT CURDATE (now)); => 2019-11-23
curtime (dATE) function returns the years May day information such as: the SELECT curtime (now ()); => 17:01:24
Week (date) returns the date for the first few weeks of the date year
year (date) returns the date date year
hour (time) returns the time the hour
minute (time) returns the time of the minutes
monthname (date) returns the date date of the month name => English
month (date) returns the month of the date date => digital

  1. Date, time stamp, each string conversion
    1. date_format (date, format) Date and time string transfer function corresponding to the oracle to_char
    example: select date_format (now (), "% Y-% m-% d% H: % i:% s "); => 2019-11-23 17:01:24 ( a string)
    2. UNIX_TIMESTAMP (DATE) transfer time stamp
    SELECT UNIX_TIMESTAMP (now ());
    # results: 1488160428
    3. STR_TO_DATE (str, format) string rotation time
    SELECT STR_TO_DATE ( '2017-02-27', 'M-% D%%% Y-H');
    # results: 2017-02-27 00:00:00
    4. UNIX_TIMESTAMP (str) string transfer stamp
    SELECT UNIX_TIMESTAMP ( '2017-02-27');
    # results: 1,488,124,800
    5. The FROM_UNIXTIME (int) rotation time stamp
    SELECT FROM_UNIXTIME (1488160428);
    # results: 2017-02-2709: 53:48
    6. The FROM_UNIXTIME (int, the format) to string timestamp
    SELECT FROM_UNIXTIME (1488160428, 'M-% D%%% Y-T');
    # results: 2017-02-27 09:53:48

  2. Time difference function:
    TIMESTAMPDIFF (interval, datetime1, the datetime2) return time difference (time period 2- 1), the results given by the unit interval parameter.
    type interval are
    frac_second milliseconds (low version is not supported by second, and then divided by 1000)
    SECOND, second
    minute minutes
    hour hours
    day days
    week weeks
    month months
    quarter quarter
    year on

  3. Time difference function: datediff (datetime1, datetime2)
    passing two parameters date, comparison DAY days, the first parameter minus the value of the second argument of the day
    , for example, SELECT DATEDIFF ( '2013-01-13', ' 2012-10- 01 '); => 104

  4. Time difference function: timeDiff
    timeDiff (TIME1, TIME2) subtract the time difference between two returns obtained, time1-time2
    e.g. SELECT TIMEDIFF ( '2018-05-21 14:51:43', '2018-05-19 12:54 : 43 '); => 49:57:00 Note: this method is a standard two parameters must date format (' 2018-05-19 12:54:43 ')

Released four original articles · won praise 0 · Views 704

Guess you like

Origin blog.csdn.net/fan_bigdata/article/details/103216672