create table students(
id int auto_increment primary key,
name varchar(10) not null,
sex varchar(3) default '女',
address varchar(50),
phone int not null unique,
age,
);
select * from students limit 1,5; #从第几条开始,下面的x条,不包含开始的那一条
SELECT * from students limit 5;查询5条
SELECT id,stu_name,sex,money,phone from students;#指定查询的字段
SELECT * from students;#查询所有的数据
SELECT * from students where sex='男';#指定条件
SELECT * from students where sex='男' and money>100; #多个条件,必须同时满足
SELECT * from students where sex='男' or sex='未知' ; #多个条件,有一个满足即可
SELECT * from students where sex !='男'; #<>也是不等于
SELECT * FROM students where addr like '%东京%';#模糊匹配,%代表的是通配符,必须得用like
SELECT * from students a where a.stu_name like '姚_';#_通配符表示任意一个单字符,姚字后面只能跟一个字
SELECT a.stu_name '学生名称',a.phone '学生电话' from students as a where a.stu_name='姚远';#给表起别名,as可以省略
SELECT * from students a where a.stu_name in ('牛牛','林倩','林远');# in
SELECT * from students a where a.money BETWEEN 1000 and 10000;#在什么什么之间的数据
SELECT * from students ORDER BY money desc;
#order by xxx desc,根据哪个字段继续排序,默认是升序,
降序是desc,升序asc
SELECT * from students a where a.addr = '' or a.addr is null; #查询字段为空的数据
SELECT DISTINCT a.money from students a ;#去重
SELECT COUNT(*) '学生人数' from students where sex='女'; #统计行数
SELECT MAX(a.money) 钱最多 from students a; #最大值
SELECT min(money) 钱最少 from students;#最小值
SELECT AVG(a.money) 平均多少钱 from students a; #平均数
SELECT sum(a.money) 总共多少钱 from students a;#总和
SELECT sex 性别,count(*) 人数 from students GROUP BY sex; #分组
复制代码代码如下:
复制代码代码如下:
即:让WHERE条件不成立.
复制代码代码如下:
CREATE TABLE 新表
LIKE 旧表
复制代码代码如下:
复制代码代码如下:
表一:t_book
表二:t_bookType
表三:t_priceLevel
select * from t_book,t_bookType;
1.内连接查询(两张或以上的表连接起来查询需要的数据)
根据表一的bookTypeId查询出所有bookTypeName
select * from t_book,t_bookType where t_book.bookTypeId=t_bookType.id;
查询某几个字段:
select bookNme,author from t_book,t_bookType where t_book.bookTypeId=t_bookType.id;
2.外连接查询(两张或以上的表连接起来查询某张表的信息)
3.左连接查询
select * from t_book left join t_bookType on t_book.bookTypeId=t_bookType.id;
如下图:表一(左边表)t_book的数据全部查出 表二没有的字段用null代替
4.右连接查询
select * from t_book right join t_bookType on t_book.bookTypeId=t_bookType.id;
查出表二(右边表)的所有信息,表一没有的用null代替
5.多条件连接查询
select * from t_book,t_bookType where t_book.bookTypeId=t_bookType.id and t_book.price>70;
select * from t_book where bookType in(select id from t_bookType);
select * from t_book where bookType not in(select id from t_bookType);
select * from t_book where price>=(select price from t_priceLevel where priceLevel=1);
select * from t_book where exists(select * from t_booktype);
select * from t_book where not exists(select * from t_booktype);
select * from t_book where price>= any(select price from t_priceLevel);
select * from t_book where price>= all(select price from t_priceLevel);
使用union关键字是,数据库系统会将所有的查询结果合并到一起,然后去掉相同的记录;
select id from t_book union select id from t_bookType;
使用union all,不会去除掉重复的记录;
select id from t_book union all select id from t_bookType;