Mysql database depth knowledge

Stop command: net stop mysql
Start command: net start mysql
 

Login command mysql

mysql -h ip -P port -u user name -p
 
mysql mysql --version or -V for logged out, the view of the present machine version mysql
select version () ;: under logins, see link library version
 
Show all databases: show databases;
Enter the specified library: use the library name;
The table shows all current library: show tables;
View other libraries in all the tables: show tables from the library name;
View the table creation statement: show create table table name;
View table structure: desc table name;
View current database: select database ();
 

mysql syntax specification

  1. Case insensitive, but suggested keywords in uppercase, table names, column names lowercase
  2. Each command is best to use a semicolon at the end
  3. Each command as required, may be indented or line
  4. Note
    • Single-line comments: # comment text
    • Single-line comments: - text notes, note that this requires spaces
    • Multi-line comments: / ** comment text ** /

SQL language classification

  • DQL (Data Query Language): Data Query Language
    select the relevant statements
  • DML (Data Manipulate Language): Data Manipulation Language
    insert, update, delete statement
  • DDL (Data Define Languge): Data Definition Language
    create, drop, alter statement
  • TCL (Transaction Control Language): Transaction Control Language
    set autocommit=0、start transaction、savepoint、commit、rollback
 
It includes the following five categories
Integer types: bit, bool, tinyint, smallint, mediumint, int, bigint
Floating-point types: float, double, decimal
String type: char, varchar, tinyblob, blob, mediumblob, longblob, tinytext, text, mediumtext, longtext
Date Type: Date, DateTime, TimeStamp, Time, Year
Other data types: temporarily introduce, use less.
 

Type (n) Description

In development, we will encounter some of the wording of the definition of integers is int (11), such an approach personal feeling is not of any use in the development process, but still it is about, int (N) We only need to remember two things :
  • No matter how much N is equal to, int always 4 bytes
  • N denotes the display width, insufficient with zeros, ignoring over the entire length of the direct digital display, but is set to an integer valid unsigned zerofill
 
It uses a decimal rounding 
float and double uses four banker's rounding
What is a four banker's rounding?
Is 5 or less give up 5 or more carry, when if you need treatment number is 5, it is necessary to see whether the back 5 there are not any numbers 0, if there is a direct carry, and if not, need to look in front of the 5 digit, odd the carry, if the even will give it 5
char type uses fixed-length data if stored as recommended char type fixed length, such as: information fixed-length cell phone number, ID cards, etc.

Some suggestions Data Type Selected

  • Small election do not choose large: Under normal circumstances can choose the smallest data type to store the correct data, the smaller the data types are generally faster and take up disk, memory, and CPU cache smaller.
  • Simple: simple data type of operation typically requires fewer CPU cycles, for example: the cost of operating the character integer ratio is much smaller, because the character set and collation (collation) to make the comparison more complex character than integer.
 
  • Try to avoid NULL: Try to develop as NOT NULL, NULL value unless really need to type, there are NULL column values ​​will make the index, the index statistics and value comparison is more complicated.
  • Select the type of floating-point decimal recommendations unity
  • Recommended to use the recording time or bigint int type, a timestamp format conversion time, conversion time, as will be seconds, milliseconds, stores, convenience take the index
 

Permissions effective time

User authority information in a library and a library named mysql, mysql start time, the content is read into memory and take effect from this point, and so if the authority to modify the user information by directly operating tables, need to restart or to flush mysql privileges; before they can take effect.
After the user logs in, mysql and will create a connection between the current user, then the user permissions related information is stored in this connection, stored in memory, at this time if there are other places to modify the permissions of the current user, these changes permissions will take effect the next time you log.

Create a user

grammar:
create user username [@ hostname] [identified by 'password'];
Description:
  1. The default value is hostname%, indicating that users can connect from any host server mysql
  2. The password can be omitted, represent no login password
By modifying the Change Password mysql.user table
use mysql;
update user set authentication_string = password('321') where user = 'test1' and host = '%';
flush privileges;
 
Authorize the user:
grant privileges ON database.table TO 'username'[@'host'] [with grant option]
 
grant command description:
  • priveleges (permission list), may be all, showing all rights, may be select, update permissions, etc., are separated by commas multiple permissions.
  • ON to specify the rights for which libraries and tables, format database table, in front of the point number is used to specify the database name, dot behind to specify the table name, *. * Means all tables in all databases.
  • TO said it will give a user privileges, in the format username @ host, the user name before the @, followed by @ host access restrictions can be IP, IP segment, as well as domain name%,% indicates anywhere.
  • WITH GRANT OPTION This option means that users can have their own authority delegated to others. Note: people often do not specify WITH GRANT OPTION option when creating the user's operation later led the user can not create a user using the GRANT command, or to other authorized users.
    Note: You can add permissions to users using GRANT repeated, superimposed authority, for example, you give permission to add a select users, and then add a user insert gave permission, then the user will have both the select and insert privileges.

View user what permissions

show grants for 'user name' [@ 'host']
show grants - to view the current user's permissions
Revoke user privileges: revoke privileges ON database.table FROM 'username' [@ 'host'];
delete users:
1.drop user 'username' [@ 'host']
2.delete from user where user = 'username' and host = 'host';
 
 

Authorization Statement of Principles

  • Awarded only to meet the minimum required permissions to prevent users from doing bad things, such as the user only needs to query, it is only to select permissions on it, do not give the user gives update, insert or delete permissions
  • Create a user when the user's login restrictions host, is generally limited to specified IP or IP network segment
  • Initialize the database is not deleted when the user's password, when you install the database will automatically create some users who do not default password
  • Set password complexity to meet the password for each user
  • The user does not need regular cleaning, recycling or delete user permissions
 

to sum up

  1. Operating users and permissions through the command does not need to refresh automatically take effect next logon
  2. By modifying the tables in the mysql database operation, user information, you need to call flush privileges; refresh, next logon automatically take effect
  3. mysql identify the user's way: Username + Host
  4. Mentioned herein, some instructions the tape host, the host can be omitted, the default value of%, all machines
  5. Mysql database users and permissions information in the library named mysql
 
 

Modify column

alter table column name table modify column new type [bound];
or
alter table column name table change column new column name of the new type [bound];
2 ways to distinguish: modify the column name can not be changed, change can change the column name
 
delete delete single table
delete [alias] from table [[AS] alias] [WHERE condition];
note:
If no alias when the table name is an alias
If there is an alias, must be written later delete the alias
If no alias, delete the alias back can be omitted.
Examples
- Delete all records in the table test1 delete from test1;
- Delete all records in the table test1 delete test1 from test1;
- aliased way to delete all records in the table test1 delete t1 from test1 t1;
- remove aliased manner to meet the conditions of the recording delete t1 from test1 t1 where t1.a> 100;
Multi-table delete
You can also delete records from multiple tables, the syntax is as follows:
delete [1 alias, alias 2] from Table 1 [[AS] alias 1] and Table 2 [[as] Alias ​​2] [where Condition];
Description:
Aliases can be omitted, but need to keep up the table name in the back delete, separated by commas between multiple table names.
Example 1
delete t1 from test1 t1,test2 t2 where t1.a=t2.c2;
Test1 delete records in the table, such that a field of the record present in the recording test.c2
 

drop,truncate,delete区别

  • drop (delete the table): Delete the content and definition, free space, in short, is to remove the entire table, after new data to be impossible, unless a new table.
    drop table delete statement structure is dependent constraints (constrain), the trigger (Trigger) index (index), is dependent on the table stored procedure / function will be retained, but its status changes: invalid.
    If you want to remove table definition and its data, use the drop table statement.
  • truncate (empty data table): delete the content, free up space without deleting the definition (reserved table data structure), and the drop is different, just clear the table data only.
    Note: truncate can not delete specific rows of data, it is imperative to delete the entire table cleared.
  • delete (delete the data in the table): delete statement to remove rows in a table. Process delete delete statement is deleted from the table each row, and at the same row as the delete transaction records stored in a log, for rollback operation.
    truncate and delete without a where: the only delete data, without deleting the table structure (as defined)
    Truncate table to delete all the rows in the table, but the table structure and its columns, constraints, indexes and so on remain unchanged.
    For tables referenced by the foreign key constraints, you can not use truncate table, and use the delete statement without a where clause. Since truncate table recorded in the log, it can not activate the trigger.
    delete statement is a database manipulation language (dml), ​​this operation will put rollback segement, the only take effect after the transaction commits; if there is a corresponding trigger, when the execution will be triggered.
    truncate, drop a database definition language (ddl), operating with immediate effect, the original data is not put rollback segment can not be rolled back, the operator does not trigger the trigger.
    If you have an auto increment, truncate delete mode after auto-increment value will be initialized, delete way points to the case (if the database is restarted, an auto-increment value will be initialized, the database is not restarted, unchanged)
  • If you want to remove table definition and its data, use the drop table statement
  • Safety: Be careful using the drop and truncate, in particular when there is no backup, or too late to cry
  • Delete speed, in general: drop> truncate> delete
drop
truncate
delete
 
Deleting
not support
not support
stand by
Delete table structure
stand by
not support
not support
To delete a transactional way
not support
not support
stand by
The trigger is activated
no
no
Yes
Alias ​​special symbols, such as spaces, then the alias must be enclosed in quotes.
 
It is not equal to the symbols used:
<> This is the first usage.
! = Was later added by.
Both the same meaning in the former than the latter portability
Therefore make use of the sql statement <> do ranging Analyzing
 
 

 

like (fuzzy query)

select the column name from table where column like pattern;
pattern can contain wildcards, the following wildcards:
%: Represents one or more characters match any
_: Means match any one character.

 

Query operator, like, between and, in, not in the query can not afford to effect a NULL value
 

<=> (Equal Security)

<=>: NULL value may be determined, and based on common values, low readability, use less
 

to sum up

  • % in the like can be matched to a plurality of arbitrary characters match any one character _
  • Null queries or require the use of IS NULL IS NOT NULL, NULL other query operator of an invalid value
  • Recommended that you create a table, try to set the table can not be empty, the field is set to a default value
  • <=> (Equal Security) can play, it is recommended to use less
grammar:
select 列 from 表 limit [offset,] count;
Description:
offset: indicates the offset, popular speak is the number of lines to skip, offset may be omitted, the default is 0, 0 means skip line; range: [0, + ∞).
count: After taking skip start offset rows, rows count taken; range: [0, + ∞).
And count the offset value limit of expression can not be used.
 

Expression limit can not be used, the latter two numbers can not be negative limit

 

Present field the same value, the same value as when there is a sorting process, no other collation, mysql ignorant force, do not know how sorted; 
Recommendation: Paging, the sort not ambiguous, may cause paged results out of order under ambiguous circumstances, you can append a primary sort key in the back
where multi-field while limiting:
SELECT
user_id user id,
price largest amount,
the_year Year
FROM
t_order t1
WHERE
(t1.user_id , t1.price)
IN
(SELECT
t.user_id, MAX(t.price)
FROM
t_order t
GROUP BY t.user_id);
Now let's discuss why the output of the order java and sql inconsistent?
The above two query connection java code table used nested loops, the outer loop executed once each, the whole cycle will traverse a table, if placed in mysql, equivalent to all the scanning an internal standard (full table io reading operation), the main table (outer loop) If there are n pieces of data, then the table will need full table scan n times, the data table is stored on disk, each need to do a full table scan operation io, io operation is the most time-consuming, if java mysql implemented in the above manner, it is certainly very low efficiency.
That mysql is how to optimize it?
Msql internal memory cache using a space, called him join_buffer it, first data into the external circulation join_buffer then traversed on the table, a data fetch and join_buffer data are compared from the table, from the table and then and then take the articles 2 and join_buffer data are compared, until the table walk is complete, the use of which side ways to reduce the io number table scan, when join_buffer sufficiently large, large enough to store the master list of all data, from the table only It requires a full table scan (i.e., only need to read a full table io operation).
mysql in this manner is called Block Nested Loop.
 
 
When a field value is NULL, not in the query have pit, to pay attention to this
Recommended that you create table, the column does not allow null
 

delimiter key sql statement terminator

delimiter used to set the terminator, when mysql execute the script, met terminator when the end would break all previous statements as a whole runs a stored procedure script multiple sql, but as a whole needs to run so here uses a delimiter
 
/ * Set hasSqlError any abnormality during the execution of TRUE * /
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET hasSqlError=TRUE;
Whether there is abnormal according to hasSqlError judgment, do rollback and commit operation
 
 
mysql binlog-use change and relaylog records database
binlog three formats: ROW STATEMENT MIXED, ROW record national data is modified, modify what has become; STATEMENT record sql to modify the binlog; mixed MIXED that more than two modes.
binlog is a binary file, parse binlog in two ways:
1. In use the command line, show binlog events in 'binlog-filename'; View mode
2. Download the analysis binlog, and then analyzed by the mysqlbinlog tool
 
 
Sectors: the smallest unit of disk storage, a sector size is generally 512Byte
Disk blocks: the smallest unit of the file system to interact with the disk (the smallest unit of a computer system to read and write disk), a disk block is composed of several successive sectors, generally the block size is 4KB
 
The advantages of a binary search data: positioning data very quickly, provided that: the destination array is ordered.
 

To summarize some of the recommended index

  1. Indexing can effectively use the index, discrimination is too low, can not effectively use the index, you might need to scan all data pages in the above fields with high distinction, and this time do not use the index almost
  2. Note that the leftmost joint index matching principle: must match the order from left to right, mysql will always be matched to the right until it encounters a range queries (>, <, between, like) to stop the match, such as a = 1 and b = 2 and c> 3 and d = 4 if the establishment (a, b, c, d) of the order index, d is less than the index, if the establishment of (a, b, d, c) the index can be used, order a, b, d may be adjusted
  3. Search record time, less use *, try to use the index covering can be reduced back to the table operations, improve efficiency
  4. Some queries may take joint index, and then use to push down the index (IPC), can be reduced back to the table operations, improve efficiency
  5. Prohibit the use of functions, operators, operation of the field index, the index will fail
  6. String field and make the numbers when comparing index is invalid
  7. Fuzzy queries '%% value' will make the index is invalid, becomes full table scan, but the '% value' index that can be used effectively
  8. Sort index field to use as much as possible, thus reducing the sorting, improve query efficiency

Guess you like

Origin www.cnblogs.com/Mr-Rocker/p/11712529.html