产品经理学SQL

预备知识

  1. 数据库(DB)与数据库管理系统(DBMS)

数据库:由一张张表构成。现在使用的数据库大多数是关系型数据库,是建立在关系模型上的数据库。
数据库管理系统:是在计算机中对数据库进行定义、描述、建立、管理和维护的系统软件。mysql,oracle都属于数据库管理系统。

  1. SQL语言构成
  • 数据定义语言(DDL):对数据库对象进行操作(数据库、表、视图、索引)
  • 数据操作语言(DML):对表内进行操作(增删改)
  • 数据查询语言(DQL):对单表或多表中数据进行查询
  • 数据控制语言(DCL):设置数据库用户权限(GRANT\DENY\REVOKE等)
  1. 安装mysql
    下载地址
    下载及安装教程

基本查询语法

select 列名,(查看所有列,则select *);
from 表名
where 限制条件
Group by 按列名进行分组统计;
eg: select * from city group by district
(按地区分组查看城市列表)
Having 列名——对分组统计的结果进行限制;
Order by 列名,默认升序,desc是降序,ASC升序;
distinct去重
eg:select distinct * from city;

group by 跟着汇总函数一起使用,
汇总函数:max() 统计最大,min() 统计最小,count() count(distinct)计数; avg(),计算平均数; sum() 汇总。

例 计算各个城市代码(countyrcode)的人口总数;
select CountryCode,sum(Population) from city group by countrycode;

select * from city where CountryCode="AFG";
注意:where 列名=“值”,要有双影号。

where过滤:between and,or , in , not in, not null , null

例 查看不同CountryCode的城市数量;


image.png

select CountryCode,count(ID) from city group by CountryCode;

like 模糊查询
查找以A开头的countrycode的所有记录。
select * from city where CountryCode like "A%" ;

例:查看以A开头的城市代码的城市平均人口
select CountryCode,avg(Population) from city where CountryCode like "A%" group by CountryCode;

创建 删除

create/drop database 数据库名;
create table 表名(列名 类型,...)

使用某个数据库: use 数据库名;

查看表结构:desc 表名;

增删改(DDL):alter table;

  • 增加一列:alter table 表名 ADD 列名 数据类型
  • 删除一列:alter table 表名 drop column 列名
  • 修改列名:alter table 表名 change 旧字段 新字段名 新列数据类型
  • 修改表名:alter table 旧表名 rename 新表名
  • 设置主键:Alter table 表名 Add Primary Key(列名);

(DML)表内数据操作语言

  1. 插入
    insert into 表名 values(xx,xx,xx)
  2. 更新
    update 表名 set 列名= 新值 where 列名= 值;
  3. 删除表中记录
    delete from 表名(where 列名=值);

今后将在实践中持续更新。

你可能感兴趣的:(产品经理学SQL)