MYSQL instruction set

1. Create database database name; Create database;

2. show databases; view all libraries;

3. Use + library name; select a specific database;

4. show tables; view all tables in the current library;

5. Drop database database name; delete the database;

6. Tables and columns in mysql can be renamed, but database cannot be renamed; rename table oldname to newname;

7. The name of the drop table; delete the table;

8. Truncate table name; clear table data; (equivalent to delete and rebuild, to get a brand new table)

9. Delete table name; delete table data; (equivalent to erasing data with eraser, if all are cleared, truncate will be faster)

10. Set names + coding types; 

11. tee directory; output SQL statements and query results to files;

12. Insert into table name (column 1, column 2,...) values ​​(value 1, value 2,...); If you do not declare the column name, insert all columns in sequence;

13. Insert into table name (column 1, column 2,...) values ​​(value 1, value 2,...), (value 3, value 4,...), (value 5, value 6,. ..); Insert multiple rows of data at once;
    insert into table name select column 1, column 2,... from table name;

14, update table name set expression 1 (column 1=value/column 1=column 1+value/...), expression 2 (column 2=value/column 2=column 2+value/...) where expression (and/or); without where, the corresponding column of all rows will execute set; as long as the expression after where is true, it will be executed, if multiple rows are true, multiple rows will be executed;

15. Delete from the table name where expression; delete the row where the expression is true from the corresponding table;

15. Delete from table name; all data in the table are deleted; (table structure is still there)

16, select * from table name; take out all rows and all columns;

17, select column 1, column 2,... from table name where expression; take out the corresponding rows and columns that meet the conditions;

18. MYSQL three column types:

    Integer type: (Generally speaking, N bytes, 0~2^8N-1, -2^(8N-1)~+2(8N-1)-1) ((M): fill 0 width, cooperate with zerofill Only meaningful, unsigned: unsigned, zerofill: fill 0, must be and default unsigned type)

        tinyint: Occupied space: 1 byte; Storage range: -128~127, 0~255; Smallint
        : Occupied space: 2 bytes; Storage range: 0~65535, -32768~32767;
        Mediumint: Occupied space: 3 bytes ;
        Int: Occupied space: 4 bytes;
        bigint: Occupied space: 8 bytes;
        
    Floating point type: (M: precision, represents the total number of digits, the sign does not occupy the number of digits; D: scale, represents the number of digits to the right of the decimal point)
        float(M,D)10^38.10^-38; if M<=24, it takes 4 bytes, otherwise 8 bytes; float precision sometimes loses precision;
        decimal (M,D) integer and decimal are stored separately , Variable-length type, more accurate than float;
        
    character type:
        char (M): M is between 0 and 255, M refers to the number of characters; fixed-length type; when looking for records, if they are all fixed-length, you can pass the number of rows and The length of the line calculates the offset of the file pointer; fill in the missing part with spaces, take it out and delete the space on the right side, so there is a space at the end of the content, it will be deleted; the fixed length speed is faster;
        varcahr(M): M In the range of 0~65535, M refers to the number of characters; variable length type; no spaces are required, but there are 1~2 bytes before the column content to mark the length of the column;
        text: text type, generally used to store the content of the article , News content, etc.;
        mediumtext: larger text type;
            blob: binary type, used to store binary information such as images and audio; meaning: to prevent information loss due to character set problems;

    Date/time type:
        date type: storage year-month-day; range 1000-01-01~9999-12-31;
        time type: 00:00:00; datatime
        type: yyyy-mm-dd hh: ii: ss ;

19. Modify table syntax:
    
    alter table table name add column name column type column parameter; add column statement;
    alter table table name add column name column type column parameter after a certain column; add a new column after a certain column;
    alter table table name add Column name column type column parameter first; add a new column in the first column position;

    alter table table name drop column name; delete a column;

    alter table table name modify column name column new type column new parameter; modify column type and parameter;
    alter table table name change old column name new column name column new type column new parameter; modify column name, column type and column parameter;

20. Query statement: (Query model: treat the column as a variable, and the expression in if after where. If the expression after where is true, it will be retrieved by the query; the where query is the effect on the table, which cannot be Query results have an effect; use having to have an effect on the results)

    select * from table name where column name! = Value; not equal to;
    select * from table name where column name <> value; not equal to;
    select * from table name where column name in (element 1, element 2, ...); elements in this set meet;
    select * from table name where column name in (select column name from a table); in() is suitable for the case where the number of collection elements is less than the number of data in the outer table;
    select * from table name where column name between value 1 and value 2; Meet the conditions between value 1 and value 2 (including boundary values);
    select * from table name where column name not in (element 1, element 2,...); elements not in this set meet;
    select * from table name where column name like'a field%'; fuzzy query, the condition that starts with a field,% matches any character, including null characters;
    select * from table name where column name like'a field_'; Each underscore can match any single character;
    select column 1, column 2, (column 1-column 2) as column name from table name where expression;

    update table name set column name=floor(column name/10)*10 where expression; floor(x) returns the largest integer not greater than x;

