MySQL语句技巧
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL语句技巧相关的知识,希望对你有一定的参考价值。
1、查询时将时间戳格式化显示:
SELECT FROM_UNIXTIME(1234567890, ‘%Y-%m-%d %H:%i:%S‘) FROM table_name
2、最高效的删除重复记录方法 ( 因为使用了ROWID)例子:
DELETE FROM EMP E WHERE E.ROWID > (SELECT MIN(X.ROWID) FROM EMP X WHERE X.EMP_NO = E.EMP_NO);
3、查询一段时间内,每5分钟间隔在线分时数据统计(eventtime是时间戳)
SELECT FROM_UNIXTIME(`eventtime`-`eventtime`% (5*60), ‘%Y-%m-%d %H:%i:%S‘) AS stime, count(distinct uid) uids
FROM 20170828_online WHERE eventtime>=1503921000 AND eventtime<=1503925200
GROUP BY stime;
4、将两个表的查询结果合并成一行
select A.newusers,B.pay from (SELECT COUNT(DISTINCT uid) AS newusers FROM applogs.20171025_firstentry WHERE game=12 AND client=1) AS A,
(SELECT SUM(money)/100 AS pay FROM applogs.20171025_paylog WHERE eventdate=flogindate AND game=12 AND client=1 ) AS B;
5、列转行技巧
eg:统计id为1的记录数,id为2的记录数以及id为3的记录数。
SELECT COUNT(CASE WHEN id=1 THEN 1 ELSE NULL END ) AS `one_num`,COUNT(CASE WHEN id=2 THEN 1 ELSE NULL END ) AS `two_num`,COUNT(CASE WHEN id=3 THEN 1 ELSE NULL END ) AS `tree_num` FROM test;
表数据:
执行该语句的结果:
6、group_concat函数的使用方法
公式:group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator ‘分隔符‘])
基础表格:(以5中的表格数据为例)
(1)以id分组,把name字段的值放在同一结果行,以逗号分隔(默认)
SELECT id,GROUP_CONCAT(NAME) AS id_name FROM test GROUP BY id;
结果:
(2)以id分组,把name字段的值放在同一结果行,以分号分隔
SELECT id,GROUP_CONCAT(NAME SEPARATOR ‘;‘) AS id_name FROM test GROUP BY id;
结果:
(3)以id分组,把去冗余的name字段的值放在同一结果行, 以逗号分隔
SELECT id,GROUP_CONCAT(DISTINCT `name`) AS id_name FROM test GROUP BY id;
结果:
(4)以id分组,把name字段的值放在同一结果行,逗号分隔,以name排倒序
SELECT id,GROUP_CONCAT(`name` ORDER BY `name` DESC) AS id_name FROM test GROUP BY id;
结果:
7、插入数据出现UNIQUE索引或PRIMARY KEY冲突时就使用更新(ON DUPLICATE KEY UPDATE 语法)
(1) INSERT INTO `sy`.`day` (id, name, phone) VALUES(‘666‘, ‘xst‘, ‘10086‘) ON DUPLICATE KEY UPDATE name = VALUES(name),phone = VALUES(phone);
(2) INSERT INTO TABLE (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1; (UPDATE TABLE SET c=c+1 WHERE a=1;)
(3) INSERT INTO TABLE (a,b,c) VALUES (1,2,3),(2,5,7),(3,3,6),(4,8,2) ON DUPLICATE KEY UPDATE b=VALUES(b);
以上是关于MySQL语句技巧的主要内容,如果未能解决你的问题,请参考以下文章