sql基础知识第一部分

主要记录平时学习的内容,知识比较散,能记录多少是多少吧,反正也正是学习的目的,理清思路:

1.SQL HAVING 实例

SELECT Customer,SUM(OrderPrice) FROM Orders WHERE Customer='Bush' OR Customer='Adams'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500

----此语句呢, 主要理解having和where的位置

(1)having 相当于where,但是必须放到group by子句后面,放order by子句之前。
 (2) having后面的列必须要在前面select语句中存在,不是会报错!特别要注意这一点


2、多表连接查询和子查询

(1)select * from t1,t2 得到笛卡尔积

(2)使用有连接规则的连接两表

 (3)使用 表别名简化语句

(4)使用inner join

(5)使用left out join/right out join/full out join/cross join

      select * into a from b cross join c

(6)高级连接查询实例

(7)组合查询:union 关键字很重要

    A、两个select之间加上union 如果不希望去掉重复的记录,可以用union all,要注意每个单独的select子句内的字段个数一定要相同。

    B、select z1,z2,null from t1 where z1=‘1’ union select z1,z2,z3 from t1  where z2=‘2’


 3、复制表
(1)只复制表结构

     方法一:select * into b from a where 1<>1;

     方法二:select top 0 * into b from a。
(2)复制表结构、数据
    方法:select into b(a,b,c)  select d,e,f from b;

 

4、删除数据(delete/tuncate)
 (1)delete from t1 where not exits(select * from t2 where t1.field1=t2.field2)(根据条件删除部分数据)

 

 (2)tuncate table t1(删除全部数据,慎用!)

 

5、 随机取部分数据(newid)
    select top 10 * from t1 order by newid();

 

 6、查询数据之间(between)
  select a,b,c from t1 where a not between 1 and 2

 

7、分组查询(group by)

 (1)group by 后面带的参数必须要在前面select 有查询的字段,不是会报错;

      比如:

select a, b from A group by a ----这样会报错
select a, b from A group by a,b----这样才不会报错

   (2)group by 前面可以用where条件语句,这样相当于在条件语句查询后在进行group by分组查询,这里要特别注意用法,不是会报错!

 

posted on 2015-10-29 12:44  找回失去的青春  阅读(97)  评论(0编辑  收藏  举报

导航