"MySQL Efficient Programming" Study Notes - Basics

1. Start MySQL Monitor to create a database


-start up-

mysql -u yonghuming -p
mysql -u yonghuming -p password No password can be omitted -p

– Set root password –

mysqladmin -u root PASSWORD password

exit exit or quit

– create database and table –

use grammar
Display database list SHOW DATABASES; case insensitive
delete database DROP DATABASE database name;
create database CREATE DATABASE database name;

Note: The library name, column name and table name are not case-sensitive in Windows, but are distinguished in Linux

– Create a new user and give it permission to operate on the database –

GRANT ALL PRIVILEGES ON database name.* TO username@localhost IDENTIFIED BY password
where all privileges means all privileges optional privileges include CREATE (create) SELECT (retrieve) UPDATE (update) DALETE (delete)
database name. Table name* means this All tables under the database

– create table –

Specify the database to use use database;
display the database currently in use select database();

Create new table

create table table name (domain name data type column option [,…])
Specify the character set when creating a
table Add CHARSET=utf8 after CREATE TABLE ~;
show all tables show tables;
show table structure desc table name; or describe
write picture description here
write picture description here

–Data insertion and display-

Insert data insert into table name (column name 1, column name 2, ...) values ​​(data 1, data 2, ...)
display data in the table select column name 1, column name 2, ... FROM table name
Display all SELECT * FROM tables name

–Define an auto-incrementing sequence-

The data type must be int etc. Add the AUTO_INCREMENT keyword to the definition of the column and use the PRIMARY KEY to set its uniqueness

mysql> create table good(id int auto_increment primary key , name varchar(30)) charset=utf8;
  • 1

Initialize the auto-incrementing sequence

alter table 表名 auto_increment=0;

================================================

2. Using SQL in MySQL


– import sql database –

mysqladmin -u root -p create home //Create database home
mysqladmin -u root -p home < sampledb.sql //Import data to database home

– Notes –

single-line comment
– ​​comment
multi- line comment
/* comment */

==2.1, insert, update, delete data==

--insert the insert command--

INSERT INTO tablename(columnname1, columnname2,...) VALUES(value1, value2,...);

—Update UPDATE command —

UPDATA table name SET column name 1 = value 1, column name 2 = value 2,. . . WHERE conditional expression;
update an existing record that matches the where conditional expression

mysql> UPDATE customer SET nam='李玉芝', birth='1980-09-09' WHERE mid = 'G002'; --注意最后一个值后没有逗号
  • 1

The where conditional expression can be omitted, and all data will be updated at this time

mysql> UPDATE customer SET birth=NULL;
  • 1

—Remove DELETE command —

DELETE FROM table name WHERE conditional expression;
when the restriction is omitted, all data in the table will be deleted
TRUNCATE TABLE command can also delete all data in the table

—Data Retrieval SELECT Command —

SELECT column name 1, column name 2,. . . FROM table name [conditional expression, etc.];

1 – Explicitly specify column names

mysql> SELECT nam,mid FROM customer;

2 – Conditional Search

mysql> SELECT nam,birth FROM customer WHERE birth>='1980/01/01';

Comparison operator
Greater than > < Less than = equal >= Greater than or equal to <= Less than or equal to < > Not equal
IS [NOT] NULL is NULL nam is NULL
[NOT] LIKE The specified target is consistent (inconsistent) nam LIKE 'small%'
[NOT] BETWEEN is included in the specified range (not included) price BETWEEN 3000 AND 4000
[NOT] IN is included in the specified candidate value (not included) mid IN ('G0001','G0002','G0003')

3 – Fuzzy Search

mysql> SELECT nam FROM customer WHERE nam LIKE '李%';
Wild card [wildcard] symbol [%] means 0 or more characters [ _ ] means one character

4 – NULL condition

mysql> SELECT nam FROM customer WHERE birth is NULL;

5 – Combination of multiple conditional expressions

mysql> SELECT nam,birth,sex FROM customer WHERE sex ='1' AND birth IS NOT NULL;

6 – Sorting of results

mysql> SELECT nam,birth,sex FROM customer ORDER BY sex ASC, birth DESC;
ORDER BY sort expression [sort column name sort method] ascending ASC; descending DESC
, NULL is the minimum value in MySQL and SQL Server, and the maximum value in Oracle

7 – Get records of specified number of pieces (m to n)

mysql> SELECT nam ,birth FROM customer ORDER BY birth DESC LIMIT 2;
[LIMIT 2] means to take 2 pieces from the starting position [LIMIT starting position, number of pieces] In principle, it is used together with the order by command

8 – Data Packet

mysql> SELECT sex, COUNT(mid) FROM customer GROUP BY sex;
GROUP BY is usually used with statistical functions, and only the columns used for grouping and statistical columns can be used in the obtained column.

【Main statistical functions】

AVG() Average COUNT Pieces MAX MIN SUM

9 – aliases for columns

mysql> SELECT sex , count(mid) AS cnt FROM customer group by sex;
Use AS to specify an alias

==2.2, operators and database functions==

--operator-

Arithmetic Operators + - * / DIV Round % Remainder
Comparison Operators > < =
Boolean Operator AND OR

– Database functions –

write picture description here
write picture description herewrite picture description here
Example introduction:

1 – The LENGTH function returns the number of bytes

mysql> SELECT LENGTH('理由'); -- 返回4或6 gbk一个汉字2字节 utf8一个汉字3字节
mysql> SELECT CHAR_LENGTH('理由'); --返回2
Returns the bit unit length BIT_LENGTH

2 – FLOOR/CEILING/ROUND functions

