Organize the basic operations of the MySQL database

MySQL functions, data types

1. Link to the database

Linking to the database usually requires a MySQL user name and password. If the server is running on a machine other than the login server, you also need to specify the host name.

shell> mysql -h host -u user -p
Enter password: ********

2. Display table structure

DESCRIBE t_name;

3. Set up query alias

SELECT name name, age FROM t_name;

4. Summary of data types

smallint 16-bit integer

Interger 32-bit integer

Decimal(p,s) p refers to the size value of all numbers, and s refers to the number of digits after the decimal point.

float 32-bit real number

double 64-bit real number

char(n) a string of n length, n is not greater than 254

varchar(n) A string of n length, n is not greater than 4000

Graphic(n) is the same as char, but the unit is two-character double-bytes, and n does not exceed 127. This form is to support two-character fonts, such as Chinese.

vargrarhic(n) A double-character string of variable length and maximum value n, n cannot exceed 2000.

The date contains the year, month, and date.

time contains hours, minutes, and seconds.

timestamp contains year, month, day, hour, minute, second, and thousandth of a second.

5. Group query

SELECT * FROM t_name GROUP BY subject; GROUP BY refers to grouping queries according to a certain column.

Mention having, having and GROUP BY must be used together, why use having instead of where is because only having can determine the data column calculated by the function, such as sum('money'). Here, you cannot write where money> xxxx; You can only use having>xxx;

6. Operator

(....) Use parentheses to specify the order of operations SELECT (12+3)*3;

Operator precedence, the same line has the same precedence

||,or,xor

&&,and

not

BETWEEN,CASE,WHEN,THEN,ELSE

=,<=,>=,<=>,<,>,<>,!=,is,like,regexp,in

|

&

<,>>

-,+

*, /, div,%, mod

^

!

binary,collate

7. String functions

ASCII(str) The return value is the leftmost character of the string str. If it is an empty string, the return value is 0. If str is null, the return value is null.

BIN(n) returns the binary string representation of n.

LCASE("string")/UCASE("string") #Convert to lowercase/uppercase, which has the same effect as LOWER(str)/UPPER(str)

length("Return string length")

8. Mathematical functions

ABS(x) returns the absolute value of x

ACOS(x) returns the arc cosine of x

ASIN(x) returns the arc sine of x

ATAN(x) returns the arc tangent of x, that is, the tangent is the value of x

ATAN(Y,X),ATAN2(Y,X) returns the arctangent of two variables x and y.

CEILING(X)CEIL(X) returns the smallest integer value not less than x.

COS(X) returns the cosine of x

COT(X) returns the cotangent of x.

CRC32(expr) Calculate the cyclic redundancy code check value and return a 32-bit symbol value

Go to Baidu for what you need, because there are too many.

9. Date function

Date function is still often needed

The range of return values ​​in the description of the following function will request the full date. If a date has a "zero" value, or an incomplete date such as '2001-11-00', the function that extracts part of the date value may return 0. For example, DAYOFMONTH('2001-11-00') will return 0.

ADDDATE(date,INTERVAL expr type)ADDDATE(expr,days)

DAYOFWEEK(date)
  returns the date date date is the day of the week (1=Sunday, 2=Monday,...7=Saturday, ODBC standard)

WEEKDAY(date)
 returns the date date is the day of the week (0=Monday, 1=Tuesday,...6=Sunday).

DAYOFMONTH(date)
 returns the day of the month that date is (in the range of 1 to 31)

DAYOFYEAR(date)
 returns the day of the year that date is (in the range of 1 to 366)

MONTH(date)
 returns the month value in date

DAYNAME(date)
 returns date is the day of the week (returned by English name)

MONTHNAME(date)
 returns the month of date (returned by English name)

QUARTER(date)
 returns which quarter of the year date is

WEEK(date,first)
 returns the first few weeks of the year for date (default value of first is 0, first value of 1 means that Monday is the beginning of the week, and 0 starts from Sunday)

YEAR(date)
 returns the year of date (range 1000 to 9999)

HOUR(time)
 returns the hours of time (range is 0 to 23)

MINUTE(time)
 returns the number of minutes of time (range is 0 to 59)

SECOND(time)
 returns the number of seconds of time (range is 0 to 59)

