Document SQL syntax (MySQL)

Document SQL syntax (MySQL)

1、DDL

1.1. Create a database
create datebase `DATABASE_NAME`;
1.2, create a table
create table `TABLE_NAME`(
	FIELD_NAME TYPE(int, varchar, ...) 
    [primary key/unique/auto_increment/foregin key],
    ...
)
1.3, copy table
/* 复制 表结构 + 数据 */
create table `TABLE_NAME_NEW` as select ...

/* 复制 表结构 */
create table `TABLE_NAME_NEW` like `TABLE_NAME`

Example 1: Create the table right_item_new and copy the structure of the table right_item.

create table right_item_new like right_item;
1.4. View the table creation statement
show create table TABLE_NAME;

2. CRUD (DML and DQL)

2.1, insert statement
insert into TABLE_NAME(FIELD_NAME, ...) value (VALUE, ...);

insert into TABLE_NAME values (VALUE, ...);
2.2. Delete statement
delete from TABLE_NAME [where ...] 

Example 1: There are two tables book_a and book_b, with fields book_id, book_name, book_code (book number), etc., delete the records in the book_a table that have the same book_id field as the book_b table.

delete from book_a where book_id in (
 select book_id from (
	select book_a.book_id from book_a, book_b
    where book_a.book_id = book_b.book_id) as t
);
2.3, update statement
update TABLE_NAME set FIELD_NAME = VALUE, ...
[where ...]
2.4, query statement
select FIELD, ... from TABLE_NAME
[left/right join TABLE_NAME_2 on ...]
[where ...]
[group by FIELD_NAME][having by ...]
[order by FIELD_NAME][asc/desc]
[limit NUMBER]

3. Index

3.1. Create an index
create index INDEX_NAME on TABLE_NAME(FIELD_NAME);
3.2, delete the index
drop index INDEX_NAME on TABLE_NAME;
3.3. View the execution plan of the SQL statement
explain ...

4. View

4.1, create a view
create view VIEW_NAME as select ....
[with check option]
4.2, delete view
drop view VIEW_NAME;

5. Trigger

5.1. Create a trigger
create trigger TRIGGER_NAME
(before/after) TRIGGER_EVENT(insert/update/delete) on TABLE_NAME
for each row
  [when ...]
  ...
5.2. Delete trigger
drop trigger TRIGGER_NAME

6. Stored procedure

6.1, create a stored procedure
create procedure PROCEDURE_NAME ([arg, ...])
  begin
  	...
  end
6.2. Delete stored procedure
drop procedure PROCEDURE_NAME;
6.3, create function
create function FUNCTION_NAME ([arg, ...])
  begin
  	...
  returns type(in/out/inout)
  end
6.4. Delete function
drop function FUNCTION_NAME;

Guess you like

Origin blog.csdn.net/weixin_51123079/article/details/127733338