Decimal handling
ceiling returns the smallest integer larger than the decimal value, FLOOR returns the largest integer smaller than the decimal value, and ROUND rounds up

mysql> SELECT CEILING(2.5);--3
mysql> SELECT FLOOR(-2.5);--  -3
mysql> SELECT CEILING(-2.5);--  -2 
mysql> SELECT ROUND(114.566);--  115
mysql> SELECT ROUND(114.566,2);--  114.57
mysql> SELECT ROUND(114.566,-2);--  100
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
3 – DATE_ADD function

The parameter type indicates the unit of addition and subtraction, and the parameter var is set to a negative value during subtraction.

mysql> SELECT DATE_ADD('2017-01-31 12:00:00',INTERVAL 1 MONTH) AS newtime;
+---------------------+
| newtime             |
+---------------------+
| 2017-02-28 12:00:00 |
+---------------------+
1 row in set (0.00 sec)
mysql> SELECT DATE_ADD('2017-01-31 12:00:00',INTERVAL -10 HOUR) AS newtime;
+---------------------+
| newtime             |
+---------------------+
| 2017-01-31 02:00:00 |
+---------------------+
1 row in set (0.00 sec)
mysql> SELECT DATE_ADD('2017-01-31 12:00:00',INTERVAL '10:50' MINUTE_SECOND) AS newtime;
+---------------------+
| newtime             |
+---------------------+
| 2017-01-31 12:10:50 |
+---------------------+
1 row in set (0.00 sec)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

4 – EXTRACT function

Used when getting any element from a date

mysql> SELECT EXTRACT(YEAR_MONTH FROM '2017-01-28 12:00:00');
+------------------------------------------------+
| EXTRACT(YEAR_MONTH FROM '2017-01-28 12:00:00') |
+------------------------------------------------+
|                                         201701 |
+------------------------------------------------+
1 row in set (0.00 sec)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

type has YEAR\ QUARTER \ MONTH\ MONTHNAME\ DAYOFMONTH(day) \ DAYNAME(week name) \ DAYFORWEEK(week number)\
HOUR \MINUTE\ SECOND \MICROSECOND etc.

5 – CASE function

Simple conditional judgment
CASE expression
WHEN comparison value 1 THEN result 1
WHEN comparison value 2 THEN result 2

[ELSE result N]
END

mysql> SELECT nam,
    -> CASE sex
    ->   WHEN 0 THEN '男'
    ->   WHEN 1 THEN '女'
    ->   ELSE 'OTH'
    -> END AS sex
    -> FROM customer;
mysql> SELECT pname,
    -> CASE 
    ->   WHEN price <1000 THEN '低'
    ->   WHEN price <=3000 THEN '一般'
    ->   ELSE '高'
    -> END AS price
    -> FROM product;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

==2.3, connection of multiple tables ===

– inner joins –

That is, the primary key between the tables is connected with the foreign key, and only the data with the same key value is obtained. INNER JOIN…ON
SELECT column name 1… FROM table 1
INNER JOIN table 2
ON table 1. foreign key = table 2. primary key
[WHERE /ORDER BY statement Wait]

– outer join –

left outer join

SELECT column name 1... FROM table 1
LEFT OUTER JOIN table 2
ON table 1. foreign key = table 2. primary key [WHERE /ORDER BY statement, etc.]

right outer join

SELECT column name 1... FROM table 1
RIGHT OUTER JOIN table 2
ON table 1. foreign key = table 2. primary key [WHERE /ORDER BY statement, etc.]
write picture description here

==2.4. Data retrieval based on other queries==

– Basic Subqueries –

Query products with more than average price from the product table
mysql> SELECT * FROM product WHERE price >(select AVG(price) FROM product);

– Subqueries with multiple return values ​​–

Retrieve users who did not place an order on a certain day
mysql> SELECT name, address FROM user WHERE uid not in (SELECT uid FROM order_basic WHERE odate ='2010-07024');

– Subqueries and EXISTS operator –

Extract the information of users who have placed at least one order
mysql> SELECT name,address FROM user WHERE EXISTS(SELECT * FROM order_basic WHERE user.uid = order_basic.uid);

=======================================================

3. Maintenance and renovation of tables


==3.1, modify the column structure of the table==

ALTER TABLE command
Modification types include MODIFY \ CHANGE \ ADD \ DROP, etc.

– change the type of the column –

ALTER TABLE table name MODIFY column name data type;

– Additional new columns –

ALTER TABLE table name ADD column name data type; – append at the end
ALTER TABLE table name ADD column name data type FIRST; – at the beginning append
ALTER TABLE table name ADD column name 2 data type AFTER column name 1; – append at any position, Append after column name 1

– Change the position of the columns –

ALTER TABLE table name MODIFY column name 1 data type AFTER column name 2; – adjust column 1 to the back of column 2

– Change column names and types –

ALTER TABLE table name CHANGE before modification column name after modification column name after modification data type;

– delete columns –

ALTER TABLE table name DROP column name;

==3.2, copy table and delete table==

– Copy the column structure of the table as well as the data to create a new table –

CREATE TABLE new table name SELECT * FROM old table name;
this method may change the column attributes, use the DESC command to confirm the table structure after the copy is completed

– Copy the column construction of the table to create a new table –

CREATE TABLE new table name LIKE old table name;

– Copy of data –

INSERT INTO table name SELECT * FROM table containing data;
INSERT INTO table name (column name) SELECT column name FROM table containing data; – copy a column of the old table to the new table

The same as the first method, you can add restrictions such as WHERE and LIMIT to limit the amount of replicated data

–Deletion of table –

DROP TABLE table_name;
DROP TABLE IF EXISTS table_name; – DROP TABLE IF EXISTS


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735721&siteId=291194637