PERIOD_ADD(P,N)
 adds N months to period P and returns (P format YYMM or YYYYMM)

PERIOD_DIFF(P1,P2)
 returns the number of months between periods P1 and P2 (P1 and P2 format YYMM or YYYYMM)

DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
ADDDATE(date,INTERVAL expr type)
SUBDATE(date,INTERVAL expr type)

Add and subtract the date and time, date: the time to be calculated, the exper value type indicates how the expression expr should be interpreted

CURDATE()
CURRENT_DATE()
 returns the current date value in the format of'YYYY -MM-DD' or YYYYMMDD (according to the context of the return value, it is a string or a number)

CURTIME()
CURRENT_TIME()
 returns the current time value in the format of'HH :MM:SS' or HHMMSS (according to the context of the return value, it is a string or a number)

UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
 returns a Unix timestamp (the number of seconds since '1970-01-01 00:00:00' GMT, date defaults to the current time)

SEC_TO_TIME(seconds)
 returns the TIME value converted from seconds in the format of'HH:MM:SS' or HHMMSS (according to the context of the return value, it is a string or a number)

TIME_TO_SEC(time)
 returns the number of seconds in the time value

10.cast function

Cast (the type of field name as conversion), where the type can be: CHAR[(N)] character 
type DATE date type
DATETIME date and time type
DECIMAL float type
SIGNED int
TIME time type


2. Encyclopedia of basic database syntax

1. Create a new user:

    >CREATE USER name IDENTIFIED BY 'ssapdrow';

  2. Change password:

    >SET PASSWORD FOR name=PASSWORD('fdddfd');

  3. Authority management

    >SHOW GRANTS FOR name; //View user permissions of name

    >GRANT SELECT ON db_name.* TO name; //Give all permissions to the name user db_name database

    >REVOKE SELECT ON db_name.* TO name; //Reverse operation of GRANT, remove permissions;

1. Database operation: 

  1. View the database:

    >SHOW DATABASES;

  2. Create a database:

    >CREATE DATABASE db_name; //db_name is the database name

  3. Use the database:

    >USE db_name;

  4. Delete the database:

    >DROP DATABASE db_name;

