`

SQL语句总结

    博客分类:
  • SQL
 
阅读更多

    Hibernate用多了,SQL语句反而有点忘记。昨天去面试,有点被刺痛。select语句基本没问题。但被delete与update难住了。平时开发的时候,delete,update语句用的很少。用到的时候再去网上查格式。所以连基本的delete与update语句的格式都忘记了。考题基本都是网上抄的,华而不实,实际编程中没啥用的。但不管如何,要吸取这次教训。下次去哪里面试都要先把SQL语句看一遍。

    还有对于SQL语句公式的记忆,不要去记忆英文。因为英文比较长,比较长。关键的地方还是用中文。

 

 

一、insert语句

insert into 表名 (列1, 列2,...) values (值1, 值2,....)

--或:
insert into 表名values (值1, 值2,....)

 

 

二、update语句

update 表名 set 列名 = 新值 where 列名 = 值

 

 

三、delete语句

delete from 表名 where 列名 = 值

--或
delete * from 表名

  

 

 

四、select语句

参看:http://shijiaqi1066.iteye.com/admin/blogs/1452791

 

 

五、表连接

表连接的分类:

    1.1左(外)连接 left join .. on ..   left out join .. on ..
  1.外连接

1.2右(外)连接

right join .. on .. right out join .. on ..
    1.3完整(外)连接 full join .. on ..

   full out join .. on ..

表连接 2.内连接         join .. on ..       inner join .. on ..
  3.交叉连接   cross join  

 

 

例表:

table1

id

name

1

lee

2

zhang

4

wang

 

table2

id

score

1

90

2

100

3

70

 

 

左连接:left join 或 left outer join 

(1) 左向外联接的结果集包括 LEFT OUTER 子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。

如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值(null)。

(2) 例:

select * from table1 left join table2 on table1.id=table2.id

 

结果集:包含table1的所有子句,根据指定条件返回table2相应的字段,不符合的以null显示。

id

name

id

score

1

lee

1

90

2

zhang

2

100

4

wang

null

null

 

 

右连接:right join 或 right outer join

 (1) 右向外联接是左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。 

 (2) 例:

select * from table1 right join table2 on table1.id=table2.id 

 

结果集:包含table2的所有子句,根据指定条件返回table1相应的字段,不符合的以null显示 

id

name

id

score

1

lee

1

90

2

zhang

2

100

null

null

3

70

 

 

完整外部联接:full join 或 full outer join

 (1)完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。 

 (2)例:

select * from table1 full join table2 on table1.id=table2.id 

 

结果集:返回左连接结果集与右连接结果集的并集。

id

name

id

score

1

lee

1

90

2

zhang

2

100

4

wang

null

null

null

null

3

70

 

 

 

内连接 join 或 inner join 

1.概念:内联接是用比较运算符比较要联接列的值的联接 

2.例:

select * from table1 join table2 on table1.id=table2.id

--等价于:
select a.*,b.* from table1 a,table2 b where a.id=b.id 
select * from table1 cross join table2 where table1.id=table2.id
--(注:cross join后加条件只能用where,不能用on) 

 

结果集:只返回符合条件的table1和table2的列 。说明,连接的符号也可以使用其他比较运算符。

id

name

id

score

1

lee

1

90

2

zhang

2

100

 

 

 

交叉连接(笛卡尔积) cross join    说明:cross join 无on子句。

1.概念:没有 WHERE 子句的交叉联接将产生联接所涉及的表的笛卡尔积。

2.例:

select * from table1 cross join table2

--等价于:
select * from table1,table2 

 

 结果集:table1和table2交叉连接产生3*3=9条记录

id

name

id

score

1

lee

1

90

2

zhang

2

90

4

wang

3

90

1

lee

1

100

2

zhang

2

100

4

wang

3

100

1

lee

1

70

2

zhang

2

70

3

wang

3

70

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics