mySQL learning introductory tutorial - 2. Create a table

2. Create the table

 

1. SQL statement model for creating data table (weak type)
CREATE TABLE [IF NOT EXISTS] table name (
field name 1 column type [attribute] [index],
field name 2 column type [attribute] [index],

Field name n column type [attribute] [index],
) [table attribute] [table character set];
[table name, field name needs to be named by yourself]
[SQL statement is not case-sensitive, but a file name: in It is not case-sensitive under Windows, but it is case-sensitive under Linux/UNIX]
[Name rules:

  1. Meaningful (English, English combination or English abbreviation)
  2. The name set by yourself is best in lowercase.
  3. It is best to capitalize SQL statements.

1、 CREATE TABLE users(
id INT,
name CHAR(32)
);
2、 SHOW TABLES;
3、 DESC users;
4、 SELECT * FROM users;

Second, the data values ​​and column types
are subdivided by the size of the space, which can be saved!

1. Numerical
integer type (integer):
very small integer type 1 byte -128~127 0~255 (unsigned) TINYINIT
small integer type 2 bytes -32768~32767 SMALLINIT
medium size integer type 3 bytes 0~ 16777215 MEDIUMIINT
standard integer 4 bytes -2147483648~2147483647 INT
large integer 8 bytes BIGINT
[Attributes can be added: UNSIGNED]
Floating point (decimal):
FLOAT (M, N) 4 bytes [length M, after the decimal point is reserved N bits]
DOUBLE (M, N) 8 bytes [rounded up]
DECIMAL (M, N) M+2 bytes [fixed-point number, store data in the form of a string, save the data more accurately, but the efficiency will be discounted. ][Rounding]
[Floating-point numbers will have errors, so when you are sensitive to numbers, you need to use fixed-point numbers to store! ]
3. Character
type MySQL supports single and double quotation marks to represent string types.
For example, "MySQL" is the same as 'MySQL'
char(M) maximum 255 fixed length string
varchar(M) maximum 255 variable length string
char(4) varchar(4)// always one more byte than character
'' 4 '' 1 byte
'a' 4 'a' 2 bytes
'abcd' 4 'abcd' 5 bytes
'abcdefg' 4 'abcdefgh'

The char type will truncate trailing spaces;
example: CREATE TABLE IF NOT EXISTS tab(v varchar(4),c char(4));
INSERT INTO tab(v,c) VALUES("ab ","ab ");
SELECT CONCAT(v,"#"),CONCAT(c,"#") FROM tab;

Best practice:
fixed length, char type is recommended (may waste some space).
Variable length, varchar type is recommended (may pay some performance penalty)

text text data: article, log length: 2^16-1
MEDIUMTEXT
LONGTEXT

blob binary data: photo, movie length: 2^16-1
MEDIUMBLOB LONGBLOB
[
Although binary files such as photos, movies, and compressed packages cannot be inserted into the database through SQL statements, we can use C++/Java and other programming languages. The file is read into a binary data stream, and then saved to the database]
ENUM enumerates 1 to 2 bytes
ENUM("one","two","three","four")~65535
can only have one value at a time

SET set 1, 2, 3, 4, 8 bytes
SET("one","two","three","four")~64
can have multiple values ​​at a time, separated by ",".
4. Date type
DATE YYYY-MM-DD //If the number of digits is sufficient, you can not add '-'
TIME hh:mm:ss //The number of digits is sufficient, you can ignore ':', the number of digits is insufficient, intercept
DATETIME YYYY from the back -MM-DDhh:mm:ss
TIMESTAMP YYYYMMDDhhmmss //When the number of digits is insufficient, the leading 0 cannot be ignored
YEAR YYYY

[When creating a data table, it is best not to use these time values. It is best to use integers in programming languages ​​such as C++/Java to save the time, which is more convenient for calculation, such as int in C++, timestamp in PHP 1970-1-10 :0:0】

 

3. Data field attribute
1, unsigned [unsigned]
can double the space, such as -128~127 can be increased to 0~255
Note: It can only be used in numeric fields


2. zerofill [leading zero]
eg create table if not exists t2(num int(5) zerofill, price float(7,2) zerofill, name varchar(10));
Note: It can only be used in numeric fields, and it will be automatically added unsigned property on


3. auto_increment [self-increment] #auto automatic; increment increment, increase
when the inserted value is: NULL, 0, when left blank, it will automatically +1; when inserting an existing value, an error will be reported
Note: only use For integers, the field value is not allowed to be repeated (it needs to be implemented in combination with other attributes, such as: primary key) #primary main; primary, basic.
eg create table if not exists t3(id int auto_increment primary key,namechar(10));
insert into t3(id,name) values(null,"xiaofang"); # can be inserted n times continuously, null can be replaced with 0
insert into t3(name) values("xiaofang");
when inserting, it will be inserted in the order of the largest number plus 1
eg delete from t3 where id >1 and id <9;
then insert
select * from t3 order by id;
delete from t3;
insert into t3(name) values("xiaofang"); # * 5
select * from t3;
insert into t3(id,name) values(100,"ashun");
insert into t3(name) values("jichang") # * 5
select * from t3 order by id;
Best practice: it is best to set an ID field for each table, set it as an auto-growth attribute, auto_increment


4. NULL and NOT NULL
NULL: The default is empty
Recommendation: When creating a table, do not insert empty values ​​into each field, because there are many uncertainties when NULL values ​​are converted to other programming languages.
NOT NULL: not empty
eg create table if not exists t4(id int not null,name varchar(10) notnull,price double(7,2) not null) ;
5. default[default value]
eg create table if not exists t5(id int not null default 0,name varchar(10) not null default “NULL”,price double(7,2) not null default 0.00);


6、综合
createtable users(
id int unsigned not null auto_increment primary key,
name varchar(30) not null default “”,
height double(10,2) not null default 1.00,
age int unsigned not null default 1,
sex varchar(5) not null default ”man”

);


Fourth, create an index
1. Primary key index [primarykey] #duplicate replication, so that double entry is entered, intrusion
: Determine the location of a specific data record in the database table, a table can only have one primary key, and the value of the primary key cannot be empty.
Recommendation: It is best to define a primary key for each data table!
eg 1) create table t7(id int not null auto_increment primary key,name varchar(10));
2) create table t7(
id int not null auto_increment,
name varchar(10) not null '',
primary key(id)

); #specify the primary key index at the end