Two, create a table:

  1. Create a table:

    >CREATE TABLE table_name(

    >id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, //id value, unsigned, non-empty, increment-uniqueness, can be used as primary key.

    >name VARCHAR(60) NOT NULL

    >score TINYINT UNSIGNED NOT NULL DEFAULT 0, //Set the default column value

    >PRIMARY KEY(id)

    >)ENGINE=InnoDB //Set the storage engine of the table, generally InnoDB and MyISAM are commonly used; InnoDB is reliable and supports transactions; MyISAM is efficient and does not support full-text retrieval

    >DEFAULT charset=utf8; //Set the default encoding to prevent Chinese garbled characters in the database

    If you can create a data table conditionally, you can also use> CREATE TABLE IF NOT EXISTS tb_name (........

  2. Copy the table:

Copy table structure

>CREATE TABLE t_2 LIKE t_1

Copy the contents of the table (the table structure must be exactly the same)
 
>INSERT INTO t_2 SELECT * FROM t_1

Suggestion (copy the specified column)

>INSERT INTO t_2(name) SELECT name FROM t_1

Copy all of the table

    >CREATE TABLE tb_name2 SELECT * FROM tb_name;

    Or partial copy:

    >CREATE TABLE tb_name2 SELECT id,name FROM tb_name;

  3. Create a temporary table:

    >CREATE TEMPORARY TABLE tb_name (here is the same as creating a normal table);

  4. View the tables available in the database:

    >SHOW TABLES;

  5. View the structure of the table:

    >DESCRIBE tb_name;

    You can also use:

    >SHOW COLUMNS in tb_name; //from also works

  6. Delete the table:

    >DROP [ TEMPORARY ] TABLE [ IF EXISTS ] tb_name[ ,tb_name2.......];

    Examples:

    >DROP TABLE IF EXISTS tb_name;

  7. Rename the table:

    >RENAME TABLE name_old TO name_new;

    You can also use:

    >ALTER TABLE name_old RENAME name_new;

Three, modify the table:

  1. Change the table structure:

    >ALTER TABLE tb_name ADD[CHANGE,RENAME,DROP] ...what to change...

    Examples:

    >ALTER TABLE tb_name ADD COLUMN address varchar(80) NOT NULL;

    >ALTER TABLE tb_name DROP address;

    >ALTER TABLE tb_name CHANGE score score SMALLINT(4) NOT NULL;

Four, insert data:

  1. Insert data:

    >INSERT INTO tb_name(id,name,score)VALUES(NULL,'Zhang three',140),(NULL,'Zhang four',178),(NULL,'Zhang five',134);

    Insert multiple pieces of data here, add a comma directly after it, and write the inserted data directly; the primary key id is an auto-incremented column, so you don’t need to write it.

  2. Insert the retrieved data:

    >INSERT INTO tb_name(name,score) SELECT name,score FROM tb_name2;

5. Update data:

  1. Specify update data:

    >UPDATE tb_name SET score=189 WHERE id=2;

    >UPDATE tablename SET columnName=NewValue [ WHERE condition ]

6. Delete data:

  1. Delete data:

    >DELETE FROM tb_name WHERE id=3;

7. Condition control:

  1. WHERE statement:

    >SELECT * FROM tb_name WHERE id=3;

  2. HAVING statement:

    >SELECT * FROM tb_name GROUP BY score HAVING count(*)>2

  3. Relevant condition control characters: 

    =、>、<、<>、IN(1,2,3......)、BETWEEN a AND b、NOT

    AND 、OR

    In the usage of Linke(),% means to match any, _ to match one character (can be Chinese characters)

    IS NULL null value detection

 Eight, MySQL's regular expressions:

  1. Mysql supports REGEXP regular expressions:

    >SELECT * FROM tb_name WHERE name REGEXP'^[AD]' //Find the name starting with AD

  2. Special characters need to be escaped.

 Nine, some functions of MySQL:

  1. String link-CONCAT()

    >SELECT CONCAT(name,'=>',score) FROM tb_name

  2. Mathematical functions:

    AVG、SUM、MAX、MIN、COUNT;

  3. Text processing function:

    TRIM、LOCATE、UPPER、LOWER、SUBSTRING

  4. Operator:

    +、-、*、\

  5. Time function:

    DATE()、CURTIME()、DAY()、YEAR()、NOW().....

 10. Group query:

   1. The grouping query can be grouped according to the specified column:

    >SELECT COUNT(*) FROM tb_name GROUP BY score HAVING COUNT(*)>1;

  2. Conditional Use Having;

  3. ORDER BY sorting:

    ORDER BY DESC|ASC => Sort data in descending and ascending order

11. UNION rules-two statements can be executed (duplicate lines can be removed)

 12. Full-text search-MATCH and AGAINST

  1、SELECT MATCH(note_text)AGAINST('PICASO') FROM tb_name;

  2. InnoDB engine does not support full-text search, MyISAM can;

 13. View

  1. Create a view

    >CREATE VIEW name AS SELECT * FROM tb_name WHERE ~~ ORDER BY ~~;

  2. The special function of the view:

      a, simplify the connection between the tables (write the connection in select);

      b. Reformat and output the retrieved data (functions such as TRIM, CONCAT, etc.);

      c. Filter unwanted data (select part)

      d. Use the view to calculate field values, such as summarizing such values.

 Fourteen, the use of stored procedures:

  Personally, a stored procedure is a custom function with local variable parameters, parameters can be passed in, and values ​​can be returned, but this syntax is dull enough~~~

  1. Create a stored procedure:

    >CREATE PROCEDURE pro(

    >IN num INT,OUT total INT)

    >BEGIN

    >SELECT SUM(score) INTO total FROM tb_name WHERE id=num;

    >END;

   *** Here IN (pass a value to the stored procedure), OUT (pass a value from the stored procedure), INOUT (pass into and out of the stored procedure), INTO (save variables)

  2. Call the stored procedure:

    >CALL pro(13,@total) //There are two variables in the stored procedure, one is IN and the other is OUT. The OUT here also needs to be written. If you don't write it, you will get an error

    >SELECT @total //You can see the result here;

  3. Other operations of the stored procedure:

    >SHOW PROCEDURE STATUS; //Display the current stored procedure

    >DROP PROCEDURE pro; //Delete the specified stored procedure

15. Use cursors:

  I don’t understand this very well, please give me some advice from my friends~~~

   1. The operation of the cursor

    >CREATE PROCEDURE pro()

    >BEGIN 

    >DECLARE ordername CURSOR FOR

    >SELECT order_num FROM orders;

    >END;

    

    >OPEN ordername; //Open the cursor


    >CLOSE ordername; //Close the cursor

The self-written instance
create PROCEDURE t_cur()
BEGIN
        declare notf int DEFAULT 0; - The loop condition is 1 to stop the loop
    declare a int; - The cursor variable is used to receive the age
    declare n VARCHAR(45) in t_test ; - The cursor Variables are used to receive the name in t_test
    declare cur cursor for select name, age from t_test; - Declare the value that the cursor assigns to it t_test
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET notf = 1; - Re-assign the next data if it is not traversed Is 1
    open cur; - open the cursor
        FETCH cur INTO n, a; - write the first row of data into the variable, the cursor points to the first row of the record
    WHILE notf != 1 DO - judge
        insert into t_ceshi(name,age ) VALUES (n,a); - cyclically insert data
        FETCH cur INTO n, a; - unknown
    end WHILE;
    close cur; - close cursor to release space
END;

16. Trigger:

  Trigger refers to triggering the specified operation in the trigger when a specified operation is performed;

  1. The statements that support triggers are DELETE, INSERT, UPDATE, and others are not supported

  2. Create a trigger:

    >CREATE TRIGGER trig AFTER INSERT ON ORDERS FOR EACH ROW SELECT NEW.orser_name;

    >INSERT statement, trigger statement, return a value

  3. Delete the trigger

    >DROP TRIGGER trig;

Seventeen, grammar collation:

  1, ALTER TABLE (modify the table)

    ALTER TABLE table_name

    (  ADD    column  datatype    [ NULL | NOT NULL ]  [ CONSTRAINTS ]

       CHANGE  column   datatype   COLUMNS  [ NULL | NOT NULL ]   [ CONSTRAINTS ]

       DROP    column,

       。。。。

    )

  2. COMMIT (processing affairs)

    >COMMIT;

   3. CREATE INDEX (create an index on one or more columns)

    CREATE INDEX index_name ON tb_name (column [ ASC | DESC ] , .......);

   4. CREATE PROCEDURE (create a stored procedure)

    CREATE PROCEDURE pro([ parameters ])

    BEGIN

    ........

    END

   5. CREATE TABLE (create table)

    CREATE TABLE tb_name(

    column_name  datetype  [ NULL | NOT NULL ]   [ condtraints]   ,

    column_name  datetype  [ NULL | NOT NULL ]   [ condtraints]   ,

    .......

    PRIMARY KEY( column_name )

    )ENGINE=[  InnoDB | MyiSAM ]DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

   6, CREATE USER (create user)

    CREATE USER user_name [ @hostname ] [ IDENTIFIED BY [ PASSWORD ] 'pass_word' ];

   7, CREATE VIEW (create a view on one or more tables)

    CREATE [ OR REPLACE ] VIEW view_name AS SELECT。。。。。。

   8. DELETE (delete one or more rows from the table)

    DELETE FROM table_name [WHERE ......]

   9. DROP (permanently delete databases and objects, such as views, indexes, etc.)

    DROP DATEBASE | INDEX | PROCEDURE | TABLE | TRIGGER | USER | VIEW  name

   10. INSERT (add rows to the table)

    INSERT INTO tb_name [ ( columns,...... ) ]  VALUES(value1,............);

    Insert using SELECT value:

    INSERT INTO tb_name [ ( columns,...... ) ]

    SELECT columns , .......   FROM tb_name [ WHERE ...... ] ;

   11. ROLLBACK (revoke a transaction block)

    ROLLBACK [  TO  savapointname  ];

   12. SAVEPOINT (set reserved point for ROLLBACK)

    SAVEPOINT sp1;

   13, SELECT (retrieve data, display information)

    SELECT column_name,.....FROM tb_name  [ WHERE ]   [ UNION ]    [ RROUP BY ]   [ HAVING ]   [ ORDER BY ]

   14, START TRANSACTION (the beginning of a new transaction processing block)

    START TRANSACTION

   15, UPDATE (update one or more rows in a table)

    UPDATE tb_name SET column=value,......[ where ]


Guess you like

Origin blog.csdn.net/old_wzhou/article/details/78262261