1.创建(删除)数据库---create(drop)
CREATE [IF NOT EXISTS]DATABASE mydatabase
CHARACTER SET utf8mb4//字符集(utf-8)
COLLATE utf8mb4_general_ci;//排序规则
2.数据类型
(1)数值类型
(2)时间类型
(3)字符串类型
3.创建表(删除drop)
CREATE TABLE table_name (//表名
column1 datatype,//cloumn是列的名字
column2 datatype,//datatype是每个列的数据类型
...
);
//实例
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
birthdate DATE,
is_active BOOLEAN DEFAULT TRUE
);
4.插入数据
INSERT INTO users (username, email, birthdate, is_active)
VALUES ('test', 'test@runoob.com', '1990-01-01', true);
//因为是所有列的数据,上面的(username, email, birthdate, is_active)可以省略
INSERT INTO users
VALUES (NULL,'test', 'test@runoob.com', '1990-01-01', true);
//这里,NULL 是用于自增长列的占位符,表示系统将为 id 列生成一个唯一的值。
//多行插入
INSERT INTO users (username, email, birthdate, is_active)
VALUES
('test1', 'test1@runoob.com', '1985-07-10', true),
('test2', 'test2@runoob.com', '1988-11-25', false),
('test3', 'test3@runoob.com', '1993-05-03', true);
第一列如果没有设置主键自增(PRINARY KEY AUTO_INCREMENT)的话添加第一列数据比较容易错乱,要不断的查询表看数据。
如果添加过主键自增(PRINARY KEY AUTO_INCREMENT)第一列在增加数据的时候,可以写为0或者null,这样添加数据可以自增, 从而可以添加全部数据,而不用特意规定那几列添加数据。
5.查询
-- 选择所有列的所有行
SELECT * FROM users;
-- 选择特定列的所有行
SELECT username, email FROM users;
-- 添加 WHERE 子句,选择满足条件的行
SELECT * FROM users WHERE is_active = TRUE;
-- 添加 ORDER BY 子句,按照某列的升序排序
SELECT * FROM users ORDER BY birthdate;
-- 添加 ORDER BY 子句,按照某列的降序排序
SELECT * FROM users ORDER BY birthdate DESC;
-- 添加 LIMIT 子句,限制返回的行数
SELECT * FROM users LIMIT 10;
升级语句(使用and,or,in)
-- 使用 AND 运算符和通配符
SELECT * FROM users WHERE username LIKE 'j%' AND is_active = TRUE;
-- 使用 OR 运算符
SELECT * FROM users WHERE is_active = TRUE OR birthdate < '1990-01-01';
-- 使用 IN 子句
SELECT * FROM users WHERE birthdate IN ('1990-01-01', '1992-03-15', '1993-05-03');
6.牛客
(1)去重 distinct
select distinct university from user_profile
(2)前几个 limt
select device_id from user_profile limit 2;
(3)将查询后的列重新命名 as
select device_id as user_infos_example from user_profile limit 2
(4)年龄在a,b区间 between and
select device_id,gender,age from user_profile where age between 20 and 23
(5)除了。。。 where age not in。。。
select device_id,gender ,age,university from user_profile where university not in ('复旦大学')
(6)年龄不为空的数据(过滤空值) age is not null
select device_id,gender ,age,university from user_profile where age is not null
(7)且(and)或(or)
select device_id,gender,age,university,gpa from user_profile where gender = 'male' and gpa > 3.5
//or在存在索引的情况下,会失效,这个时候要使用union
select device_id,gender,age,university,gpa from user_profile where univergity='北京大学' or gpa >3.7
//使用union的情况
SELECT `device_id`,`gender`,`age`,`university`,`gpa` FROM `user_profile` WHERE `university` = '北京大学'
UNION
SELECT `device_id`,`gender`,`age`,`university`,`gpa` FROM `user_profile` WHERE `gpa`>3.7