2. Unique index [unique] #unique unique and unique
can prevent the creation of duplicate values, but each table can have multiple unique indexes
create table if not exists users(id int not null auto_increment,name varchar(30 ) not null default '' unique,age int,primary key(id));


3. Conventional index [index/key]
is the most important technology, which can improve the performance of the database and is the first aspect of database optimization. Index can improve the speed of search, but it will slow down the speed of insertion, deletion and modification.
It is an independent data object like a table. It can be used when creating a table, or it can be used
alone: ​​createindex ind1 on users(name,age );
drop index ind1 on users; #Delete index
use when creating:

createtable carts(
id int not null auto_increment,
uid int not null,
sid int not null,
primary key(id),
key cuid(uid),
index csid(sid)

);


4. Fulltext index
fulltext type index can only be used on MyISAM table type, only on varchar, char, text. Can also be used on multiple data columns.
create table books(
id int not null auto_increment,
bookname varchar(30) not null unique,
price double,
detail text not null,
full text(detail),
index ind(bookname),
primary key(id));


Original query: select * from books where bookname like '%C++%';
Now query: select bookname,price from books where match(detail)against('C++');
select match(detail) against('C++') from books ; #match match; against lean, lean;

//MATCH is equivalent to the column to be found, and AGAINST is the content to be found.
The query speed can be significantly improved!

 

