sql basics (for mysql)

Create database
CREATE DATABASE database name;

delete database
DROP DATABASE database name;

mysql close/open safe mode
SET SQL_SAFE_UPDATES = 0;
SET SQL_SAFE_UPDATES = 1;

create table
CREATE TABLE T_Person (FName VARCHAR(20), Fage INT, FRemark VARCHAR(20) ,PRIMARY
KEY (FName));

CREATE TABLE T_Debt (FNumber VARCHAR(20),FAmount DECIMAL(10,2) NOT NULL,
FPerson VARCHAR(20),PRIMARY KEY (FNumber),
FOREIGN KEY (FPerson) REFERENCES T_Person(FName) ) ;

delete data in the table
TRUNCATE TABLE table name;
DELETE FROM table name;

delete table
DROP TABLE table name

Simple additions, deletions and changes
INSERT INTO tablename (field name) VALUES (field value);
any order of fields, any number of fields (non-null constraint field must be inserted)
INSERT INTO T_Person(FName,Fage,FRemark) VALUES('Tom',18,'USA');

UPDATE tablename SET fieldname=value
UPDATE tablename SET fieldname=value WHERE ...
UPDATE T_Person SET Fage = 12 WHERE FNAME= 'Tom';

DELETE FROM table name WHERE ...
DELETE FROM T_Person WHERE Fage > 20 or FRemark = 'Mars';

Query statement
SELECT * FROM table name;
SELECT field name FROM table name;
SELECT * FROM table name WHERE ... ;

Aliasing mechanism
SELECT field name as alias FROM table name;
SELECT alias. field name FROM table name as alias;

max, min, avg, sum function

count function
SELECT COUNT(*), COUNT(FNumber), COUNT(FName) FROM T_Employee
#COUNT(*) counts the total number of results in the result set, while COUNT(field) counts the total number of records except that the fields in the result set are not null (that is, not equal to NULL).

Sort function (ASC ordering - default, DESC descending order)
SELECT * from t_employee order by Fage desc,FSalary desc;
#ORDER BY clause is at the end of the SELECT statement

LIKE and wildcard
SELECT * FROM T_Employee WHERE FName LIKE '_erry';
#'_' single-character match, '%' multi-character match

NOT non-
SELECT * FROM T_Employee WHERE NOT(FName LIKE 'S%') AND NOT(FName LIKE 'J%');

sql judges NULL,NOT NULL
select * from T_Employee where FName is null;

select * from T_Employee where FName is not null;

IN clause
SELECT Fage,FNumber,FName FROM T_Employee WHERE Fage IN (23,25,28);

BETWEEN (mysql default includes boundaries)
SELECT * FROM T_Employee WHERE FAGE BETWEEN 23 AND 27 #equivalent
to >=23 and < =27

GROUP BY grouping function
SELECT Fage FROM T_Employee GROUP BY Fage;
#GROUP BY must be after the select statement

SELECT Fage,sum(FSalary) FROM T_Employee GROUP BY Fage;

#GROUP BY clause can specify multiple columns, just separate the column names of multiple columns with commas. After specifying multiple grouping rules,
#the database system will group the data layer by layer according to the defined grouping order, first grouping according to the first grouping column, #then grouping
again according to the second grouping column in each group ... grouping layer by layer, so as to achieve the effect of "group in group", and the result set of the query is output by the last level of grouping.
SELECT FSubCompany,FDepartment FROM T_Employee GROUP BY FSubCompany,FDepartment;

HAVING #Only
retrieve age groups with more than 1 person
SELECT Fage,COUNT(*) AS CountOfThisAge FROM T_Employee GROUP BY Fage HAVING COUNT(*)>1

requires special attention, in HAVING The statement cannot contain ungrouped column names. For example, the following SQL statement is wrong:
SELECT Fage,COUNT(*) AS CountOfThisAge FROM T_Employee GROUP BY Fage HAVING FName IS NOT NULL
When executed, the database system will prompt an error message similar to the following :
The column 'T_Employee.FName' in the HAVING clause is invalid because the column is not included in an aggregate function or GROUP BY clause.
A WHERE statement needs to be used instead of HAVING. The modified SQL statement is as follows:
SELECT Fage,COUNT(*) AS CountOfThisAge FROM T_Employee WHERE FName IS NOT NULL GROUP BY Fage

LIMIT
MYSQL provides the LIMIT keyword to limit the returned result set. LIMIT is placed at the end of the SELECT statement, and the
syntax is "LIMIT the first row number, the maximum number of result sets to be returned". For example, the following SQL statement will
return up to five records starting from the second row (row numbers start at 0) in descending order of salary:
SELECT * FROM T_Employee ORDER BY FSalary DESC LIMIT 2,5;

DISTINCT
SELECT DISTINCT FDepartment FROM T_Employee;
SELECT FDepartment FROM T_Employee;
#DISTINCT suppresses data duplication for the entire result set, rather than for each column, execute the following SQL statement:
SELECT DISTINCT FDepartment,FSubCompany FROM T_Employee;

Index
Indexes are special files (indexes on InnoDB tables are an integral part of a tablespace) that contain pointers to all the records in the table. More generally speaking, the database index is like the table of contents in front of a book, which can speed up the query speed of the database. For the above SQL statement, if there is no index, the database will traverse all 200 pieces of data and select the eligible items; after having the corresponding index, the database will directly find the eligible options in the index.
Although indexes can improve the speed of data query, everything is a double-edged sword, and it also has some disadvantages: indexes occupy a certain amount of disk space, and indexes slow down the speed of data insertion and deletion. Because indexes need to be updated for every insert and delete, the more indexes a table has, the greater the average performance drop for write operations.
CREATE INDEX index name table name (field1, field2, ...)
DROP INDEX index name ON table name;

