SQL数据库基本知识2



1.top子句

top子句用于规定要返回的记录的数目。

对于拥有数千条记录的大型表来说,TOP 子句是非常有用的。

注释:并非所有的数据库系统都支持 TOP 子句。

<1>table表中选取头两条记录。

Select  top 2* from table;======select top 50 percent * from table;

2.like操作符

like 操作符用于在 WHERE 子句中搜索列中的指定模式。

"%" 可用于定义通配符(模式中缺少的字母)。

Select * from table where username like w%; 在表中选取以w开头的人

Select * from table where username like %k;在表中选取以k结尾的人

    Select * from table where city like %bei%;在表中选取居住包含bei”的城市的人

通过使用 NOT 关键字,在表中选取居住包含bei”的城市的人

Select * from table where city  not like %bei%;

  1. _通配符

    我们希望从上面的 table 表中选取名字的第一个字符之后是 eijing的人:

    Select * from table where city like _eijing; Select * from table where city like _eij_ng;

  2. [charlist] 通配符

我们希望从上面的table表中选取居住的城市以 "b" "l" "n" 开头的人:Select * from table where city like =[bln]%;

我们希望从上面的table表中选取居住的城市 "b" "l" "n" 开头的人:Select * from table where city like =[!bln]%;

  1. in操作符

In操作符允许我们在where子句中规定多个值。

Select *

from table

where username in(tom,wk);

6.between 操作符

操作符 between...and.. 会选取介于两个值之间的数据范围。这些值可以是数值、文本或者日期。

重要事项:不同的数据库对 between...and 操作符的处理方式是有差异的。某些数据库会列出介于 "tom" "wk" 之间的人,但不包括 "tom" "wk" ;某些数据库会列出介于 "tom" "wk" 之间并包括 "tom" "wk" 的人;而另一些数据库会列出介于 "tom" "wk" 之间的人,包括 "tom" ,但不包括 "wk"

Select *

from table

where username betweentomandwk; 不包括wk

Select *

from table

where username  not betweentomandwk; 包括wk

  1. 通过使用 sql,可以为列名称和表名称指定别名(Alias)。

    假设我们有两个表分别是:"Persons" "Product_Orders"。我们分别为它们指定别名 "p" "po"

    现在,我们希望列出 "tom" 的所有定单。

    Select po.orderid,p.age,p.sex

    From person as p,product_orders as po

    Where p.age=19 and p.sex=

    把列名别名修改

    Select username as name,password as pwd

    From table

    8.有时为了得到完整的结果,我们需要从两个或更多的表中获取结果。我们就需要执行 join

    数据库中的表可通过键将彼此联系起来。主键(Primary Key)是一个列,在这个列中的每一行的值都是唯一的。在表中,每个主键的值都是唯一的。这样做的目的是在不重复每个表中的所有数据的情况下,把表间的数据交叉捆绑在一起。

    <1>举例说明:table1table2,引用两个表

    Select table1.name,table1.age,table2.tel

    From table1,table2

    Where table1.id_p=table2.id_p

    用两个id连接起两个表。

    <2>使用关键词join

    Select table1.name,table1.age,table2.tel

    From table1

    Inner join table2

    On table1.id_p=table2.id_p

    Order by table1.name

    下面列出了您可以使用的 join 类型,以及它们之间的差异。

  • join: 如果表中有至少一个匹配,则返回行

  • Left join: 即使右表中没有匹配,也从左表返回所有的行

  • Right join: 即使左表中没有匹配,也从右表返回所有的行

  • Full join: 只要其中一个表中存在匹配,就返回行

Inner join join用法相同。

9.union union all操作符

Union操作符用于合并两个或多个select语句的结果集。

请注意,union 内部的 select语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 select 语句中的列的顺序必须相同。

<1.>union命令只会选取不同的值

<2.>union all 可以重复

Select E_name from E_china

Union

Select E_name from E_usa

10.select into 语句可用于创建表的备份复件。

从一个表中选取数据,然后把数据插入另一个表中。

常用于创建表的备份复件或者用于对记录进行存档。

Select *(或者只是其中的一列)

  into new_table[in externaldatabase]  from old_table

In子句可用于向另一个数据库中拷贝表:

Select * into table in database.mdb from table;

猜你喜欢

转载自blog.csdn.net/qq_41915456/article/details/80015602