MySQL知识

298 阅读2分钟

1、左链接

select * from 表1 left join 表2 on 条件

2、查找重复值

select 字段名 from 表名 group by  字段名 having count(*)>0

3、查询第二高的薪水

select distinct 字段名 from 表名 order by 字段名 desc limit 1,1

4、自定义函数的使用     查询第n高的薪水

     需要定义参数n set n=n-1; 因为数组是以0开始的

      把 sql语句复制到return 后面 改变参数就行

return(select distinct 字段名 from 表名 order by 字段名 desc limit n,1)

5、查看表中创建日期为2019-09-07的数据

select * from 表名 where DATEDIFF(字段名,'2019-09-07')=0    
DATEDIFF()函数是比较两个数的差 前减后

//第二种更精确
select  *  from  表名 where 字段名 between '2019-09-07 00:00:00' and '2019-09-07 23:59:59';
必须带时分秒

6、把数据库中数字改变成中文

select id, case 字段名 when '1' then '中文'  else '未知' end from 表名

7、if的使用

select q.* if(q.type=1,(select u.username from  user u where q.createuser=u.id),
(select a.adminname from  admin a where q.createuser=a.id)) as nickname from quotation q

8、优先按照类型排序然后按照时间排序

1   select *  from type order by case when type='管理员' then 1 else 2 end , createtime desc
2   select *  from test ORDER BY type desc ,createtime desc

9、排名问题如果相同就同一排名

select score,(select count(distinct score)from scores where scord>=s.score)as rank from  
scores s order by score desc

MySQL在xml文件中比较运算符转义

三、DQL(Data Query Language)数据查询语言

1、语句顺序

* 书写顺序:SEKECT、DISTINCT、FROM、JOIN ON、WHERE、GROUP BY、HAVING、ORDER BY、LIMIT

* 执行顺序:FROM、JOIN ON、WHRER、GROUP BY、HAVING、SELECT、DISTINCT、ORDER BY、LIMIT

2、基础查询

(1)去重(DISTINCT)

select distinct name from test_tables    ##查询结果去重

(2)查询函数

         LENGTH(str)返回字符串长度

select length('hello'); #返回结果就是5

https://blog.csdn.net/qq_37969433/article/details/102637226