DataBase

浏览模式: 标准 | 列表 | 图文
What's the difference between utf8_general_ci and utf8_unicode_ci

What's the difference between utf8_general_ci and utf8_unicode_ci

Copy from http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci

看到本文其实是源于Yii2 的migrate中的init,它其中就有一段:

if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB';
}

于是我才发现了上面的URL,然后打开看了下,发现是有人在提问:Between utf8_general_ci and utf8_unicode_ci, are there any differences in terms of performance?

然后有一个554个赞的评论,这样写:

There are at least two important differences:

  • Accuracy of sorting

    utf8_unicode_ci is based on the Unicode standard for sorting, and sorts accurately in a very wide range of languages.

    utf8_general_ci comes close to correct Unicode sorting in many common languages, but has a number of limitations: in some languages, it won't sort correctly at all. In others, it will merely have some quirks.

  • Performance

    utf8_general_ci is faster at comparisons and sorting, because it takes a bunch of performance-related shortcuts.

    utf8_unicode_ci uses a much more complex comparison algorithm which aims for correct sorting according in a very wide range of languages. This makes it slower to sort and compare large numbers of fields.

Unicode defines complex sets of rules for how characters should be sorted. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.

  • As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8_general_ci sorting in MySQL, but there are still a few differences:

    For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8_general_ci sorts them as single characters (presumably like "s" and "e" respectively).

  • In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8_general_ci sorting. The suitability of utf8_general_ci will depend heavily on the language used. For some languages, it'll be quite inadequate.

Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8_unicode_ci handles these properly.

What should you use?

There is almost never any reason to use utf_general_ci anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by quite other bottlenecks than this nowadays. The difference in performance is only going to be measurable in extremely specialised situations, and if that's you, you'd already know about it. If you're experiencing slow sorting, in almost all cases it'll be an issue with your indexes/query plan. Changing your collation function should not be high on the list of things to troubleshoot.

When I originally wrote this answer (over 4 years ago) I said that if you wanted, you could use utf8_general_ci most of the time, and only use utf8_unicode_ci when sorting was going to be important enough to justify the performance cost. However, the performance cost is no longer really relevant (and it may not have been back then, either). It's more important to sort properly in whichever language your users are using.

One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

还有一些代码,不过我就不贴了,建议查看原网页,别说没地址。。

解决:Data truncated for column 'fieldname' at row 1

解决:Data truncated for column 'fieldname' at row 1

在修改数据库结构的时候,突然间报这个错:Data truncated for column 'xxxxx' at row 1,xxxxx是数据库的字段名。

检查了一下,原来刚才在修改字段的时候,加了一个允许 null,然后默认的值都变成null,可是后来我又修改表结构为not null default '';所以,报会这个错

到数据库里:update xxxx set xxx = '';,再修改表结构,一切Over。

MYSQL 存储过程

MYSQL 存储过程

说实话,关于存储过程的博客还真的不多,有几个是值得看一下的

1、官方;http://dev.mysql.com/doc/refman/5.1/zh/stored-procedures.html

2、http://www.netingcn.com/tag/%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B

3、http://blog.why100000.com/?p=711

也发现,如果不做复杂查询,存储过程对我来说几乎没有,本来是想解决查找GEO相关的信息的,但发现这样的SQL:

SELECT userid,lat,lng,gender,
( 6371 * acos( cos( radians(31.000700) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(120.000099) ) + sin( radians(31.000700) ) * sin( radians( lat ) ) ) ) AS distance
FROM `user_geo` WHERE last_activity_time > '2013-03-11 00:00:00'
ORDER BY distance ASC limit 100

这其中的复杂度就在于distance每次都要计算,所以我尝试换成了存储过程:

DROP PROCEDURE IF EXISTS search_around_user;
DELIMITER //
CREATE PROCEDURE search_around_user
(
s_lat float(10,6),
s_lng float(10,6),
s_last_act datetime,
s_gender tinyint,
s_number tinyint,
s_page tinyint
)
LABEL_PROC:
BEGIN
if s_number <= 1 then
set s_number = 20;
end if;
if s_page <= 0 then
set s_page = 0;
end if;
if s_gender <= 0 then
set @genderQuery = "";
else
set @genderQuery = concat(" and gender = " , s_gender , " ");
end if;
set @limitQuery = concat("LIMIT " , s_page * s_number , " , " , s_number , " ");

