mysql基本语法
程序员文章站
2022-05-17 08:53:43
...
Create Table
表结构:
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
``一 去重
SELECT DISTINCT NAME FROM student;
二 、 +号的作用 +号是一个运算符(两个字段的和)
SELECT id+age AS student_sum FROM student
三 concat
SELECT CONCAT(sname , address) AS message FROM student;
条件查询
查询年纪大于2岁的
SELECT age FROM student WHERE age>2;
查询年纪小于2岁的
SELECT age FROM student WHERE age<2;
查询年纪不等于2岁的
SELECT age FROM student WHERE age<>2;
第二种写法:
SELECT age FROM student WHERE age !=2;
查询年纪大于等于3岁的
SELECT age FROM student WHERE age >=3;
查询年纪大于3 并且id大于2(mysql推荐使用and)
SELECT * FROM student WHERE age >3&&id>2;
查询年纪大于3或者id>2 (mysql推荐使用or)
SELECT * FROM student WHERE age >3||id>2;
! 或者是not的用法
SELECT * FROM student WHERE NOT(id>3)
模糊查询
包含张的用户 %表示任意多个字符
SELECT * FROM student WHERE sname LIKE '%张%' ;
下划线——表示任何单个字符
举个栗子
查询第一个字符是a,第三个字符是g的用户
SELECT * FROM student WHERE sname LIKE '_s__g%'
注意 如果要查询名字中有_的用户,这里的_需要转义才能查询到
```sql
SELECT * FROM student WHERE sname LIKE '_\_%'
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200416161655801.png)
如果不适用\转义 也可以适用capase指定转义字符
```sql
SELECT * FROM student WHERE sname LIKE '%$_%' ESCAPE '$'
如果不适用\转义 也可以适用escape指定转义字符
```sql
SELECT * FROM student WHERE sname LIKE '%$_%' ESCAPE '$'
在什么什么之间 between and
```sql
SELECT * FROM student WHERE age BETWEEN 1 AND 4
In 的用法
SELECT * FROM student WHERE age IN(1,2,3,5)
查询没有地址的用户
、
SELECT * FROM student WHERE address IS NULL
类似的 如果查询不为Null的
SELECT * FROM student WHERE address IS NOT NULL
了解 安全等于
SELECT * FROM student WHERE address <=> NULL
is null 只能判断null值
而安全等于不仅可以判断null 值 也可以判断普通的值
= 是不能判断null值的
排序查询:
升序
SELECT * FROM student ORDER BY id ASC
降序
SELECT * FROM student ORDER BY id DESC
查询用户的年薪
SELECT
id,
sname,
salary*12*(1+IFNULL(salary,0)) AS '年薪'
FROM student
ORDER BY id ASC
查找字段的长度
SELECT LENGTH(sname) FROM student
按照字段的长度排序
SELECT *, LENGTH(sname) AS 长度 FROM student
ORDER BY LENGTH(sname) ASC
上一篇: sql server中datetime字段去除时间代码收藏
下一篇: mysql 字符函数