My SQL (1) Basic Operation

MySQL is one of the popular relational database management systems, especially in WEB applications. Version 5.6 is recommended.

 My Sql client has a lot of

 There are PHP MyAdmin, is a web form and control the operation of the MySQL database management tool. WAMP is an integrated package of software tools.

Navicat premium cracked version installation and connection http://www.downcc.com/soft/322714.html 

Supplementary MYSQL

(1) limit two numbers

select * from student limit 2,4 

2 represents the first of several data start with an index; the second 4 represent how much data the current page display.

limit 2,4 denotes the third from the start, the display 4 the data.

(2) limit two numbers

select * from student limit 4. 4 show data.

(3) grouping function aggregate functions together with general! !

select sdept, count(*) from student group by sdept;

(4) having the conditions for grouping function! !

select sdept,count(*) from student group by sdept having count(*)>5

(5) show tables show all the current database tables and views

The main function is to simplify the query view, a lot of complex nested queries

 (6) stored procedure

Example 1:

CREATE DEFINER=`root`@`localhost` PROCEDURE `pro1`(OUT `cnt` integer)
BEGIN
    #Routine body goes here...
select count(*) into cnt from student where sdept='PC';
END

Call in the query

the set  shu = 0 to ;
call pro1(@shu); 
select @shu;

shu is session variables, beginning with @.

Example 2:

Write the query script

CREATE PROCEDURE pro3(IN sig integer,OUT cnt integer)
BEGIN
    IF sig = 1 THEN
        SELECT count(*) INTO cnt FROM student WHERE sclass = '01';
    ELSE 
        SELECT count(*) INTO cnt FROM student WHERE sclass <>'01'; #<>
    end if;
END;

Call pro3 does not appear in the list on the left need to refresh

call pro3(1,@cnt);
select @cnt;

---

(7) Index

You can improve query data, where data can be used in a lot of cases, commonly used in the field general inquiries indexed.

Add an index, will form "backup" copy sorted index it will consume memory!

chapter1 database operations

1. System database: After installing MySQL server is, with some of the database. For example information_schema, information (user name information, column information, rights information, etc.) stored in the main database objects. performance_schema primarily for storing a database server performance parameters.

Create a database create database xy; or create schema xy;

Database does not allow two of the same name, you can create database if not exists xy;

2. view, select, delete database

show databases|schemas like|where

show databases like 'db_%'; to find the beginning of the db database.

Select the database. After create database statement, the database will not be a current database, you need to write use database;

Delete database drop database | schema, such as drop database if exists xy;

chapter2 data types

1. Digital Type

tyniint (if the value is not more than 127, better than with tyniint int);

There are int, float, double and so on.

2. String type

(1) Normal: char, varchar (variable length)

(2) Variable: text for text length; BOLB for binary data to support any data, including text, sound, images and the like.

(3) Special: enum ( 'value1', 'value2', ......), the contents of the column is limited in one option, only one of the values ​​listed or null;

set ( 'value1', 'value2', ......), can accommodate a set of values ​​or null.

3. The date and time types

datetime\date\timestamp\time\year

date format yyyy-mm-dd

time format is hh: mm: ss

datetime format yyyy-mm-dd hh: mm: ss

Datasheet operation chapter3

1. Create a table

 create table if not exists table (column 1 1 attribute, second attribute column 2, ......);

Report an error if not exists to avoid the build table.

For table successfully created, you can view the table show columns or describe the structure

show columns from the table name from the database name; or show columns from a database table names

describe table name or table names for short desc;

Or look at a field desc ranked table name;

2. Modify the table structure

Add a new field alter table table name add sno varchar not null;

Modify field name alter table table name change column old field new field;

Delete field alter table table name drop field names;

Modify the table name alter table table name rename as a new table name; or rename table the old table to the new table name;

Copy the table create table (if not exists) the new table name like the name of the source table; this statement does not copy the data in the table.

 create table (if not exists) the new table name AS the SELECT * from source table name; the copied data.

Delete table drop table (if exists) table;

 

chapter 4 MYSQL basis

1. Arithmetic Operators + - * / 

