SQL学习笔记
1 从 "XXX" 表中选取 50% 的记录:
SELECTTOP 50 PERCENT * FROM XXX
2 查找以N开头的(结尾的用%N,包含的用%N%)
SELECT* FROM Persons WHERE City LIKE 'N%'
不包含:NO LIKE
第一个字符后面是N的:_N
以a或者b或者c开头的:’[abc]%‘,
不以a或者b或者c开头的‘[!abc]%’
3 IN:
选择Name等于a,b,c 的:
Select* from table where Name in (a, b, c)
4 选择Value等于2到5的
Select* from table where Value between 2 and 5
Not between(不包括)
5
Alias(别名使查询程序更易阅读和书写)
假设我们有两个表分别是:"Persons" 和"Product_Orders"。我们分别为它们指定别名 "p" 和 "po",现在,我们希望列出 "John
Adams" 的所有定单
SELECTpo.OrderID, p.LastName, p.FirstName
FROM Persons AS p, Product_Orders AS po
WHERE p.LastName='Adams' AND p.FirstName='John'EG:
6 innerjoin
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons, Orders
WHERE Persons.Id_P = Orders.Id_P
查询两张表:
Select* from XXX1 inner join XXX2 on xxx1.ID= XXX2.ID
LEFT JOIN 关键字会从左表 (Persons) 那里返回所有的行,即使在右表 (Orders) 中没有匹配的行
查询互赞用户
7 Union:同名不展示
Union all: 同名的也展示出来
EG:
UserID dianzanuserID
A B,C,D
B A,D,E
SQL显示互赞用户语句:
Select UserID, dianzanuserID from table where UserID in (select dianzanuserIDfrom table) and dianzanuserID in (select UserID from table)
8
Insert: Insert into orders(a,b,c) values(a,b,c)
UPDATEOrdersSET FirstName = 'John', LastName = 'Who' WHERE LastName='Wo'
DELETE FROM Orders WHERE OrderDate < '10/10/2010'
先ALTER table XXX.再alter column XXX type(year)
9 AUTO_INCREMENT自动增加
10
等号(=):是用来查找与单个值匹配的所有数据;
IN :是用来查找与多个值匹配的所有数据;IN子句中也可以使用数字、字符串或日期
LIKE:用来查找与一个模式匹配的所有数据。(模糊查询)
Example:
select * from table where name =“Youri”
select * from table where name in(“MTbaby", "abboter", "小明")
select * from table where name like”%Youri%”
11 EXTRACT()("提取"的意思) 函数用于返回日期/时间的单独部分,比如年、月、日、小时、分钟等等
EG:EXTRACT(MONTH FROM OrderDate) AS OrderMonth,
12 count()
Select count(*) from table
13 having的用法
Select s.id from table group by sid having sum(score)>60
14 limit
返回排在第n个的值
Select salary, eid from employee oder by salary limit n-1,1
15 Datediff()
Where DATEDIFF(date1,date2)=1 两个日期变量的差值为1(连续的两天)
16 窗口函数:可以用于排序,生成序列号等,包括sum,avg,count,max,min, rank,dense_ran看,row_number等(只用在select中)
<窗口函数> over ([partition by<列清单>] order by<排序用列清单>)
17 IFNULL()
IFNULL((select a from table group by a limit 1,1),NULL)
18 Group by 默认由小到大排序 降序:desc
select a from table group by a desc