SQL之单表与多表查询

DML语句使用

source  路径  :把SQL脚本导入到数据库中

查询语句类型:【简单查询|多表查询|子查询

投影:select    字段名,字段名   from   表名   where   条件   :作对比

选择:select    *  from   表名    where   条件   :选择显示莫一行

单表查询

在一个表中,某个字段中相同的数值只显示一次!

select  distinct  字段名   from  表名;

 

from子句 :表,多个表,其他查询语句(select

where子句:布尔关系表达式,操作符(<,>,>=,<=,=

 

组合条件查询

符号:   %:任意长度任意字符

         _:任意单个字符

 rlike/regexp:使用正则表达式

         in :离散取值

order  by  字段 (asc升序/desc降序):给查询出来的数据排序,(默认为升序)

and :和

or :或

not :非

between。。。and。。。:。。。与。。。。之间

 

select   cid  from  xuehao  where      not   cid >2;

                          关键字          条件

select   cid  from  xuehao  where     not    cid >2      and   id=1;

                          关键字         条件           条件

select   cid  from  xuehao  where    cid >2    or    id=1;

                          关键字    条件   或者   条件

select   cid  from  xuehao  where     not   cid > 2   and   not    id =1;

                          关键字         条件            条件

select   cid  from  xuehao  where     not  (cid > 2  or  id =1);

                          关键字     非     条件1或条件2

select   cid  from  xuehao  where     cid    between  2  and  6;

                          关键字     cid在26之间(between:。。。与。。。之间

select keming from    kehao  where    keming   like          'y%'

                            关键字  字段名   关键字    以y开头的字符

select keming from    kehao  where     keming   like         'k_ _ _';

                                                         以K开头后面有3个字符

select keming from    kehao   where    keming    like         '%k%';

                                                         字符中包含了k的字符串

select keming from    kehao   where     keming   rlike            '^[ky].*$' ;

                                           使用正则表达式     开头是k或y

select   cid   from    kehao  where      cid       in         (1,2,5);

                                    筛选出一个表中id的值为1,2,5

select    *    from    xuehao     order   by  cid

                                  排序   根据cid

别名:select  a.Name , b.Cname      from   students  as  a,courses  as  b  where  a.CID1=b.CID;

         字段别名为a   字段别名为b           表别名为a      表别名是b   条件   表aCID1=bCID

多表查询

连接方式

   交叉连接:笛卡尔乘积

   自然连接:将两张表上相同字段当中的的那个值逐一作比较,只将等值关系将它保留下来

    外连接:

           左外连接:左表  left  join  右表  on  条件

           右外连接:左表  right  join 右表  on  条件

select s.Name,c.Cname  from  students   as    lef t join  courses  as     on     s.CID1=c.CID;

                             左表  别名   s   左外连接 右表  别名    c  连接条件 

select s.Name,c.Cname  from  students   as    s   right join  courses  as  c  on  s.CID1=c.CID;

                             左表  别名   s   右外连接   右表  别名 c 连接条件

     子连接

          比较操作中使用子查询,子查询只能返回单个值

          in ():使用子查询

联合查询

union

  

(select Name,Age from  students) union  (select Tname,Age from  tutors);

posted @ 2019-08-02 17:35  え稚始گ  阅读(373)  评论(0编辑  收藏  举报