Remainder% or mod 

select score,score+score from student;

2 does not equal comparison operators <> or! = 

is null ; is not null; between.. and ...; in ;not in;

like; not like; regexp (regular expressions)

regexp can match the value of a field whether to start with the specified character, end, or contains a string.

The return value is 1 or 0.

3. Logical Operators

and  && ; || or ;  ! not ; xor 异或

Shame shame = 0; 0 0 1 1 = 0;

4. Process control

(1)if then.. elseif then... else... end if;

(2)case

case value

   when .. then...

   when..then...

   else...

end case

(3)while

while condition DO

...

end while

Creating a procedure

create procedure pro4(out sum int)
begin 
declare i int default 1;
declare s int default 0;
while i<10 DO 
set s =s+i;
set i=i+1;
end while;
set sum=s;
end

transfer

call pro4(@s);
select @s

45 obtained: From 1 + 9 = 45 ,,,;

(4)loop 

loop

...

end loop

(5) repeat the first loop executed once, after the judgment for condition Condition, true loop is exited.

repeat 

...

until conditon 

end repeat

create procedure pro5(out sum int)
begin 
declare i int default 1;
declare s int default 0;
repeat 
set s =s+i;
set i=i+1;
until i>10 
end REPEAT;
set sum=s;
end


call pro5(@s);
select @s

55 obtained from the 1 + 10 = 55 ,,,

 

CRUD chapter5 table data, commonly used functions

1. Increase Data

(1) insert into table values ​​( '', '', ''), ( '', '', ''); a plurality of data can be inserted.

(2) insert into table set sname = 'mike', sno = '001'; the specified field.

(3) insert into table select clause.

insert into 表名 (sno,sname) select sno,sname from student;

2. Modify Data

update  表名  set sname='mike' where sno='001';

3. Delete Data

delete from table name where sno = '001'; delete a row of data

truncate table table name; delete all the rows in the table.

4. group by

select sname,sdept from student group by sdept;

Do not function, group by a set of display data of only one

      

select sdept,count(*)from student group by sdept;

GROUP_CONCAT can be a group of the following field values ​​are displayed.

select sdept,GROUP_CONCAT(sname) from student group by sdept;

 

 5. exists inquiry

When using exists, the inner query does not return records check, but return a true or false value. Return true, the outer query query.

If there are 001 students sc table number, then the look-up table of student data. 

select * from student where exists(select * from sc where sno='001');
select * from student where sclass='01' and exists (select * from sno='001');

not exists: If the inner returns false, the outer query began.

6. any 与 all

<Any (select score from ...) represents less than all values.

> All greater than the maximum.

7. Regular Expressions

Beginning with x ^ x

x $ x to end

. Matches any single character

[Character Set]  

[^ Set of characters] [^ abc] Apart from any one character abc

a|b|c

* Matching the characters preceding the plurality of symbols comprising zero or 1;

+ Matches the characters preceding the plurality of the symbol, or more;

{N} n times the matched string occurs;

{M, n} occurs once mn;

select sname from student where sname regexp'm$' ;  以 m 结尾。

regexp 'a {3}' a appears three times;

'J + A' at least once J; 

8. Mathematical Functions

abs (x); ceil (x); floor (x); rand () random number between 0-1; sign (x); PI ();

truncate (x, y) x y bits reserved to the decimal value; round (x); pow (x, y) or power (x, y);

sqrt, exp, mod (x, y); log (x), a radix 2; log10 (x); sin (); asin (); cos (); acos ();

select abs(-5),sqrt(5);

9. String Functions

Characters char_length (s) s of;

The length of the length (s) s (bytes);

concat(s1,s2,...) 

cncat_ws (x, s1, s2, ...); each string to be added directly x

select CONCAT_WS ( '*', 'aaa', 'bbb'); get aaa * bbb

upper(s); lower(s);

left (s, n) n characters left; right (s, n);

Ltrim(s); Rtrim(s);

insert (s1, x, len, s2): s1 len length from x bits replaced by s2. select insert ( 'mikj', 3,2, 'book') obtained mibook

