事先设定一个表 :table1,包含字段:id,qty,name,city
普通查询:
select * from table1
select 1 from table1
为什么存在select 1 from 这种写法呢?
当我们只关心数据表有多少条记录,而不需要知道具体的字段的数值时,这是一个很不错的写法,可以减少系统的开销,提高运行效率。因为这样写,数据库引擎就不会去检索数据表里一条条具体的记录和每条记录里一个个具体的字段值并将它们放到内存里,而实根据查询到多少行记录就输出多少个“1”,每个“1”代表一条记录,同时选用数字 “1” 还因为它所占的内存空间最小,当然用数字 字 “0” 的效果也一样。在不需要知道具体的记录值是什么的情况下这种写法无疑更加可取。
举两个例子:
select name ,count(1) as num from table1 group by name
select a.* from table1 as a where not exists( select 1 from table2 as b where b.id=a.id)
select top 1 from table1
select top 10 percent * from table1
select distinct name from table1
select count(distinct name) from table1 //--------统计以name去重后的记录条数
select avg(qty),sum(qty),max(qty), min(qty) from table1
条件查询 :
select * from table1 where name= '青峯'
select * from table1 where name like '%青峯%' ['青峯%']['%青峯']
select * from table1 where name not like '%青峯%'
select * from table1 where name= '青峯' order by city desc[asc]
select count(*) from table1 group by name
select count(*), name table1 group by name
select count(qty), name table1 group by name
select * from table1 where date between '2019-01-22' and '2019-12-31'
select * from table1 where date > '2019-01-22' and date < '2019-12-31'
select * from table1 where id in (1,2)
select * from table1 where id=1 or id=2
对同一字段进行搜索,in和or的区别在哪呢?
在需要使用的这个字段所在的列为索引或者主键时,使用in或者or的区别不是很大。
反之,在没有索引的情况下,随着in或者or的数量越来越多,in的效率不会有很大的下降,但是or会随着记录越来越多的情况下性能下降很快。
因此在给in和or的效率下定义的时候,应该再加上一个条件,就是所在的列是否有索引或者是否是主键。如果有索引或者主键性能没啥差别,如果没有索引,性能差别不是一点点!
select * from table1 where name is null
select * from table1 where name != '青峯'
select count(*),city from table1 group by city having city=‘guangzhou’
查询篇暂时到此,当中可能会有遗漏的写法,期间会不断地补充,同时欢迎大家各抒己见,共同分享,感谢大家...................