set @strsql = CONCAT("select userid, ",
"( 6371 * acos( cos( radians(",s_lat,") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( ",s_lng," ) ) ",
"+ sin( radians( ",s_lat," ) ) * sin( radians( lat ) ) ) ) AS distance ",
" FROM user_geo where last_activity_time >= '", s_last_act , "' " , @genderQuery , " ORDER BY distance " , @limitQuery) ;

prepare stmtsql from @strsql;
execute stmtsql;


END LABEL_PROC;
//
DELIMITER ;

然后再次调用:

call search_around_user(31.000700,120.000099,'2013-03-11 00:00:00',0,20,0)

所耗费的时间和上述直接写SQL的时间是几乎一样的。想来,这也是因为distance的计算不能被优化而导致的。。。于是乎,放弃用存储过程

全文索引的苦逼记事二

全文索引的苦逼记事二

继昨天的处理之后,又来新的笔记 ,这次的笔记纯粹是个人的测试,与实际条件有关,比如,我要查询的字段不超过varchar的255的长度,所以我才这么做。

昨天做普通索引后,1100万条记录,索引 为220M,改成全文索引后,索引文件为1.1G,存储空间上,涨了5倍左右。

以下是笔记 ,请不要笑话,场景不同而已

  • 经过测试
    • title 字段改为全文索引后,在1100万条的时候
      • 优点:
        • 速度也为0.0x秒级。速度非常快
        • 即使有or条件,只要带了limit参数,速度也非常快
      • 缺点:
        • 如果查询不带limit ,直接卡死,因为他要计算total count
        • select count() 卡死
        • 如果查询不存在的关键字,卡死
    • 使用方法
      • 尽量不做select count 查询 (数量低于100万时可以考虑,超过100万时,其实已经没有必要)
      • 查询一定要带上limit条件
      • 每次查询到不存在的关键字时,记录到关键词库,每次有新增记录时,select 关键词库一下,如果新增房间中有关键字,则将关键词去除,避免卡死
  • 暂时不使用coreseek(sphinx)/xunsearch等第三方工具
    • xunsearch只支持分词查询,不支持完全匹配
    • 第三方工具,耗内存,而且增量的时候,不够及时
全文索引的苦逼记事一

全文索引的苦逼记事一

这是一篇未完成的博客,在这里面做了一点记录

场景:需要做一个关于标题的模糊查询,只是记录有点多,而且需要相对精确,比如搜索:ac, 不能出现abc,可以接受acb,bac,之类。
测试:
1、100万数据,mysql / mongo ,在这种情况下。无论是查询什么数据,基本上都在0.00x秒级,
mysql的查询是like '%xxxx%' , mongo 是 {title:/xxxx/i}
一般情况下,两者速度真心差不多,但如果查询一下不数据库中不存在的关键字,一般都在0.2秒至2秒左右,mongo会相对好一点,在0.5秒
2、500万~1000万数据
查询条件如上
mysql 查询的时候 cpu 占40%左右,20多秒 (mysql 1100万数据)
mongo 查询的时候 CPU占50%左右,10秒/8秒左右 (mongo 550万)
这种性能没法用啊
---下一步
1、xunsearch / coreseek(sphinx)
2、mysql 全文索引
需要再次测试一下。关键mysql虽然100万只有0.00x或者0.0x秒左右。但是如果多个并发的时候就会卡死了。
所以需要再次考虑 场景的复杂性
MySQL STRAIGHT_JOIN 与 NATURAL JOIN

MySQL STRAIGHT_JOIN 与 NATURAL JOIN

这是一篇文档的简要介绍,本来没有想过要提的,因为我以前真没用过straight join,看到这个名词其实是老王的一句话,他说,利用这个优化了SQL,于是就看了一下。果然发到了这句话:

STRAIGHT_JOIN 实际上与内连接 INNER JOIN 表现完全一致,不同的是使用了 STRAIGHT_JOIN 后,table1 会先于 table2 载入。
提示
MySQL 在执行 INNER JOIN 的时候,会根据自己内部的优化规则来决定先载入 table1 还是 table2,如果您确认 MySQL 载入表的顺序并不是最优化的时候,就可以使用 STRAIGHT_JOIN 以替代 INNER JOIN。

我参考的这页,说是关于mysql 的join有五篇:

本章节内容共分 5 部分:

  1. 1. MySQL JOIN 语法说明与 INNER JOIN 语法用法实例
  2. 2. MySQL LEFT JOIN 语法用法与实例
  3. 3. MySQL RIGHT JOIN 语法用法与实例
  4. 4. MySQL JOIN 多表连接
  5. 5. MySQL STRAIGHT_JOIN 与 NATURAL JOIN
  6. 确实 是值得一看。
mongodb 的 geo near

mongodb 的 geo near

本来是想用mongo的geo功能来做查询,想着这个功能是它自带的,性能一定很牛叉吧?结果事实让我们非常失望。

我们做了一个简单的测试,插了1000万条数据,y=x的方式插入,即[0.00001,0.00001]~[99.99999,99.99999],在坐标上其实就是显示成一条实现。如果我们随便指定一个坐标值,求near。你会发现其实很卡。。。20多秒才能出数据,而且还不准。

要知道我的机器可是:i7 4核,16G内存,SSD的硬盘,都这么卡,而且出来的都这么慢。

当然,其实更重要的是不准。。。我坐标[20,90],查出来的点,居然是[55,55],这太让人伤心了。随便算了算,怎么着都应该是77左右啊。。。

估计,只能用mysql了。。。伤心。

MySQL中show语法

MySQL中show语法

我知道,你看到下面的内容,一定没有兴趣往下读,实在太乱了,所以我准备了两份PDF,希望你们读起来会方便一点(两种不同的排版方式,看各位喜欢了)

1、第一份,原网站的排版:mysql中show-句法得到表列及整个库的详细信息(精品珍藏).pdf

2、我自己整理的markdown格式的排版:mysql_show命令.pdf

mysql show命令

show databases;

show tables from db_name;

show columns from table_name from db_name;

show index from talbe_name [from db_name];

show status;

show variables;

show [full] processlist;

show table status [from db_name];

show grants for user;

除了status,processlist和grants外,其它的都可以带有like wild选项,它可以使用SQL的'%'和'_'字符;

show databases like '%t';

将会列出所有数据库名字末尾为't'字符的数据库

当然了,在这些sql中,你也可以用db_name.table_name来代替 table_name from db_name这样写会更简便些!

如果一个用户没有一个表的任何权限,表将不在SHOW TABLES或mysqlshow db_name中的输出中显示

大家可能还记得describe table_name ,它实现的是与show columns from db_name.table_name一样的效果

show status将可以用mysqlshow --status 来得到同样的效果

  • 列 含义
  • Name 表名
  • Type 表的类型 (ISAM,MyISAM或HEAP)
  • Row_format 行存储格式 (固定, 动态, 或压缩)
  • Rows 行数量
  • Avg_row_length 平均行长度
  • Data_length 数据文件的长度
  • Max_data_length 数据文件的最大长度
  • Index_length 索引文件的长度
  • Data_free 已分配但未使用了字节数
  • Auto_increment 下一个 autoincrement(自动加1)值
  • Create_time 表被创造的时间
  • Update_time 数据文件最后更新的时间
  • Check_time 最后对表运行一个检查的时间
  • Create_options 与CREATE TABLE一起使用的额外选项
  • Comment 当创造表时,使用的注释 (或为什么MySQL不能存取表信息的一些信息)。

SHOW FIELDS是SHOW COLUMNS一个同义词,SHOW KEYS是SHOW INDEX一个同义词。你也可以用mysqlshow db_name tbl_name或mysqlshow -k db_name tbl_name 列出一张表的列或索引。

SHOW INDEX以非常相似于ODBC的SQLStatistics调用的格式返回索引信息。下面的列被返回:

列 含义

Table 表名

Non_unique 0,如果索引不能包含重复。

Key_name 索引名

Seq_in_index 索引中的列顺序号, 从 1 开始。

Column_name 列名。

Collation 列怎样在索引中被排序。在MySQL中,这可以有值A(升序) 或NULL(不排序)。

Cardinality 索引中唯一值的数量。这可通过运行isamchk -a更改.

Sub_part 如果列只是部分被索引,索引字符的数量。NULL,如果整个键被索引。

SHOW STATUS提供服务器的状态信息(象mysqladmin extended-status一样)。输出类似于下面的显示,尽管格式和数字可以有点不同:

+--------------------------+--------+

| Variable_name | Value |

+--------------------------+--------+

| Aborted_clients | 0 |

| Aborted_connects | 0 |

| Connections | 17 |

| Created_tmp_tables | 0 |

| Delayed_insert_threads | 0 |

