Basic database operations
SQL operations can be achieved:
operating | Language |
---|---|
Build a table | CREATE TABLE table (c1 int,c2 varchar(50),c3 varchar(50)); |
Delete table | DROP TABLE table; |
Modify column | ALTER TABLE table ADD/DROP/ALERT column_name (datatype); |
select | SELECT c1,c2 FROM table WHERE … ; |
insert | INSERT INTO a VALUES(9,30,30); |
Update | UPDATE table SET c1=value1,c2=value2,…WHERE… ; |
delete | DELETE FROM table WHERE …; |
connection | select * from [user] full JOIN phone ON [user].id=phone.id |
WHERE | |
HAVING | Filter each group of data after grouping SELECT FROM WHERE GROUP BY HAVING; |
Operation result processing | WHERE |
---|---|
AND | SELECT * FROM table WHERE c1=‘a’ AND c1=‘b’; |
OR | SELECT * FROM table WHERE c1=‘a’ OR c1=‘b’; |
Sort ORDER BY | Keyword is used to sort the result set according to one or more columns, in descending order ORDER BY column name DESC, column name DESC |
Designated mode LIKE | Operators are used to search for the specified pattern in the column in the WHERE clause. |
Return the number of rows COUNT(c1) | SELECT COUNT(c1) FROM table WHERE ; |
Alias AS, AS can be omitted | Name AS alias, such as SELECT column name FROM table name AS alias; |
SQL join is used to combine rows from two or more tables : INNER JOIN and JOIN (INNER JOIN and JOIN are the same
), LEFT JOIN (left full right empty), RIGHT JOIN, FULL JOIN
Processing view VIEW, index
trigger
Create TRIGGER [dbo].[Trigger_Insert]
ON a
AFTER INSERT
AS
BEGIN
Declare @age int; --@age为局部变量
Select @age=Age From inserted
IF(@age<150)
Begin
Insert into a(id, name, age)
Select ID, Name, Age From inserted
END
ELSE
Begin
print('年龄应小于150')
rollback transaction --数据回滚
END
END
SELECT name, AVG(age) AS age FROM a
GROUP BY name HAVING AVG(age) > 12
other
Error handling
user is a keyword in sql, so an error will be reported. Generally, do not use keywords as table names. If keywords are used as table names, use [] to enclose
Writing norms
1. All lowercase SQL statements
2. Use single quotes when quoting characters
3. Add parentheses before and after the subquery
4. It is forbidden to use select * statements, and the specific fields of select must be pointed out. Avoid the use of'*' in the select clause. During the process of parsing, the database will convert'*' into all the column names in turn. This work is done by querying the data dictionary, which means that more time will be spent
5. It is forbidden to use insert into table values(?,?,?), you must point out the specific fields to be assigned, namely insert into tablea (col1, col2,…) values(?,?,…)
6. Avoid implicit type conversion. For example, the comparison or addition of numeric and int columns in the where clause, string conversion, etc.
7. Prohibit the use of views (views are basically related data between several tables. Very pressure for large data queries)