21. The group and statistical functions of the 5 sub-sentences of select: max: maximum, min: minimum, sum: sum, avg: average, count: total number of rows; select-->where-->group by/column Projection operation-->having-->order by-->limit;

    select max (column name/expression) from table name;
    select min (column name/expression) from table name;
    select sum (column name/expression) from table name;
    select avg (column name/expression) from table Name;
    select count(*) from table name; query output total number of rows, the parameter is * to calculate the absolute number of rows, the parameter is the column name to calculate the number of rows that the column is not null;
    select sum (column name) from table name group by A certain column name; after grouping by a certain column, query the results of each group;
    select column name 1, sum (column name 2) from table name; For SQL standards, this statement is wrong, but it can be so in MySQL Run, column 1 is to take out the value that first appeared;
    select column name 1, sum (column name 2) from table name group by column name 1; this statement conforms to the SQL standard, there is no objection; strictly speaking, after select The column can only be selected in the column behind group by, or is a statistical function;
    
    order by sorting is for the final result set; order by is placed after where/group by/having;
    select column name from table name where expression order by a column name desc/asc; sort according to a column in descending order/ascending order; default ascending order;
    select column name from table name order by column name 1 asc, column name 2 desc; first sorted according to column name 1 in ascending order, followed by Column name 2 sorted in descending order;

    limit [offset,] N: limit entry; (offset (can be omitted): offset, number of rows skipped; N: entry, number of rows actually taken out)
    select column name from table name where expression order by a column Name asc/desc limit offset, entry;

    Subquery:
        where type subquery: refers to the inner query result as the comparison condition of the outer query;
        if the where column = (inner SQL), the inner SQL must return a single row and single column, a single value;
        if the where column is in (Inner SQL), the inner SQL returns a single column, which can be multiple rows;

        From type subquery: treat the inner query result as a temporary table for the outer SQL to query again, and the subquery result must be renamed;

        exists type subquery: take the query result of the outer layer to the inner layer to see if the inner query is established, if the inner SQL is established, it will be changed and taken out;
        select * from table name 1 where exists (select * from table name 2 where table name 1. column name 1 = table name 2. column name 2); exists () suitable for the case where table name 2 is larger than table name 1 data; when table name 1 and table name 2 have the same amount of data, in and The exists efficiency is similar;
    why not null default''/default 0 is added when creating the table;
    Answer: I don’t want null values ​​to appear in the table;

     Why don’t you want a null value?
    Answer: It’s not easy to compare. Null is a type. When comparing, you can only use the special is null and is not null to compare. When encountering operators, they will always return null; the efficiency is not required, which will affect the improvement of the index effect; Therefore, we often not null default''/0 when building a table;

22. Exercise:
    Question: Calculate the average score of students with an average score of less than 60 points and more than 2 subjects.
    Table creation statement:
        create table result (
        name varchar(20) default null,
        subject varchar(20) default null,
        score tinyint(40) default null
        )engine=myisam default charset=utf8;

        insert into result
        values
        ('Zhang San','Mathematics',90),
        ('Zhang San','Chinese',50),
        ('Zhang San','Geography',40),
        ('李四',' Language', 55),
        ('Li Si','Politics',45),
        ('Wang Wu','Politics',30)
    Chart:
    +--------+---------+-------+
     | name | subject | score |
    +--------+ ---------+-------+
     | Zhang San | Mathematics | 90 |
     | Zhang San | Language | 50 |
     | Zhang San | Geography | 40 |
     | Li Si | Language | 55 |
     | Li Si | Politics | 45 |
     | Wang Wu | Politics | 30 |
    +--------+---------+-------+

    Answer: select name,avg(score),sum(score<60) as gk from result group by name having gk>=2;
    +--------+----------- -+------+
     | name | avg(score) | gk |
    +--------+------------+------+
     | Zhang San| 60.0000 | 2 |
     | Li Si | 50.0000 | 2 |
    +--------+------------+------+

23. Cartesian product:
    
    Multiplying two tables. From a row perspective, each row of the two tables is combined in pairs; from a column perspective, the column in the result set is the addition of the column names of the two tables;
    select column 1 , Table 1. Column 2, Column 3, Table 2. Column 4,... from Table 1, Table 2; Table 1 and Table 2 are the results of the Cartesian product operation; the number of rows in the result set is the number of rows in Table 1 and The product of the number of rows in Table 2, and the price ratio accounts for memory;
    select column 1, table 1. column 2, column 3, table 2. column 4,... from table 1, table 2 where table 1. column 2 = table 2. column 4;

24. The syntax of the left connection:

    Assuming that table A is on the left, table B slides on the right of table A, table A and table B filter the rows of table B through a relationship;
    A left join B on condition; if the condition is true, the corresponding row of table B is taken out; The result set is also formed, which can be regarded as a table, which can be queried. Both columns of A and B can be checked. Naturally where, group by, having, order by, and limit can be used normally;
    (A left join B on condition ) Left join D on condition; can be nested;
    select column name 1. column name 2 from A left join B on condition where condition; 
    
    the difference between left join and right join: (left and right joins are interchangeable, A right join B on condition; equivalent to B left join A on condition;)
    A left join B on condition; A needs to be all listed, only the ones that match B will be listed;
    B right join A on condition; A needs to list all, Only B matches will be listed;

    The characteristics of
        inner joins : (intersection) A inner join B on condition; A and B meet the conditions at the same time are listed;

    Outer connection: (union) SQL server support, but MySQL does not support;

25. Union usage:
    merge the results of 2 or more statements, syntax: SQL1 union SQL2; merge result set;
    select column name 1 from table name 1 union select column name 2 as column name 1 from table name 1 order by field asc /desc; similar to the or function; if the column names are different, the first SQL will prevail; as long as the number of columns in the two result sets is the same; order by can sort the final result, which ultimately affects the result set Will work

    Union's treatment of duplicate rows (that is, all the column values ​​of certain rows are the same): deduplication by default, if you want to keep duplicate rows, use union all;

26. Commonly used functions:

    length(): count the number of bytes;
    char_length(): count the number of characters;
    reverse(): reverse the string;
    position('substr' in'string'): the position of the substring in the string;
    right('string' , Length): cut the rightmost string;

    now(): current time, return datetime format;
    curdate(): return date, date format;
    curtime(): return time, time format;
    dayofweek(): a certain day is the day of the week, dayofmonth(), dayofyear( ) Same
    thing ; week (year): the first few weeks of the year;

    md5 ('string'): md5 encryption function, irreversible;

    select case column name when a certain possible value then return value when another possible value then return value else default value end from table name; switch function;
    if (expression 1, expression 2, expression 3): expression 1 If it is true, return expression 2, otherwise use expression 3;
    ifnull (expression 1, expression 2, expression 3): If expression 1 is null, return expression 2, otherwise return expression 3;
    
    user(): returns the user and host;
    database(): returns the name of the library being operated;
    version(): returns the database version;

27. View view: (1. The view can simplify our query; 2. More refined permission control; 3. There are many data, which can be used when the table is divided) The
    
    view can be regarded as a virtual table, which is a table through some kind of A projection obtained by calculation;
    create view view name as select statement;
    view data can also be modified, provided that the data of the view corresponds to the data of the table one-to-one, just like a function mapping; (table launches view data, view launches Table data) The
    view is not a table, it can be understood as the storage and reuse of SQL query statements;

    algorithm=merge: merge query statement;
    algorithm=temptable: temporary table;
    algorithm=undefined: undefined, determined by the system;
    create algorithm=merge 

28. Declare the character set:

    set character_set_client=utf8/gbk; set the client character set;
    set character_set_connection=utf8/gbk; set the connector character set;
    set character_set_result=utf8/gbk; set the returned character set;
    if all three are gbk, you can set names gbk;
    server>=connection>=client;

29. MySQL engine: (myisam: high batch insertion rate, support full-text index, table lock; innoDB: low batch insertion rate, support transaction security, row lock; BDB; memory; archive)

    The engine engine is the different way mysql stores data; what is unchanged is the data, and what is changed is the storage format; the
    transaction has 4 attributes:
        Atomicity: 2-step or n-step operation is logically indivisible, either all succeed or not succeed ;
        Consistency: The value changes before and after the operation are consistent;
        Isolation: Before the end of the transaction, the impact of each step of the operation is invisible to others.
        Persistence: Once the transaction is completed, it cannot be undone; (only one compensatory transaction can be done)
    Start transaction: start transaction SQL statement commit (submit)/rolback (rollback);

Guess you like

Origin blog.csdn.net/weixin_44182586/article/details/100898735