| Delayed_writes | 0 |

| Delayed_errors | 0 |

| Flush_commands | 2 |

| Handler_delete | 2 |

| Handler_read_first | 0 |

| Handler_read_key | 1 |

| Handler_read_next | 0 |

| Handler_read_rnd | 35 |

| Handler_update | 0 |

| Handler_write | 2 |

| Key_blocks_used | 0 |

| Key_read_requests | 0 |

| Key_reads | 0 |

| Key_write_requests | 0 |

| Key_writes | 0 |

| Max_used_connections | 1 |

| Not_flushed_key_blocks | 0 |

| Not_flushed_delayed_rows | 0 |

| Open_tables | 1 |

| Open_files | 2 |

| Open_streams | 0 |

| Opened_tables | 11 |

| Questions | 14 |

| Slow_queries | 0 |

| Threads_connected | 1 |

| Threads_running | 1 |

| Uptime | 149111 |

+--------------------------+--------+

上面列出的状态变量有下列含义:

  • Aborted_clients 由于客户没有正确关闭连接已经死掉,已经放弃的连接数量。
  • Aborted_connects 尝试已经失败的MySQL服务器的连接的次数。
  • Connections 试图连接MySQL服务器的次数。
  • Created_tmp_tables 当执行语句时,已经被创造了的隐含临时表的数量。
  • Delayed_insert_threads 正在使用的延迟插入处理器线程的数量。
  • Delayed_writes 用INSERT DELAYED写入的行数。
  • Delayed_errors 用INSERT DELAYED写入的发生某些错误(可能重复键值)的行数。
  • Flush_commands 执行FLUSH命令的次数。
  • Handler_delete 请求从一张表中删除行的次数。
  • Handler_read_first 请求读入表中第一行的次数。
  • Handler_read_key 请求数字基于键读行。
  • Handler_read_next 请求读入基于一个键的一行的次数。
  • Handler_read_rnd 请求读入基于一个固定位置的一行的次数。
  • Handler_update 请求更新表中一行的次数。
  • Handler_write 请求向表中插入一行的次数。
  • Key_blocks_used 用于关键字缓存的块的数量。
  • Key_read_requests 请求从缓存读入一个键值的次数。
  • Key_reads 从磁盘物理读入一个键值的次数。
  • Key_write_requests 请求将一个关键字块写入缓存次数。
  • Key_writes 将一个键值块物理写入磁盘的次数。
  • Max_used_connections 同时使用的连接的最大数目。
  • Not_flushed_key_blocks 在键缓存中已经改变但是还没被清空到磁盘上的键块。
  • Not_flushed_delayed_rows 在INSERT DELAY队列中等待写入的行的数量。
  • Open_tables 打开表的数量。
  • Open_files 打开文件的数量。
  • Open_streams 打开流的数量(主要用于日志记载)
  • Opened_tables 已经打开的表的数量。
  • Questions 发往服务器的查询的数量。
  • Slow_queries 要花超过long_query_time时间的查询数量。
  • Threads_connected 当前打开的连接的数量。
  • Threads_running 不在睡眠的线程数量。
  • Uptime 服务器工作了多少秒。

关于上面的一些注释:

如果Opened_tables太大,那么你的table_cache变量可能太小。

如果key_reads太大,那么你的key_cache可能太小。缓存命中率可以用key_reads/key_read_requests计算。

如果Handler_read_rnd太大,那么你很可能有大量的查询需要MySQL扫描整个表或你有没正确使用键值的联结(join)。

SHOW VARIABLES显示出一些MySQL系统变量的值,你也能使用mysqladmin variables命令得到这个信息。如果缺省值不合适,你能在mysqld启动时使用命令行选项来设置这些变量的大多数。输出类似于下面的显示,尽管格式和数字可以有点不同:

+------------------------+--------------------------+

| Variable_name | Value |

+------------------------+--------------------------+

| back_log | 5 |

| connect_timeout | 5 |

| basedir | /my/monty/ |

| datadir | /my/monty/data/ |

| delayed_insert_limit | 100 |

| delayed_insert_timeout | 300 |

| delayed_queue_size | 1000 |

| join_buffer_size | 131072 |

| flush_time | 0 |

| interactive_timeout | 28800 |

| key_buffer_size | 1048540 |

| language | /my/monty/share/english/ |

| log | OFF |

| log_update | OFF |

| long_query_time | 10 |

| low_priority_updates | OFF |

