zoukankan      html  css  js  c++  java
  • 常用的SQL语句<三> 联合查询和高级用法

    1、子查询(表A:table1(a,b,c)  表B:table2(c,d,e) )
    select a,b,c from table1 where a IN (select d from table2 ) 
    

    2、外连接查询

    select table1.a, table1.b, table1.c, table2.c, table2.d, table2.e from table1 LEFT OUT JOIN table2 ON table1.c = table2.c
    --或者
    select A.a, A.b, A.c, B.c, B.d, B.e from table1 as A LEFT OUT JOIN table2 as B ON A.c = B.c

    3、between的用法,between限制查询数据范围时包括了边界值,not between不包括

    select * from table1 where time between time1 and time2
    select a,b,c, from table1 where a not between 数值1 and 数值2

    4、in 的使用方法

    select * from table1 where a [not] in ('值1','值2','值4','值6')

    5、两张关联表,删除主表中已经在副表中没有的信息

    delete from table1 where not exists ( select * from table2 where table1.c=table2.c)

    6、多表联查问题:

    select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....

    7、数据库分页

    select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

    8、前十条记录

    select top 10 * form table1 where 范围

    9、选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等。)

    select a,b,c from table1 ta where a=(select max(d) from table2 tb where tb.c=ta.c)

    10、包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表

    (select a from tableA ) except (select a from tableB) except (select a from tableC)

    11、随机取出10条数据

    select top 10 * from tablename order by newid()
    --随机选择记录
    select newid()

    12、删除重复记录

    Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)

    13、列出数据库里所有的表名

    select name from sysobjects where type='U'

    14、列出表里的所有的

    select name from syscolumns where id=object_id('TableName')

    15、列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case

    select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type
    --显示结果:
    --type vender pcs电脑 A 1电脑 A 1光盘 B 2光盘 A 2手机 B 3手机 C 3

    16、初始化表table1

    TRUNCATE TABLE table1

    17、选择从10到15的记录

    select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
  • 相关阅读:
    NGINX_深度优化实践
    NFS服务端___NFS客户端
    NFS 批量管理 分发
    MYSQL---数据备份与还原
    MYSQL---建立字符集数据库
    MYSQL---基于mysql多实例数据库创建主从复制
    MYSQL---关于MYSQL优化
    bug记录-left jion连接后不是一对一情况时,记得去重
    bug记录-不等于某个值,查询后注意不包括为空的情况(由于NULL不能直接用算术运算符进行比较值。要想把为NULL 的那行也查询出来的话,只能使用IS NULL)
    bug记录-sqljion连接 like
  • 原文地址:https://www.cnblogs.com/bindot/p/select.html
Copyright © 2011-2022 走看看