当前位置:Gxlcms > 数据库问题 > sql基本查询语句

sql基本查询语句

时间:2021-07-01 10:21:17 帮助过:4人阅读

查询满足条件的元组,一般通过where 语句实现:select 列名 from 表名 where 条件

技术分享

例子:

1、比较:select * from lu_order where sku =‘123‘

2、确定范围 :select * from lu_order where stage between 20 and 30

3、确定集合:select * from lu_order where sku in(‘123‘,‘1232‘,‘1232323‘)

4、字符匹配:select *from lu_order where sku like ‘%123_‘   (%_指通配符,%可表示任意字符长度的字符,_表示单个字符)

5、空值:select * from lu_order where sku is null

6、多重条件逻辑运算: select * from lu_order where sku=‘123’ and type=‘234’

 

三  order by使用

对查出的元组按指定的列(一个或多个)按升序(asc)或降序(desc)排序

1、升序:select * from lu_order order by id asc

2、降序:select *  from lu_order where sku=‘122’ order by sku  desc

 

四 group by 

将查询结果按照某一列或多列进行分组,值相等的为一组。一般是为了细化聚合函数的作用对象,若未进行分组,则聚合函数是作用整个查询结果;若分组了,则是每个组一个聚合函数作用。

常用的聚合函数有:

技术分享

 

例如:

1、未分组,使用聚合函数:select count(*)  from lu_order--->计算出表中的所有元组数量

2、分组,使用聚合函数:select ordernumber,count(*)  from lu_order  group by ordernumber--->ordernumber相同的为一组,得出每组中包含的元组数量

 

五 having子句

对分组后的结果进行筛选,得出符合条件的组。注意:使用having则,查询语句中必须使用了group by,否则会报错。

例如:

1、select ordernumber,count(*)  from lu_order  group by ordernumber having ordernumber in(‘1‘,‘2‘,‘3‘)--->ordernumber相同的为一组,得出每组中包含的元组数量

 

六 limit 字句

限制结果显示的条数。

例如:

1、查询前3行的数据:select *  from lu_order limit 0,3

 

七  多表查询

表跟表之间通过某些条件,连接起来。

1、自然连接:select a.*,b.* from lu_order a,lu_order_detail b where a.ordernumber=b.ordernumber

2、自身连接:select a.*,b.* from lu_order a,lu_order b where a.ordernumber=b.ordernumber

3、左连接:select a.*,b.* from lu_order  left out join lu_order_detail

4、右连接:select a.*,b.* from lu_order  right out join lu_order_detail

 

八 嵌套查询

在select-from-where..称为一个查询块,将一个查询块嵌套在另一个查询块的where或having子句中的就叫做嵌套查询。

例如:

1、select  ordernumber,sku,carrier from lu_order  where ordernumber in(select ordernumber from lu_order_detail  where ordernumber=‘1‘)

 

sql基本查询语句

标签:limit   通过   多表   常用   sql   http   strong   style   logs   

人气教程排行