| max_allowed_packet | 1048576 |

| max_connections | 100 |

| max_connect_errors | 10 |

| max_delayed_threads | 20 |

| max_heap_table_size | 16777216 |

| max_join_size | 4294967295 |

| max_sort_length | 1024 |

| max_tmp_tables | 32 |

| net_buffer_length | 16384 |

| port | 3306 |

| protocol-version | 10 |

| record_buffer | 131072 |

| skip_locking | ON |

| socket | /tmp/mysql.sock |

| sort_buffer | 2097116 |

| table_cache | 64 |

| thread_stack | 131072 |

| tmp_table_size | 1048576 |

| tmpdir | /machine/tmp/ |

| version | 3.23.0-alpha-debug |

| wait_timeout | 28800 |

+------------------------+--------------------------+

SHOW PROCESSLIST显示哪个线程正在运行,你也能使用mysqladmin processlist命令得到这个信息。

如果你有process权限, 你能看见所有的线程,否则,你仅能看见你自己的线程。见7.20 KILL句法。如果你不使用FULL选项,那么每个查询只有头100字符被显示出来。

SHOW GRANTS FOR user列出对一个用户必须发出以重复授权的授权命令。

mysql> SHOW GRANTS FOR root@localhost;

+---------------------------------------------------------------------+

| Grants for root@localhost |

+---------------------------------------------------------------------+

| GRANT ALL PRIVILEGES ON *.* TO 'root''localhost' WITH GRANT OPTION |

+---------------------------------------------------------------------+

1

关于mongo的GEO相关笔记

关于mongo的GEO相关笔记

很乱。我自己明白即可,三种查询条件。

{loc:{"$near":[121.417397,31.204075]} }
{loc : {"$within" : {"$center" : [ [121.417397,31.204075], 5]}} }
db.places.find({loc:{ $near:[ 30.28009,120.12857],$maxDistance:5}}).limit(20)

上述的内容参考与某个网站,它的基本内容如下:

最近一直在做基于LBS的项目,地标的坐标索引和基于坐标查询,一直没找到一种简单方便的方法,在做mongo索引优化的时发现竟然有Geo的索引
创建字段
建议使用方式:{ loc : [ longitude , latitude] }
也可以:{ loc : { lon :longitude, lat:latitude } }
Loc自己决定,我用poi的
建立索引
注意:每个Collection只能建立一个geospatial索引
db.places.ensureIndex( { loc : “2d” } , { min : -500 , max : 500 } )
如果db.places.ensureIndex( { loc : “2d” }),
默认值的范围是:-180到180,也就是经纬度的范围
查询
注:1.默认会按距离排序;
2.转换 111.12 距离(一度是大约 111.12 公里)使用公里,或由 69 (对于英里)
默认取100条距离最近的点,注:默认是limit(100)
db.collection.find({loc:{$near :[ 30.28009,120.12857]}})
取正方形范围的坐标点,注意:5是坐标系的5,也就是经纬度的5,按111.12换算成公里
db.places.find({loc:{ $near:[ 30.28009,120.12857],$maxDistance:5}}).limit(20)
取指定半径的点,注意:半径5是坐标系的5,也就是经纬度的5,按111.12换算成公里
以5为半径的圆:{“Coordinate” : {“$within” : {“$center” : [ [30.28009,120.12857], 5]}} }
---------

纯笔记,别多想,测试了一下。比现在使用的好多了,我现在是:
$criteria->order = new \CDbExpression("ACOS(SIN(({$lat} * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(({$lat} * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(({$lng} * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc,last_activity_time DESC");

不要多想,我是用的Yii的玩意,也是一个笔记。

mongo中的group by

mongo中的group by

在mysql里面,我们偶尔会有这样的sql出现:
select userid,count(userid) as cnt from xxxxxtable group by userid;

这样的sql在mongo里怎么实现呢?其实也相对比较简单

<?php
$mongo = new Mongo();
$mongo->selectDB('xxx');//库
$collection = $mongo->selectCollection('表');

$field = array('userid'=>1);
$cnt = array('cnt'=>0);
$result = $collection->group($field,$cnt,"function(obj,pref){pref.cnt++;}");

打印出来的结果也很方便识别:

Array
(
[retval] => Array
(
[0] => Array
(
[userid] => 11111
[cnt] => 2
)
//省略
)

[count] => 21
[keys] => 11
[ok] => 1
)

果然轻轻松松啊