首页 > 代码库 > MySQL实用技巧
MySQL实用技巧
自增Id重新计数 TRUNCATE TABLE 表名
获取最后插入数据的ID SELECT LAST_INSERT_ID();
使用"id1,id2,id3"当参数 FIND_IN_SET(id,"id1,id2,id3,")
返回受影响行数 FOUND_ROWS() : select
ROW_COUNT() : update delete insert.
大小写敏感 在查询敏感字段前加 BINARY
查询结果去重 DISTINCT
模糊查询 Like CONCAT(‘%‘,keyword,‘%‘)
随机查询数据 ORDER BY rand() LIMIT 5
查询上一个
SELECT MAX(id) INTO count FROM sys_notepad WHERE id<_id;
SELECT * FROM sys_notepad WHERE id=count;
查询下一个
SELECT * FROM sys_notepad WHERE id>_id LIMIT 1;
从别的表查询数据|给定值 插入到当前表
INSERT INTO <TableName> (collection1,collection2,addTime) (SELECT value,collection2,NOW() FROM 表 WHERE id=_id );
定义变量 DECLARE 变量名 类型 DEFAULT 默认值;
日期计算
返回天数 SELECT DATEDIFF(‘2015-01-01 19:00:00‘,‘1991-01-01 00:00:00‘);
返回秒数 SELECT UNIX_TIMESTAMP(‘2015-01-01 19:00:01‘)-UNIX_TIMESTAMP(‘1991-01-01 00:00:00‘)
复制表结构
1。获取语句
SHOW CREATE TABLE 表名
2。C#取语句
MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
GetSQL = reader[1].ToString().Replace("\n", "");
}
慢:WHERE name like "MySQL%"
快:WHERE name>="MySQL"and name<"MySQM"
慢:WHERE Amount/7<24;
快:WHERE Amount<24*7;
//分组排序
select *,ROW_NUMBER() over(partition by convert(varchar(10),SessionTime, 120) order by ID) as new_index from WC_MessageRelation
//有更新时间和添加时间的,添加记录时必须插入更新时间
//拼接SQL语句
BEGIN
SET @sel = ‘DELETE FROM us_projectpipeline where Id in (‘;
SET @sentence = concat(@sel,_id,‘)‘); -- 连接字符串生成要执行的SQL语句
prepare stmt from @sentence; -- 预编释一下。 “stmt”预编释变量的名称,
execute stmt; -- 执行SQL语句
deallocate prepare stmt; -- 释放资源
SET @sel1= ‘select count(Id) from us_projectpipeline where Id IN (‘;
SET @sentence1 = concat(@sel1,_id,‘)‘); -- 连接字符串生成要执行的SQL语句
prepare stmt1 from @sentence1; -- 预编释一下。 “stmt”预编释变量的名称,
execute stmt1; -- 执行SQL语句
deallocate prepare stmt1;
END
MySQL实用技巧