Summary of common SQL statements

Inquire:

 

1. Test center: check the scores of account s_01 in all subjects

 

select id,pin from student where pin='s_01'

select sid,gid,fenshu from student_group where sid=222

select id,name from group where id=333

 

The account must exist, and the account-subject relationship exists, then the score must exist. If the account-group relationship does not exist, it does not need to be displayed, then:

According to the left join feature, all columns of the left table will be listed. The sql statement is:

 

selct XX from A left join B on A.XX=B.XX where XXX;

 

select s.pin as 学生,g.name as 学科,sg.fenshu as 分数 from student as s left join student_group as sg on s.id=sg.sid left join group as g on sg.gid=g.id where s.pin='s_01'

 

2. Query grouped data, such as querying the total score of all students, test sites: sum function, max, min, avg, group by

 

select s.pin as 学生,sum(sg.fenshu) as 分数 from student as s left join student_group as sg on s.id=sg.sid where s.pin in('s_01','s_02') group by s.pin

 

sum() is generally used with group by.

 

 

3. select count (distinct A) from XXX, when calculating the total, if there are duplicates, use this syntax to remove duplicates from A.

 

4. Select distinct A from XXX. When querying results, if there are duplicate items, use this syntax to remove duplicate items from A.

 

5. Having syntax:

SELECT column_name, aggregate_function(column_name)

FROM table_name

WHERE column_name operator value

GROUP BY column_name

HAVING aggregate_function(column_name) operator value

order by XXX

 

eg:

SELECT Customer,SUM(OrderPrice) FROM Orders

GROUP BY Customer

HAVING SUM(OrderPrice)<2000

order by Customer desc

 

 

Added:

INSERT INTO table name VALUES (value1, value2,....)

eg: INSERT INTO Persons VALUES ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing') (Persons table has 4 columns)

 

We can also specify the column to insert data into:

INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

eg:INSERT INTO Persons (LastName, Address) VALUES ('Wilson', 'Champs-Elysees')

 

Revise:

 

UPDATE table name SET column name = new value WHERE column name = some value

 

delete:

 

DELETE FROM table name WHERE column name = value

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326120895&siteId=291194637