repeat (s, n); s is repeated n times;

substring (s, n, len), len acquired length of the string s starting at position n.

reverse (s), in turn, sequentially;

field (s, s1, s2 ...) returns the position of the first string matches s. select field ( 'aa', 'bfa', 'faae', 'aa') to give 3.

locate (s1, s) s1 start position in s; There are similar position (s1 in s) or instr (s, s1)

10. The date function

curdate (); current_date (); the same, to get the current date.

curtime (); current_time (); Get the current time.

Gets the current date and time: now (), current_timestamp (), localtime (), sysdate ();

Days datediff (d1, d2) spaced. SELECT datediff ( '2014-2-4', '2015-4-9') -429

adddate (d, n); contrast subdate (d, n);

11. The condition judging function! ! ! Very important

if (expr, v1, v2), expr founded on the implementation of v1; 

ifnull (v1, v2), v1 is not empty is returned v1, otherwise v2;

case when expr1 then v1 when expr2 then v2 else v0 end 

case expr when e1 then v1 when e2 then v2 else v0 end 

12. The system information function

 version () database version number

connection_id () Get the number of server connections

database (), schema () Gets the current database name

user (), system_user (), session_user () Gets the current user

 

 

 

 chapter 6 Index

Indexes can improve query speed, without traversing all the data in the table, only you need to query the index column.

Like a book index directory. But creating an index and ongoing maintenance takes a lot of time, the index will take up physical memory.

There will also affect the index table insert operation, because the newly inserted data will be sorted by index. (You can delete the index and then insert the data, then rebuild the index ..)

Index type:

(1) general index normal:

(2) the only index: unique, the only value of the index. The primary key is a special index

(3) full-text index fulltext: char varchar text can only be established in the field of type Yes.

Create a regular index 

create table score(id int(11), auto_increment primary key not null), 
name varchar(20) not null, grade int(5) not null, index(id))

Create a unique index

create table score(id int(11), auto_increment primary key not null), name varchar(20) not null, grade int(5) not null, unique index(id))

Create a full-text index, the index name is beizhu1

create table score(id int(11), auto_increment primary key not null), 
name varchar(20) not null,
grade int(5) not null, beizhu varchar(100),FULLTEXT KEY beizhu1(id))

The creation of the index in an existing table

create index index name on table name (field)

create index stu_info on student(info)
create unique index stu_info on student(info)
create fulltext index stu_info on student(info)

Modify, delete indexes

the ALTER  the Table Student the Add  index idx1 (SnO);
 drop  index idx1 ON Student; # delete the index

chapter7 view

create or replace view view1(sno, cno) as select 。。with check option. 

with check option when updating a view to ensure representation within the purview of the view.

View View desc view name

Look view

 

 Watch

 

 This is the difference between the tables and views

show create view pc view detailed definition of the view pc's.

Modify the view, you can change which columns

alter  view view1(sno) as  select sno from student with check option;

Update the view: update view1 set grade = 100 where sno = '001';

Updates to the view that an update to the base table.

并不是所有的视图都可以更新,以下情况不能更新:

(1) 用了函数sum等;

(2) 包含union, distinct,group by, having;

(3) 视图中的select 包含子查询。

最好不要通过视图进行更新。删除视图 drop view if exists view1;

 

chapter8 数据完整性约束

1.实体完整性

(1)主键约束, 一个表只能有一个主键,主键能够唯一标识一行记录,且不为null. 可以是一列或者多列。primary key.

(2)候选键约束,可以是一列或多列。值唯一且不为空。unique

2. 参照完整性

foreign key(sno) references sc(sno) on delete restrict on update restrict;

reference 后面跟的表是被参照表(父表)。

restrict:禁止对被参照表的删除或者更新;

cascade: 被参照表删除或更新时,参照表的数据也被更新或删除;

set null :被参照表删除或更新时,设置参照表中对应的外键为null;

3.用户定义完整性

check(expr) : 

对列:age int not null check(age>0 and age<100)

对表:check sno in (select sno from student)

 

   

 

 

Guess you like

Origin www.cnblogs.com/xuying-fall/p/11788623.html