数据库

SQL语句的使用

2021-05-25  本文已影响0人  過尽千帆_YL

1. select语句

通过 * 把 users 表中所有的数据查询出来
select * from users
从 users 表中把 username 和 password 对应的数据查询出来
select username, password from users

2. INSERT INTO语句

向 users 表中,插入新数据,username 的值为 tony stark password 的值为 098123
insert into users (username, password) values ('super_idol', '098123')

3. UPDATE 语句

将 id 为 4 的用户密码,更新成 888888
update users set password='888888' where id=4
更新 id 为 2 的用户,把用户密码更新为 admin123 同时,把用户的状态更新为 1
update users set password='admin123', status=1 where id=2

4.DELETE 删除语句

删除 users 表中, id 为 4 的用户
delete from users where id=4

5. 演示 where 子句的使用

select * from users where status=1  // 查询表中状态为1的用户
select * from users where id>=2 // 查询表中id大于等于2的用户
select * from users where username<>'ls' // 查询表中不等于'ls'的用户
select * from users where username!='ls' // 查询表中不等于'ls'的用户

6. AND 和 OR 运算符

使用 AND 来显示所有状态为0且id小于3的用户
select * from users where status=0 and id<3
使用 or 来显示所有状态为1 或 username 为 zs 的用户
select * from users where status=1 or username='zs'

7. ORDER BY 排序语句

对users表中的数据,按照 status 字段进行升序排序
select * from users order by status
按照 id 对结果进行降序的排序 desc 表示降序排序 asc 表示升序排序(默认情况下,就是升序排序的)
select * from users order by id desc
对 users 表中的数据,先按照 status 进行降序排序,再按照 username 字母的顺序,进行升序的排序
select * from users order by status desc, username asc

8. COUNT(*) 函数

使用 count(*) 来统计 users 表中,状态为 0 用户的总数量
select count(*) from users where status=0
使用 AS 关键字给列起别名
select count(*) as total from users where status=0
select username as uname, password as upwd from users

9. 分页查询 LIMIT()

分页查询公式:(currentPage - 1) * pagesize

-- ( 当前页 - 1 ) * 每页显示条数

-- (1-1) * 2 =0
-- (2-1) * 2 =2
-- (3-1) * 2 =4
LIMIT 参数1,参数2  参数1=从哪开始取值  参数2=你要取几个
select * from ev_users limit 4,2

10. 多表查询 左连接

SELECT art.`Id`,art.`title`,art.`pub_date`,art.`state`,cate.`name` 
FROM ev_articles art LEFT JOIN ev_article_cate cate
ON art.`cate_id` = cate.`Id` LIMIT 2,2
上一篇下一篇

猜你喜欢

热点阅读