constraint (: not null constraint; unique constraint; CHECK constraint; primary key constraint; foreign key constraint)
not null constraint:
NOT NULL

Unique constraint:
Defining a composite unique constraint needs to be defined after the list of all fields. The syntax is as follows:
CONSTRAINT constraint name UNIQUE (field 1, field 2... field n)
where "field 1, field 2... field n" is the composition of the constraint Multiple fields, if there is only one field, it can be regarded as another form of single-field unique constraint definition. A unique constraint defined in this form has a definite name, so it is easy to delete the constraint by this name.
Add/drop a unique constraint to an existing table
ALTER TABLE table name ADD CONSTRAINT unique constraint name UNIQUE (field 1, field 2... field n);
ALTER TABLE table name DROP CONSTRAINT unique constraint name
However, the above syntax cannot be executed in MYSQL. The syntax for deleting constraints in MYSQL is:
ALTER TABLE table name DROP INDEX unique constraint name

check constraint:
add CHECK constraints directly to the column definition, you can use constant expressions, and you can also use functions. But the downside is that constraints cannot refer to other columns.
To use other columns, you need to use
CONSTRAINT constraint name CHECK(...)
to add/delete check constraints to the already created table
ALTER TABLE table name ADD CONSTRAINT constraint name CHECK(...);
ALTER TABLE table name DROP CONSTRAINT constraint Name
However , the above syntax cannot be executed in MYSQL. The syntax for deleting constraints in MYSQL is:
ALTER TABLE table name DROP INDEX constraint name

Primary key constraint:
directly created when the table is created
Data type field name PRIMARY KEY, or
CONSTRAINT primary key name PRIMARY KEY (Field 1, Field 2,...)
Add/delete primary key to an already created table
ALERT TABLE table name ADD CONSTRAINT primary key name PRIMARY KEY (field 1, field 2,...)
ALERT TABLE table name DROP CONSTRAINT primary key name
However, in mysql, it needs to be written as
ALERT TABLE table name DROP PRIMARY KEY

Foreign key constraints:
create
CONSTRAINT foreign key name POREIGN KEY (field name) REFERENCES associated table name (associated field)
add/delete foreign key to the already built table
ALERT TABLE table name ADD CONSTRAINT foreign key name POREIGN KEY (field name) REFERENCES associated table name (associated field)
ALERT TABLE table name DROP CONSTRAINT foreign key name
But in mysql it needs to be written as
ALERT TABLE table name DROP FIREIGN KEY external name

table connection
inner join
select order from A INNER JOIN B ON A .name = 'TOM'
Query all orders named TOM in table A and table B.
inner join is based on the relationship between the two tables to join the tables, only the union of the two tables is displayed compared to the inner join

cross join
, cross join is very simple, because it does not exist ON clause. A cross join will include all records in
all tables involved in the result set

outer join
left outer join
In a left outer join, all records in the left table will be placed in the result set, regardless of whether there is a match in the right table
Record.

right outer join
In contrast to a left outer join, a right outer join returns
all .

full outer join
is a combination
of outer join and right outer join, because even if there is no data matching the join condition in the right table, all records in the left table
will be put into the result set, also even in the left table. No data matching the join condition exists in the table, and all records in the right table
will also be placed in the result set.
Full outer join is not supported in mysql, you need to use UNION to get the collection of left join and right join.

UNION
The UNION operator is used to combine the result sets of two or more SELECT statements.
Note that the SELECT statement inside the UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same.
SQL UNION syntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note: By default, the UNION operator selects different values. If duplicate values ​​are allowed, use UNION ALL.

UNION ALL
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
In addition, the column names in the UNION result set are always equal to the column names in the first SELECT statement in the UNION.

Self-connection
So far , the connections we have explained are between different data tables. In fact, the tables participating in the connection
can be the same table, that is, the table is connected to itself, so the connection is called self-connection. . Self-connection is not another connection method independent
of cross-connection, inner-connection, outer-connection and other connection methods, but only
a special case of these connection methods, that is, cross-connection, inner-connection, outer-connection and other connection methods. As long as the tables participating in the join are the same
table , they can be called self joins.

Subquery
SELECT statements can be nested in other statements, such as SELECT, INSERT, UPDATE, and DELETE. These nested SELECT statements are called subqueries. It can be said that when a query depends on the results of another query, it can be Use subqueries. There are two types of subqueries. One is a subquery that only returns a single value. In this case, it can be used where a single value can be used. At this time, the subquery can be regarded as a function with a return value. The first is a subquery that returns a column of values. At this time, the subquery can be regarded as a data table that exists temporarily in memory.

Single
- valued subquery The syntax of a single-valued subquery is no different from that of an ordinary SELECT statement. The only restriction is that the return value of the subquery must have only one row and only one column. Such subqueries are also called scalar subqueries.

Column-valued subqueries
Unlike scalar subqueries, column-valued subqueries can return a result set with multiple rows and multiple columns. Such a subquery is also called a table subquery. A table subquery can be regarded as a temporary table. A table subquery can be used in the FROM clause of a SELECT statement, an INSERT statement, a join, an IN clause, and many other occasions.

Scalar subqueries in the SELECT list
Scalar subqueries are perfectly fine to return values ​​that vary with the current query record.
SELECT FId,FName,(SELECT MAX(FYearPublished) FROM T_Book WHERE T_Book.FCategoryId= T_Category.FId) FROM T_Category;
Returns the latest publication year of a category of books

scalar subquery in the WHERE clause
select FReaderId from t_readerfavorite where FCategoryId = (select Fid from t_category where FName="Story");
the primary key list of readers who like "Story"

Guess you like

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