等值连接:
– select * from 表1,表2 where 表1.列=表2.列
– select * from students,scores where students.studentNo=scores.studentNo
内连接:
– select * from 表1
– inner join 表2 on 表1.列=表2.列
– select * from students
– inner join scores on students.studentNo=scores.studentno
左连接:
– 取左边表的所有数据
右连接:
– 取右边表的所有数据
自关联查询:
– 适用于有上下级关系的表
– 一个表可以查多次,但是必须给表起别名
– select * from areas as sheng,areas as shi
– where sheng.aid=shi.pid and sheng.atitle=‘河南省’
子查询:
标量子查询:子查询返回的结果是一行一列(用等号)
– select * from scores where studentNo=(
– select studentNo from students where name=‘王昭君’
– ) and courseNo=(select courseNo from courses where name=‘数据库’)
– 等号后面返回的结果是一行一列,否则会报错
– 即查询:
– select * from scores where studentno=‘王昭君的学号’
– and courseNo=‘数据库的课程号’
列子查询:列子查询返回的结果是一列多行(用in)
– select score from scores where studentno in (select studentno from students where age=‘18’)
行子查询:子查询返回的结果是一行多列,注意:子查询只能返回一行
– select * from students where (sex,age)=(select sex,age from students where sex=‘男’ order by age desc limit 1)
表子查询:子查询返回的结果是一个表,多行多列,作为表使用
from、inner join、left join、right jion后面跟的是数据源(数据源:可以是一个真正的表也可以是查询出来的结果)
当数据源是查询出来的结果时一定要给这个结果起别名
– select * from scores
– inner join
– (select * from courses where name in (‘数据库’,‘系统测试’)) as jieguo
– on scores.courseNo=jieguo.courseNo
子查询中特定关键字使用:
in 范围
格式: 主查询 where 条件 in (列子查询)
any | some 任意一个
格式: 主查询 where 列 = any (列子查询)
在条件查询的结果中匹配任意一个即可,等价于 in
all
格式: 主查询 where 列 = all(列子查询) : 等于里面所有
格式: 主查询 where 列 <>all(列子查询) : 不等一其中所有
– select * from students where age in (select age from students where age between 18 and 20)
– select * from students where age=any(select age from students where age between 18 and 20)
– select * from students where age=some(select age from students where age between 18 and 20)
– in =any =some这三者等价,其中=可以换成> < >= <= !=(!=any没有意义,=all没有意义)
把查询出来的数据插入到另一个表中:
– insert into goods_cates(cate_name) select distinct cate from goods
创建表并插入数据:create table … select …
– create table goods_brands (
– id int unsigned primary key auto_increment,
– brand_name varchar(40)
– )
– select distinct brand_name from goods
备份表:
– create table goods_back select * from goods
select后面查询出的字段与create中的字段相同,就会将select中的列创建在create的表中,
如果create的表中没有select中的字段,创建出的表会增加一列,增加的一列即为select中的列
将某个表中的某一列更新为另一个表中的一列:
先
select * from goods
inner join goods_cates on goods.cate=goods_cates.cate_name
然后改为:
update goods
inner join goods_cates on goods.cate=goods_cates.cate_name
set goods.cate=goods_cates.id