5. Data table types and storage locations
1. Unlike most databases, MySQL has a storage engine concept. MySQL can choose different storage engines for different storage requirements.
2. show engines; #View the storage engine storage engine supported by MySQL
3. show variables like 'table_type'; #View the default data table type
MyISAM and the most commonly used storage engine of InnoDB [Table Type]
4. Specify the table type [Which to use A storage engine]:
create table ...() engine = InnoDB;
Note: In a database, different table types can be specified when creating a data table, that is, multiple data tables of different table types can exist in the same database


5. Features of different engines:
1) MyISAM table type:
mature and stable, easy to manage, using a table locking mechanism, it is necessary to use "optimizetable table name" frequently to restore the space wasted by the mechanism.
Emphasis allows for fast read operations. But there are also some functions that are not supported.
2) InnoDB table type:
supports some functions that MyISAM does not support
Disadvantages: takes up a lot of space, does not support full-text indexing
Comparison:

 
6. MySQL default character set
1. MySQL supports data encoding
ASCII code #7 characters to store
ISO-8859- 1/latin1 character set #Western European character set, often used by programmers for transcoding, 8-bit encoding
gb2312-80 #Not recommended
...
GBK [95 years] #2 bytes, can be used, but not recommended, double-byte Encoding
GB18030 [released in 2000] #Database support is relatively rare
UTF-32 #4 bytes, not commonly used
USC-2 #2 bytes, Windows2000 uses
UTF-16 #2/4 bytes encoding internally, JAVA, WindowsXP, WindowsNT internal Use
UTF-8 #1 ~ 4 byte encoding, Unicode is a character set widely supported by Internet and UNIX/Linux and MySQL servers, strongly recommended
eg

GBK 2 bytes: namevarchar(12) 6 Chinese characters
UTF-8 3 bytes: namevarchar(12) 4 Chinese characters


2. MySQL server, database, data table, and fields can specify different character sets. Use "showcharacter set;" to view all character sets supported by MySQL.
Note: UTF-8 in the database is utf8 when used.


3. MySQL's character set includes #character character
character set [charset]: used to define the storage method of MySQL strings
Collation rules [collation]: used to define the comparison method of MySQL strings
is a one-to-many relationship: 1 character The set can correspond to multiple collation rules
show collation like 'gbk%'; #Can be used to view the collation rules corresponding to gbk
show collation; #Can be used to view all the collation rules, ending with ci, which means case insensitive, ending with cs , case sensitive, ending with bin means binary comparison
show variables like 'character_set_server'; #View server-side character set
show variables like 'collation_server'; #View server segment collation rules


4. Specify the default character set and collation rules
create database xsdemo default character gbk collategbk_chinese_ci; #Specify the default character set of the database
create table t1(id int not null auto_increment primary key)engine=myisam default character set gbk collategbk_chinese_ci; #Make the characters of the data table set


5. When the client interacts with the server
character_set_client #client character set character_set_connection
#connection character set character_set_result #return
result character set
Usually these three character sets should be the same, so that the data transmission is the same, use the "setnames character" Set" can modify the values ​​of all three at the same time.
alterdatabase character set utf8; #Modify the character set of the database, alter modification, change
altertable t1 character set utf8; #Modify the character set of the data table The character set of
the server can only change the configuration file


6. Backup database
mysqldump -u root -p --default-character-set=gbk -d xsdemo >/home/xiaofang/backup.sql #dump dump; dump
7. Restore database
mysql -u root -p xsdemo < / home/xiaofang/backup.sql


Seven, modify the table
alter table... #For more information, see ?Alter table;
eg

alter table t1 add price double not null default 0.00;
alter table t1 add sex varchar(5) after name; #Add gender after name
alter table t1 add height double first; #Add height at first position
alter table t1 modify sex char (3); #modify is suitable for changing the type
alter table t1 change name username varchar(5);#change can change both the field name and the type
alter table t1 rename users; #Directly modify the table name
alter table t1 drop age; #delete field
drop table if exists users; #delete data table

 

http://blog.csdn.net/zjf280441589/article/details/18660509

http://blog.csdn.net/zjf280441589/article/details/19496181

http://blog.csdn.net/zjf280441589/article/details/19496303

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327067099&siteId=291194637