<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mysql &#8211; LPC影子技术分享</title>
	<atom:link href="https://www.mudbest.com/category/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mudbest.com</link>
	<description>行影不离,忘之却步.</description>
	<lastBuildDate>Mon, 29 Oct 2018 03:08:01 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.2</generator>
	<item>
		<title>VMware下Centos的lnmp编译安装</title>
		<link>https://www.mudbest.com/vmware%e4%b8%8bcentos%e7%9a%84lnmp%e7%bc%96%e8%be%91%e5%ae%89%e8%a3%85/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Tue, 29 Apr 2014 04:36:07 +0000</pubDate>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[lnmp]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=2043</guid>

					<description><![CDATA[VMware安装Centos就不说了，接下来是Centos的相关配置，如果Centos有防火墙的话，则需要配置 ... <a title="VMware下Centos的lnmp编译安装" class="read-more" href="https://www.mudbest.com/vmware%e4%b8%8bcentos%e7%9a%84lnmp%e7%bc%96%e8%be%91%e5%ae%89%e8%a3%85/" aria-label="阅读 VMware下Centos的lnmp编译安装">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>VMware安装Centos就不说了，接下来是Centos的相关配置，如果Centos有防火墙的话，则需要配置防火墙，非Vm通用。</p>
<p><strong>一、开启80端口、3306端口</strong><span id="more-2043"></span></p>
<pre class="brush: bash; title: ; notranslate">
vi /etc/sysconfig/iptables   #编辑防火墙配置文件 
</pre>
<p>-A INPUT -m state &#8211;state NEW -m tcp -p tcp &#8211;dport 80 -j ACCEPT（允许80端口通过防火墙）<br />
-A INPUT -m state &#8211;state NEW -m tcp -p tcp &#8211;dport 3306 -j ACCEPT（允许3306端口通过防火墙）   </p>
<pre class="brush: bash; title: ; notranslate"> 
#特别提示：很多网友把这两条规则添加到防火墙配置的最后一行，导致防火墙启动失败
#正确的应该是添加到默认的22端口这条规则的下面，添加好之后防火墙规则如下所示：
#########################################################    
# Firewall configuration written by system-config-firewall    
# Manual customization of this file is not recommended.    
*filter    
:INPUT ACCEPT &#x5B;0:0]    
:FORWARD ACCEPT &#x5B;0:0]    
:OUTPUT ACCEPT &#x5B;0:0]    
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT    
-A INPUT -p icmp -j ACCEPT    
-A INPUT -i lo -j ACCEPT    
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT    
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT    
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT    
-A INPUT -j REJECT --reject-with icmp-host-prohibited    
-A FORWARD -j REJECT --reject-with icmp-host-prohibited    
COMMIT    
#########################################################    
/etc/init.d/iptables restart  #最后重启防火墙使配置生效 
</pre>
<p><strong>二、关闭SELINUX</strong></p>
<pre class="brush: bash; title: ; notranslate">
vim /etc/selinux/config  #编辑
#SELINUX=enforcing       #注释掉 
#SELINUXTYPE=targeted    #注释掉 
SELINUX=disabled         #增加 
:wq #保存退出
shutdown -r now   #重启系统
</pre>
<p><strong>三、系统约定</strong><br />
软件源代码包存放位置：/usr/local/src<br />
源码包编译安装位置：/usr/local/软件包名字</p>
<p><strong>四、源码包下载</strong><br />
1、pcre下载(支持nginx伪静态)<br />
ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.30.tar.gz</p>
<p>2、mysql下载<br />
http://cdn.mysql.com/Downloads/MySQL-5.6/mysql-5.6.17.tar.gz</p>
<p>3、libmcrypt-2.5.7<br />
ftp://mcrypt.hellug.gr/pub/crypto/mcrypt/attic/libmcrypt/libmcrypt-2.5.7.tar.gz</p>
<p>3.2、libiconv-1.9.2<br />
http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.9.2.tar.gz</p>
<p>3.3、zlib下载<br />
http://zlib.net/zlib-1.2.8.tar.gz</p>
<p>3.4、php下载<br />
http://ar2.php.net/distributions/php-5.5.11.tar.gz<br />
http://ar2.php.net/distributions/php-5.3.28.tar.gz</p>
<p>3.5、phpredis扩展下载<br />
https://github.com/nicolasff/phpredis/archive/master.zip</p>
<p>4、cmake下载(MySQL编译工具)<br />
http://www.cmake.org/files/v2.8/cmake-2.8.8.tar.gz</p>
<p>5、nginx下载(稳定版本)<br />
http://nginx.org/download/nginx-1.4.7.tar.gz</p>
<p>安装编译工具及库文件（使用CentOS yum命令安装）</p>
<pre class="brush: bash; title: ; notranslate">
yum install make apr* autoconf automake curl-devel gcc gcc-c++ zlib-devel openssl openssl-devel pcre-devel gd  kernel keyutils  patch  perl kernel-headers compat* mpfr cpp glibc libgomp libstdc++-devel ppl cloog-ppl keyutils-libs-devel libcom_err-devel libsepol-devel libselinux-devel krb5-devel zlib-devel libXpm* freetype libjpeg* libpng* php-common php-gd ncurses* libtool* libxml2 libxml2-devel patch freetype-devel
</pre>
<p><strong>五、开始编译安装</strong><br />
1、编译准备工作</p>
<pre class="brush: bash; title: ; notranslate">
yum groupinstall &quot;Development tools&quot;
</pre>
<p>1.1、安装cmake</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src 
tar zxvf cmake-2.8.8.tar.gz 
cd cmake-2.8.8 
./configure make  #编译 
make install   #安装
</pre>
<p>2、安装MySQL</p>
<pre class="brush: bash; title: ; notranslate">
groupadd mysql  #添加mysql组    
useradd -g mysql mysql -s /bin/false  #创建用户mysql并加入到mysql组，不允许mysql用户直接登录系统    
mkdir -p /data/mysql  #创建MySQL数据库存放目录    
chown -R mysql:mysql /data/mysql   #设置MySQL数据库目录权限    
mkdir -p /usr/local/mysql #创建MySQL安装目录    
cd /usr/local/src    
tar zxvf mysql-5.5.25.tar.gz  #解压    
cd mysql-5.5.25    
cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql/ -DMYSQL_DATADIR=/data/mysql/ -DSYSCONFDIR=/etc/  #配置    
make #编译    
make install  #安装    
cd /usr/local/mysql    
cp ./support-files/my-huge.cnf  /etc/my.cnf   #拷贝配置文件（注意：如果/etc目录下面默认有一个my.cnf，直接覆盖即可）    
vim /etc/my.cnf   #编辑配置文件,在 &#x5B;mysqld] 部分增加下面一行    
datadir = /data/mysql  #添加MySQL数据库路径    
:wq!  #保存退出    
cd /usr/local/mysql/ #share 初始化的sql在这里面,下面一句命令默认读取share路径是./share/...
/usr/local/mysql/scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql/ --datadir=/data/mysql/ &amp; #生成mysql系统数据库,并定义数据data存放位置
cp ./support-files/mysql.server  /etc/rc.d/init.d/mysqld  #把Mysql加入系统启动    
chmod 755 /etc/init.d/mysqld   #增加执行权限    
chkconfig mysqld on  #设置开机启动    
vim /etc/rc.d/init.d/mysqld  #编辑    
basedir = /usr/local/mysql   #MySQL程序安装路径    
datadir = /data/mysql  #MySQl数据库存放目录    
service mysqld start  #启动    
vim /etc/profile   #把mysql服务加入系统环境变量：在最后添加下面这一行    
export PATH=$PATH:/usr/local/mysql/bin    
:wq! #保存退出    
</pre>
<p>下面这两行把myslq的库文件链接到系统默认的位置，在编译类似PHP等软件时可以不用指定mysql的库文件地址。 </p>
<pre class="brush: bash; title: ; notranslate">
ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock #创建快捷方式

ln -s /usr/local/mysql/lib /usr/lib/mysql    
ln -s /usr/local/mysql/include/mysql /usr/include/mysql    
shutdown -r now     #需要重启系统，等待系统重新启动之后继续在终端命令行下面操作    
mysql_secure_installation    #设置Mysql密码    

mysql --socket=/var/lib/mysql/mysql.sock #指定sock链接


</pre>
<p>根据提示按Y 回车（默认密码为空）<br />
然后输入2次密码<br />
继续按Y 回车，直到设置完成<br />
或者直接修改密码</p>
<pre class="brush: bash; title: ; notranslate">
/usr/local/mysql/bin/mysqladmin -u root -p password &quot;123456&quot; #修改密码    
service mysqld restart  #重启    
</pre>
<p>到此，mysql安装完成。</p>
<p>3、安装pcre</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src    
mkdir /usr/local/pcre  #创建安装目录    
tar  zxvf pcre-8.30.tar.gz    
cd pcre-8.30    
./configure  --prefix=/usr/local/pcre  #配置    
make    
make install
</pre>
<p>4、安装nginx</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src    
groupadd  www  #添加www组    
useradd -g  www www -s /bin/false  #创建nginx运行账户www并加入到www组，不允许www用户直接登录系统    
tar  zxvf nginx-1.2.0.tar.gz    
cd nginx-1.2.0    
./configure --prefix=/usr/local/nginx --without-http_memcached_module --user=www --group=www --with-http_stub_status_module --with-openssl=/usr/ --with-pcre=/usr/local/src/pcre-8.30    
#注意:--with-pcre=/usr/local/src/pcre-8.30指向的是源码包解压的路径，而不是安装的路径，否则会报错    
make    
make install    
/usr/local/nginx/sbin/nginx   #启动nginx    
</pre>
<pre class="brush: bash; title: ; notranslate">
vim /etc/rc.d/init.d/nginx    #设置nginx开启启动，编辑启动文件添加下面内容 
</pre>
<pre class="brush: bash; title: ; notranslate">
#################################################################    
#!/bin/bash    
# nginx Startup script for the Nginx HTTP Server    
# it is v.0.0.2 version.    
# chkconfig: - 85 15    
# description: Nginx is a high-performance web and proxy server.    
#              It has a lot of features, but it's not for everyone.    
# processname: nginx    
# pidfile: /var/run/nginx.pid    
# config: /usr/local/nginx/conf/nginx.conf    
nginxd=/usr/local/nginx/sbin/nginx    
nginx_config=/usr/local/nginx/conf/nginx.conf    
nginx_pid=/usr/local/nginx/logs/nginx.pid    
RETVAL=0    
prog=&quot;nginx&quot;    
# Source function library.    
.  /etc/rc.d/init.d/functions    
# Source networking configuration.    
.  /etc/sysconfig/network    
# Check that networking is up.    
&#x5B; ${NETWORKING} = &quot;no&quot; ]  exit 0    
&#x5B; -x $nginxd ] || exit 0    
# Start nginx daemons functions.    
start() {    
if &#x5B; -e $nginx_pid ];then    
  echo &quot;nginx already running....&quot;    
  exit 1    
fi    
  echo -n $&quot;Starting $prog: &quot;    
  daemon $nginxd -c ${nginx_config}    
  RETVAL=$?    
  echo    
  &#x5B; $RETVAL = 0 ]  touch /var/lock/subsys/nginx    
  return $RETVAL    
}    
# Stop nginx daemons functions.    
stop() {    
       echo -n $&quot;Stopping $prog: &quot;    
       killproc $nginxd    
       RETVAL=$?    
       echo    
       &#x5B; $RETVAL = 0 ]  rm -f /var/lock/subsys/nginx /usr/local/nginx/logs/nginx.pid    
}    
reload() {    
   echo -n $&quot;Reloading $prog: &quot;    
   #kill -HUP `cat ${nginx_pid}`    
   killproc $nginxd -HUP    
   RETVAL=$?    
   echo    
}    
# See how we were called.    
case &quot;$1&quot; in    
start)    
       start    
       ;;    
stop)    
       stop    
       ;;    
reload)    
       reload    
       ;;    
restart)    
       stop    
       start    
       ;;    
               
status)    
       status $prog    
       RETVAL=$?    
       ;;    
*)    
       echo $&quot;Usage: $prog {start|stop|restart|reload|status|help}&quot;    
       exit 1    
esac    
exit $RETVAL    
#################################################################  
:wq!  #保存退出 
</pre>
<pre class="brush: bash; title: ; notranslate">   
chmod 775  /etc/rc.d/init.d/nginx  #赋予文件执行权限    
chkconfig nginx on    #设置开机启动    
/etc/rc.d/init.d/nginx restart  #重启    
</pre>
<p>5.1、安装libmcrypt</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src    
tar zxvf  libmcrypt-2.5.7.tar.gz   #解压    
cd  libmcrypt-2.5.7 #进入目录    
./configure    #配置    
make             #编译    
make install   #安装  
</pre>
<p>5.2、安装libiconv</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src    
tar -zxvf libiconv-1.9.2.tar.gz   #解压    
cd  libiconv-1.9.2 #进入目录    
./configure --prefix=/usr/local/iconv    #配置    
make             #编译    
make install   #安装  

#重新编译php 增加编译参数--with-iconv=/usr/local/iconv 
</pre>
<p>5.3、安装zlib</p>
<pre class="brush: bash; title: ; notranslate">
yum info zlib
cd /usr/local/src    
tar -zxvf zlib-1.2.8.tar.gz   #解压    
cd  zlib-1.2.8 #进入目录    
./configure --prefix=/usr/local/zlib    #配置    
make             #编译    
make install   #安装  

#重新编译php 增加编译参数--with-iconv=/usr/local/iconv 
</pre>
<p>5.4、php5需要的devel 包：</p>
<pre class="brush: bash; title: ; notranslate">
yum install libxml2-devel gd-devel libmcrypt-devel libcurl-devel openssl-devel
</pre>
<p>6、安装php</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src    
tar -zvxf php-5.3.13.tar.gz    
cd  php-5.3.13    
mkdir -p /usr/local/php5  #建立php安装目录    
#5.3配置    
./configure --prefix=/usr/local/php5 --with-config-file-path=/usr/local/php5/etc --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-mysql-sock=/tmp/mysql.sock --with-gd --with-iconv=/usr/local/iconv --with-zlib  --enable-xml --enable-magic-quotes --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curlwrappers --enable-mbregex  --enable-fpm --enable-mbstring --enable-ftp --enable-gd-native-ttf --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --without-pear --with-gettext --enable-session --with-mcrypt --with-curl --with-jpeg-dir --with-freetype-dir    
#5.5配置    
./configure --prefix=/usr/local/php5 --with-config-file-path=/usr/local/php5/etc --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-mysql-sock=/tmp/mysql.sock --with-gd --with-iconv=/usr/local/iconv  --with-zlib --with-zlib-dir=/usr/local/zlib  --enable-xml --enable-magic-quotes --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curlwrappers --enable-fpm --enable-mbstring --enable-ftp --enable-gd-native-ttf --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --without-pear --with-gettext --enable-session --with-mcrypt --with-curl --with-jpeg-dir --with-freetype-dir 

make   #编译    
make install    #安装    

ln -s -f /usr/local/php5/bin/phar.phar /usr/local/php5/bin/phar
</pre>
<pre class="brush: bash; title: ; notranslate">
cp  php.ini-production   /usr/local/php5/etc/php.ini  #复制php配置文件到安装目录 
</pre>
<pre class="brush: bash; title: ; notranslate">
rm -rf /etc/php.ini   #删除系统自带配置文件    
ln -s /usr/local/php5/etc/php.ini  /etc/php.ini    #添加软链接    
cp  /usr/local/php5/etc/php-fpm.conf.default   /usr/local/php5/etc/php-fpm.conf      #拷贝模板文件为php-fpm配置文件    
vim  /usr/local/php5/etc/php-fpm.conf  #编辑    
user = www    #设置php-fpm运行账号为www    
group = www   #设置php-fpm运行组为www    
pid = run/php-fpm.pid    #取消前面的分号    
cp /usr/local/src/php-5.3.13/sapi/fpm/init.d.php-fpm   /etc/rc.d/init.d/php-fpm  #设置 php-fpm开机启动，拷贝php-fpm到启动目录    
chmod +x /etc/rc.d/init.d/php-fpm  #添加执行权限    
chkconfig php-fpm on    #设置开机启动    
</pre>
<pre class="brush: bash; title: ; notranslate">
vim /usr/local/php5/etc/php.ini    #编辑配置文件  
</pre>
<p>找到：&#8221;disable_functions =&#8221;，修改为：</p>
<pre class="brush: bash; title: ; notranslate">
disable_functions = passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,escapeshellcmd,dll,popen,disk_free_space,checkdnsrr,checkdnsrr,getservbyname,getservbyport,disk_total_space,posix_ctermid,posix_get_last_error,posix_getcwd, posix_getegid,posix_geteuid,posix_getgid, posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid, posix_getppid,posix_getpwnam,posix_getpwuid, posix_getrlimit, posix_getsid,posix_getuid,posix_isatty, posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid, posix_setpgid,posix_setsid,posix_setuid,posix_strerror,posix_times,posix_ttyname,posix_uname     
</pre>
<p>#列出PHP可以禁用的函数，如果某些程序需要用到这个函数，可以删除，取消禁用。</p>
<p>找到：&#8221;;date.timezone =&#8221;，修改为：</p>
<pre class="brush: bash; title: ; notranslate">
date.timezone = PRC   #设置时区   
</pre>
<p>找到：&#8221;expose_php = On&#8221;，修改为：</p>
<pre class="brush: bash; title: ; notranslate">
修改为：expose_php = OFF  #禁止显示php版本的信息    
</pre>
<p>注意：在编译PHP的过程中可能会报UNDEFINED REFERENCE TO `LIBICONV_OPEN 无法编译PHP LIBICONV错误</p>
<p>php5.4 php-fpm重启方法</p>
<p>master进程可以理解以下信号<br />
INT, TERM 立刻终止<br />
QUIT 平滑终止<br />
USR1 重新打开日志文件<br />
USR2 平滑重载所有worker进程并重新载入配置和二进制模块</p>
<p>示例：<br />
php-fpm 启动：</p>
<pre class="brush: bash; title: ; notranslate">
/usr/local/php5/sbin/php-fpm
</pre>
<p>php-fpm 关闭：</p>
<pre class="brush: bash; title: ; notranslate">
kill -INT `cat /usr/local/php5/var/run/php-fpm.pid`
</pre>
<p>php-fpm 重启：</p>
<pre class="brush: bash; title: ; notranslate">
kill -USR2 `cat /usr/local/php5/var/run/php-fpm.pid`
</pre>
<p>查看php-fpm进程数：</p>
<pre class="brush: bash; title: ; notranslate">
ps aux | grep -c php-fpm
</pre>
<p>6.1、phpredis扩展安装</p>
<pre class="brush: bash; title: ; notranslate">
cd /usr/local/src/phpredis-master
/usr/local/php5/bin/phpize
./configure --with-php-config=/usr/local/php5/bin/php-config
make
make install
</pre>
<p>增加phpredis扩展</p>
<pre class="brush: bash; title: ; notranslate">
vim /usr/local/php5/etc/php.ini
</pre>
<p>在后面增加</p>
<pre class="brush: bash; title: ; notranslate">
extension=redis.so
</pre>
<p>测试</p>
<pre class="brush: php; title: ; notranslate">
$objRedis = new Redis();
$objRedis&gt;connect('127.0.0.1',6379)
$objRedis-&gt;set('test','ok');
echo $objRedis-&gt;get('test');
</pre>
<p>7、配置nginx支持php</p>
<pre class="brush: bash; title: ; notranslate">
vim /usr/local/nginx/conf/nginx.conf      #编辑配置文件     
</pre>
<pre class="brush: bash; title: ; notranslate">
user   www  www;          #首行user去掉注释,修改Nginx运行组为www www；必须与/usr/local/php5/etc/php-fpm.conf中的user,group配置相同，否则php运行出错    
index  index.php  index.html index.htm;    #添加index.php    
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000    
#    
location ~ \.php$ {    
   root           html;#此处和server下面root保持一致,默认为html    
   fastcgi_pass   127.0.0.1:9000;    
   fastcgi_index  index.php;    
   fastcgi_param  SCRIPT_FILENAME   /usr/local/nginx/html/$fastcgi_script_name;    
   include        fastcgi_params;          
</pre>
<p>注意：取消FastCGI server部分location的注释,并要注意fastcgi_param行的参数,改为/data/webroot/(此为网站根目录绝对路径)$fastcgi_script_name</p>
<pre class="brush: bash; title: ; notranslate">
/etc/init.d/nginx restart  #重启nginx  
</pre>
<p><a href="http://www.mudbest.com/vmware%e4%b8%8bcentos%e7%9a%84lnmp%e7%bc%96%e8%be%91%e5%ae%89%e8%a3%85/cmake-2-8-8-tar/" rel="attachment wp-att-2053">cmake-2.8.8.tar</a></p>
<p><a href="http://www.mudbest.com/vmware%e4%b8%8bcentos%e7%9a%84lnmp%e7%bc%96%e8%be%91%e5%ae%89%e8%a3%85/nginx-1-4-7-tar/" rel="attachment wp-att-2054">nginx-1.4.7.tar</a><br />
<a href="http://www.mudbest.com/vmware%e4%b8%8bcentos%e7%9a%84lnmp%e7%bc%96%e8%be%91%e5%ae%89%e8%a3%85/phpredis-master/" rel="attachment wp-att-2077">phpredis-master扩展</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>由于binlog未及时清理导致硬盘爆满无法启动mysql</title>
		<link>https://www.mudbest.com/%e7%94%b1%e4%ba%8ebinlog%e6%9c%aa%e5%8f%8a%e6%97%b6%e6%b8%85%e7%90%86%e5%af%bc%e8%87%b4%e7%a1%ac%e7%9b%98%e7%88%86%e6%bb%a1%e6%97%a0%e6%b3%95%e5%90%af%e5%8a%a8mysql/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Sat, 08 Feb 2014 05:04:38 +0000</pubDate>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[Mysql]]></category>
		<category><![CDATA[binlog]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=2017</guid>

					<description><![CDATA[这几天由于太忙了，7天没有观察服务器了，今天用手机打开网站发现报mysql.sock丢失的错误，刚开始以为是m ... <a title="由于binlog未及时清理导致硬盘爆满无法启动mysql" class="read-more" href="https://www.mudbest.com/%e7%94%b1%e4%ba%8ebinlog%e6%9c%aa%e5%8f%8a%e6%97%b6%e6%b8%85%e7%90%86%e5%af%bc%e8%87%b4%e7%a1%ac%e7%9b%98%e7%88%86%e6%bb%a1%e6%97%a0%e6%b3%95%e5%90%af%e5%8a%a8mysql/" aria-label="阅读 由于binlog未及时清理导致硬盘爆满无法启动mysql">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>这几天由于太忙了，7天没有观察服务器了，今天用手机打开网站发现报mysql.sock丢失的错误，刚开始以为是my.ini修改的原因，用df一看，/dev/xvda1的占用已经100%了，这样的情况还能启动mysql就真的逆天了。这时候想到了用sql删除binlog，但是根本进不去控制台，连安全模式都启动不了，以下是具体操作。<span id="more-2017"></span></p>
<p>分配了20G的硬盘，活生生的被binlog吃完了。</p>
<pre class="brush: sql; title: ; notranslate">
tail -f /opt/server/mysql/var/slyar.err
</pre>
<p>看了一下Mysql的错误日志，意外状况出现……</p>
<pre class="brush: sql; title: ; notranslate">
Disk is full writing './mysql-bin.~rec~' (Errcode: 28). Waiting for someone to free space... (Expect up to 60 secs delay for server to continue after freeing disk space)
</pre>
<p>神奇的情况，居然是因为磁盘满了无法写入日志导致Mysql起不来。</p>
<pre class="brush: sql; title: ; notranslate">
root@hkshadow# df 
Filesystem 1K-blocks Used Available Use% Mounted on 
/dev/xvda1 20641404 20641404 0 100% / 
</pre>
<p>基本上就是被这些玩意占满了，查了一下Mysql手册发现这些东西也没啥用，直接删除(此操作最好在Mysql服务停止时进行，因为当前日志使用的话无法删除，而且有可能导致一些其它问题，不过用mysql>reset master命令可以直接清空日志)。</p>
<pre class="brush: sql; title: ; notranslate">/opt/server/mysql/var/
root@hkshadow# cd 
root@hkshadow# rm -f mysql-bin.*
</pre>
<p>如果一定要使用binlog又担心时间久了没及时清理的话，可以在my.ini里设置binlog过期时间。</p>
<pre class="brush: sql; title: ; notranslate">
expire_logs_days = 7
</pre>
<p>如果不需要binlog的话可以关闭掉，避免未来得及监控导致的系列问题。</p>
<pre class="brush: sql; title: ; notranslate">
vim /etc/my.cnf
</pre>
<p>注释掉下面2行</p>
<pre class="brush: sql; title: ; notranslate">
log-bin=mysql-bin
binlog_format=mixed
</pre>
<p>然后重启即可</p>
<pre class="brush: sql; title: ; notranslate">
/etc/init.d/mysqld restart
</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mysql的find_in_set函数查询与like查询</title>
		<link>https://www.mudbest.com/mysql%e7%9a%84find_in_set%e5%87%bd%e6%95%b0%e6%9f%a5%e8%af%a2%e4%b8%8elike%e6%9f%a5%e8%af%a2/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Wed, 20 Mar 2013 07:40:18 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[FIND_IN_SET]]></category>
		<category><![CDATA[instr()]]></category>
		<category><![CDATA[like]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1822</guid>

					<description><![CDATA[对于mysql的like查询，我想都会很熟悉，对于一些基本查询也会常用，但始终不是对大数据量查询的方案。在查询 ... <a title="Mysql的find_in_set函数查询与like查询" class="read-more" href="https://www.mudbest.com/mysql%e7%9a%84find_in_set%e5%87%bd%e6%95%b0%e6%9f%a5%e8%af%a2%e4%b8%8elike%e6%9f%a5%e8%af%a2/" aria-label="阅读 Mysql的find_in_set函数查询与like查询">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>对于mysql的like查询，我想都会很熟悉，对于一些基本查询也会常用，但始终不是对大数据量查询的方案。在查询数据需要对某一个字段里的值当作条件时，一般会用到like、instr()、find_in_set()，首先看一下手册里对这3种用法的定义。</p>
<p><strong>expr LIKE pat [ESCAPE &#8216;escape-char&#8217;] </strong></p>
<p>模式匹配，使用SQL简单正规表达式比较。返回1 (TRUE) 或 0 (FALSE)。 若 expr 或 pat 中任何一个为 NULL,则结果为 NULL。<br />
模式不需要为文字字符串。例如，可以被指定为一个字符串表达式或表列。<br />
在模式中可以同LIKE一起使用以下两种通配符： <span id="more-1822"></span><br />
字符 说明<br />
 %   匹配任何数目的字符，甚至包括零字符<br />
 _   只能匹配一种字符</p>
<p><strong>FIND_IN_SET(str,strlist) </strong></p>
<p>假如字符串str 在由N 子链组成的字符串列表strlist 中， 则返回值的范围在 1 到 N 之间 。一个字符串列表就是一个由一些被‘,’符号分开的自链组成的字符串。如果第一个参数是一个常数字符串，而第二个是type SET列，则   FIND_IN_SET() 函数被优化，使用比特计算。如果str不在strlist 或strlist 为空字符串，则返回值为 0 。如任意一个参数为NULL，则返回值为 NULL。 这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。</p>
<p><strong>INSTR(str,substr)   </strong></p>
<p>返回字符串 str 中子字符串的第一个出现位置。这和LOCATE()的双参数形式相同，除非参数的顺序被颠倒。 </p>
<p>然后来实际操作一次，有以下一下这样的一个数据。</p>
<p>data：</p>
<pre class="brush: sql; title: ; notranslate">
+------+----------------+
| id   | tagsid         |
+------+----------------+
|    4 | 2863,4351,4353 |
|    3 |                |
|    5 | 3395,2219      |
|    6 |                |
|    8 |                |
|    9 |                |
|   10 | 2689,4349,2863 |
| 1652 |                |
|   12 | 4347,3161,3029 |
|   13 | 2193,2519,2229 |
+------+----------------+
10 rows in set (0.00 sec)
</pre>
<p>首先我们使用like查询，结果如下：</p>
<pre class="brush: sql; title: ; notranslate">
mysql&gt; select id,tagsid from tbl_news where find_in_set('2863',`tagsid`) limit 1
0;
+-----+--------------------------+
| id  | tagsid                   |
+-----+--------------------------+
|   4 | 2863,4351,4353           |
|  10 | 2689,4349,2863           |
|  78 | 2863,2197,4327           |
| 245 | 3395,2863                |
|  85 | 2863,2497,3869,4315      |
| 108 | 2193,4301,2863,4303      |
| 121 | 4277,2863,4279,3311,3215 |
| 122 | 4277,4279,2863,4189,3109 |
| 137 | 3361,3811,2829,3255,2863 |
| 149 | 2289,2197,2863,2519,4199 |
+-----+--------------------------+
10 rows in set (0.00 sec)
</pre>
<p>注意：<br />
select id,tagsid from tbl_news where find_in_set(字段,值) limit 10;<br />
使用find_in_set函数一次返回多条记录 </p>
<pre class="brush: sql; title: ; notranslate">
mysql&gt; select id,tagsid from tbl_news where find_in_set(`id`,'78,10,21,2,3,22') limit 10;
</pre>
<p>id 是一个表的字段 然后每条记录分别是id等于78,10,21,2,3,22的时候，有点类似in （集合）。</p>
<pre class="brush: sql; title: ; notranslate">
mysql&gt; select id,tagsid from tbl_news where `id` in(78,10,21,2,3,22) limit 10;
</pre>
<p>然后用find_in_set()查询，结果如下：</p>
<pre class="brush: sql; title: ; notranslate">
mysql&gt; select id,tagsid from `tbl_news` limit 10;
+------+----------------+
| id   | tagsid         |
+------+----------------+
|    4 | 2863,4351,4353 |
|    3 |                |
|    5 | 3395,2219      |
|    6 |                |
|    8 |                |
|    9 |                |
|   10 | 2689,4349,2863 |
| 1652 |                |
|   12 | 4347,3161,3029 |
|   13 | 2193,2519,2229 |
+------+----------------+
10 rows in set (0.00 sec)
</pre>
<p>最后使用instr()查询，结果如下：</p>
<pre class="brush: sql; title: ; notranslate">
mysql&gt; select id,tagsid from tbl_news where instr(`tagsid`,'2863') &gt; 0 limit 10;

+-----+--------------------------+
| id  | tagsid                   |
+-----+--------------------------+
|   4 | 2863,4351,4353           |
|  10 | 2689,4349,2863           |
|  78 | 2863,2197,4327           |
| 245 | 3395,2863                |
|  85 | 2863,2497,3869,4315      |
| 108 | 2193,4301,2863,4303      |
| 121 | 4277,2863,4279,3311,3215 |
| 122 | 4277,4279,2863,4189,3109 |
| 137 | 3361,3811,2829,3255,2863 |
| 149 | 2289,2197,2863,2519,4199 |
+-----+--------------------------+
10 rows in set (0.00 sec)
</pre>
<p>初步查看并没有什么区别，紧紧在使用方法有所不同，由于查询量比较小，也未做压力测试，查询效率也就不曾而知了，但对于用法上，可根据自己的需求，选择性使用。对于大数据的查询，建议还是数据层上面搭建一个缓冲层，避免对数据库的实时查询等操作，比如索引，缓存，等等措施，毕竟全文查询对mysql压力实在是太大，以上均为本人拙见。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Sphinx在windows下安装使用(支持中文全文检索)</title>
		<link>https://www.mudbest.com/sphinx%e5%9c%a8windows%e4%b8%8b%e5%ae%89%e8%a3%85%e4%bd%bf%e7%94%a8%e6%94%af%e6%8c%81%e4%b8%ad%e6%96%87%e5%85%a8%e6%96%87%e6%a3%80%e7%b4%a2/</link>
					<comments>https://www.mudbest.com/sphinx%e5%9c%a8windows%e4%b8%8b%e5%ae%89%e8%a3%85%e4%bd%bf%e7%94%a8%e6%94%af%e6%8c%81%e4%b8%ad%e6%96%87%e5%85%a8%e6%96%87%e6%a3%80%e7%b4%a2/#comments</comments>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Fri, 15 Mar 2013 03:03:47 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[Sphinx]]></category>
		<category><![CDATA[分词搜索]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1805</guid>

					<description><![CDATA[前段时间听同事谈起过，公司内部的一个搜索功能用的就是Sphinx，但一直没时间去整一下，今天刚好有点时间，那么 ... <a title="Sphinx在windows下安装使用(支持中文全文检索)" class="read-more" href="https://www.mudbest.com/sphinx%e5%9c%a8windows%e4%b8%8b%e5%ae%89%e8%a3%85%e4%bd%bf%e7%94%a8%e6%94%af%e6%8c%81%e4%b8%ad%e6%96%87%e5%85%a8%e6%96%87%e6%a3%80%e7%b4%a2/" aria-label="阅读 Sphinx在windows下安装使用(支持中文全文检索)">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>前段时间听同事谈起过，公司内部的一个搜索功能用的就是Sphinx，但一直没时间去整一下，今天刚好有点时间，那么就折腾一次吧。一般在linux上比较多，今天就在windows下安装于调试一下吧。</p>
<p>前言：</p>
<p><strong>一、关于Sphinx</strong></p>
<p>Sphinx 是一个在GPLv2 下发布的一个全文检索引擎，商业授权（例如, 嵌入到其他程序中）需要联系作者（Sphinxsearch.com）以获得商业授权。<br />
一般而言，Sphinx是一个独立的搜索引擎，意图为其他应用提供高速、低空间占用、高结果相关度的全文搜索功能。Sphinx可以非常容易的与SQL数据库和脚本语言集成。<br />
当前系统内置MySQL和PostgreSQL 数据库数据源的支持，也支持从标准输入读取特定格式的XML数据。通过修改源代码，用户可以自行增加新的数据源（例如：其他类型的DBMS的原生支持）。<br />
搜索API支持PHP、Python、Perl、Rudy和Java，并且也可以用作MySQL存储引擎。搜索API非常简单，可以在若干个小时之内移植到新的语言上。<span id="more-1805"></span></p>
<p>本文旨在提供一种便捷的方式让Sphinx在windows下安装配置以支持中文全文检索，配置部分在linux下通用。</p>
<p>搜索API支持PHP、Python、Perl、Rudy和Java，并且也可以用作MySQL存储引擎。搜索API非常简单，可以在若干个小时之内移植到新的语言上。<br />
<strong><br />
Sphinx特性：</strong></p>
<p>    高速的建立索引(在当代CPU上，峰值性能可达到10MB/秒);<br />
    高性能的搜索(在2–4GB的文本数据上，平均每次检索响应时间小于0.1秒);<br />
    可处理海量数据(目前已知可以处理超过100GB的文本数据,在单一CPU的系统上可处理100M文档);<br />
    提供了优秀的相关度算法，基于短语相似度和统计（BM25）的复合Ranking方法;<br />
    支持分布式搜索;<br />
    提供文件的摘录生成;<br />
    可作为MySQL的存储引擎提供搜索服务;<br />
    支持布尔、短语、词语相似度等多种检索模式;<br />
    文档支持多个全文检索字段(最大不超过32个);<br />
    文档支持多个额外的属性信息(例如：分组信息，时间戳等);<br />
    停止词查询;<br />
    支持单一字节编码和UTF-8编码;<br />
    原生的MySQL支持(同时支持MyISAM和InnoDB);<br />
    原生的PostgreSQL支持.</p>
<p>中文手册下载：<br />
<a href="http://www.mudbest.com/sphinx%e5%9c%a8windows%e4%b8%8b%e5%ae%89%e8%a3%85%e4%bd%bf%e7%94%a8%e6%94%af%e6%8c%81%e4%b8%ad%e6%96%87%e5%85%a8%e6%96%87%e6%a3%80%e7%b4%a2/sphinx_doc_zhcn_0-9/" rel="attachment wp-att-1806">sphinx_doc_zhcn_0.9</a></p>
<p><strong>二、Sphinx在windows上的安装</strong><br />
1.直接在http://sphinxsearch.com/downloads/release/ 找到最新的windows版本，我这里下的是sphinx-2.0.6-release-win64-id64-full，下载后解压在E:\webserver\sphinx目录下。</p>
<p>2.在E:\webserver\sphinx 下新建一个data目录用来存放索引文件，一个log目录方日志文件，复制E:\webserver\sphinx\sphinx.conf.in到E:\webserver\sphinx\sphinx.conf（注意修改文件名）。</p>
<p>3.修改D:\sphinx\bin\sphinx.conf，我这里列出需要修改的几个：</p>
<pre class="brush: plain; title: ; notranslate">
	type           = mysql # 数据源，我这里是mysql
	sql_host       = localhost # 数据库服务器
	sql_user       = root # 数据库用户名
	sql_pass       = '' # 数据库密码
	sql_db         = test # 数据库
	sql_port       = 3306 # 数据库端口
	sql_query_pre      = SET NAMES utf8 # 去掉此行前面的注释，如果你的数据库是uft8 编码的
	index test1
	{
	# 放索引的目录
	  path      = D:/sphinx/data/
	# 编码
	  charset_type     = utf-8
	  #  指定utf-8 的编码表
	  charset_table     = 0..9, A..Z-&gt;a..z, _, a..z, U+410..U+42F-&gt;U+430..U+44F, U+430..U+44F
	  # 简单分词，只支持0 和1 ，如果要搜索中文，请指定为1
	  ngram_len       = 1
	# 需要分词的字符，如果要搜索中文，去掉前面的注释
	  ngram_chars      = U+3000..U+2FA1F
	}
	# 搜索服务需要修改的部分
	searchd
	{
	  # 日志
	  log        = D:/sphinx/log/searchd.log
	  # PID file, searchd process ID file name
	  pid_file      = D:/sphinx/log/searchd.pid
	  # windows 下启动searchd 服务一定要注释掉这个
	  # seamless_rotate     = 1
	}
</pre>
<p>如果没有分布式索引，注释掉下面的内容</p>
<pre class="brush: plain; title: ; notranslate">
	# index dist1
	# {
	 # 'distributed' index type MUST be specified
	 # type    = distributed

	 # local index to be searched
	 # there can be many local indexes configured
	 # local    = test1
	 # local    = test1stemmed

	 # remote agent
	 # multiple remote agents may be specified
	 # syntax is 'hostname:port:index1,&#x5B;index2&#x5B;,...]]
	 # agent    = localhost:3313:remote1
	 # agent    = localhost:3314:remote2,remote3

	 # remote agent connection timeout, milliseconds
	 # optional, default is 1000 ms, ie. 1 sec
	 # agent_connect_timeout = 1000

	 # remote agent query timeout, milliseconds
	 # optional, default is 3000 ms, ie. 3 sec
	 # agent_query_timeout  = 3000
	# }
</pre>
<p>4.导入测试数据<br />
E:\webserver\MySQL Server 5.5\bin>mysql -uroot test < E:/webserver/sphinx/example.sql

5.建立索引
<a href="http://www.mudbest.com/wp-content/uploads/2013/03/123.jpg"><img fetchpriority="high" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/03/123-540x370.jpg" alt="123" width="540" height="370" class="alignnone size-thumbnail wp-image-1807" /></a><br />
<a href="http://www.mudbest.com/wp-content/uploads/2013/03/333.jpg"><img decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/03/333-540x370.jpg" alt="333" width="540" height="370" class="alignnone size-thumbnail wp-image-1809" /></a></p>
<p>E:\webserver\sphinx\bin>indexer.exe test1 ( 备注 :test1 为 sphinx.conf 的 index test1() )</p>
<p>6. 测试搜索‘this’<br />
<a href="http://www.mudbest.com/wp-content/uploads/2013/03/444.jpg"><img decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/03/444-540x370.jpg" alt="444" width="540" height="370" class="alignnone size-thumbnail wp-image-1810" /></a></p>
<p>7. 测试中文搜索‘我啊’<br />
<a href="http://www.mudbest.com/wp-content/uploads/2013/03/555.jpg"><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/03/555-540x370.jpg" alt="555" width="540" height="370" class="alignnone size-thumbnail wp-image-1811" /></a><br />
貌似没有搜到，这是因为 windows 命令行中的编码是 gbk ，当然搜不出来。我们可以用程序试试，在 E:\webserver\sphinx\\api 下新建一个 foo.php 的文件，注意 utf-8 编码</p>
<pre class="brush: plain; title: ; notranslate">
&lt;?php
//加载sphinx客户端
require ’sphinxapi.php’;
$s = new SphinxClient();
$s-&gt;SetServer(’localhost’,9312);
$result = $s-&gt;Query(‘中文’);
var_dump($result);
?&gt;
</pre>
<p>启动 Sphinx searchd 服务<br />
E:\webserver\sphinx\bin>searchd.exe<br />
<a href="http://www.mudbest.com/wp-content/uploads/2013/03/666.jpg"><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2013/03/666-540x370.jpg" alt="666" width="540" height="370" class="alignnone size-thumbnail wp-image-1812" /></a></p>
<p>执行 PHP 查询：<br />
访问 http://www.test.com/sphinx/api/foo.php ( 自己配置的虚拟主机 )</p>
<p>至此，windows下Sphinx服务端的配置已结束。</p>
<p>贴出以上Sphinx测试的conf配置：</p>
<pre class="brush: plain; title: ; notranslate">
#
# Sphinx configuration file sample
#
# WARNING! While this sample file mentions all available options,
# it contains (very) short helper descriptions only. Please refer to
# doc/sphinx.html for details.
#

#############################################################################
## data source definition
#############################################################################

source src1
{
	# data source type. mandatory, no default value
	# known types are mysql, pgsql, mssql, xmlpipe, xmlpipe2, odbc
	type			= mysql

	#####################################################################
	## SQL settings (for 'mysql' and 'pgsql' types)
	#####################################################################

	# some straightforward parameters for SQL source types
	sql_host		= 127.0.0.1
	sql_user		= root
	sql_pass		= shadow
	sql_db			= test
	sql_port		= 3306	# optional, default is 3306

	# UNIX socket name
	# optional, default is empty (reuse client library defaults)
	# usually '/var/lib/mysql/mysql.sock' on Linux
	# usually '/tmp/mysql.sock' on FreeBSD
	#
	# sql_sock		= /tmp/mysql.sock


	# MySQL specific client connection flags
	# optional, default is 0
	#
	# mysql_connect_flags	= 32 # enable compression

	# MySQL specific SSL certificate settings
	# optional, defaults are empty
	#
	# mysql_ssl_cert		= /etc/ssl/client-cert.pem
	# mysql_ssl_key		= /etc/ssl/client-key.pem
	# mysql_ssl_ca		= /etc/ssl/cacert.pem

	# MS SQL specific Windows authentication mode flag
	# MUST be in sync with charset_type index-level setting
	# optional, default is 0
	#
	# mssql_winauth		= 1 # use currently logged on user credentials


	# MS SQL specific Unicode indexing flag
	# optional, default is 0 (request SBCS data)
	#
	# mssql_unicode		= 1 # request Unicode data from server


	# ODBC specific DSN (data source name)
	# mandatory for odbc source type, no default value
	#
	# odbc_dsn		= DBQ=C:\data;DefaultDir=C:\data;Driver={Microsoft Text Driver (*.txt; *.csv)};
	# sql_query		= SELECT id, data FROM documents.csv


	# ODBC and MS SQL specific, per-column buffer sizes
	# optional, default is auto-detect
	#
	# sql_column_buffers	= content=12M, comments=1M


	# pre-query, executed before the main fetch query
	# multi-value, optional, default is empty list of queries
	#
	#如果是utf-8，需要取消注视这行
	# sql_query_pre		= SET NAMES utf8
	sql_query_pre		= SET NAMES utf8
	# sql_query_pre		= SET SESSION query_cache_type=OFF


	# main document fetch query
	# mandatory, integer document ID field MUST be the first selected column
	sql_query		= \
		SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
		FROM documents


	# joined/payload field fetch query
	# joined fields let you avoid (slow) JOIN and GROUP_CONCAT
	# payload fields let you attach custom per-keyword values (eg. for ranking)
	#
	# syntax is FIELD-NAME 'from'  ( 'query' | 'payload-query' ); QUERY
	# joined field QUERY should return 2 columns (docid, text)
	# payload field QUERY should return 3 columns (docid, keyword, weight)
	#
	# REQUIRES that query results are in ascending document ID order!
	# multi-value, optional, default is empty list of queries
	#
	# sql_joined_field	= tags from query; SELECT docid, CONCAT('tag',tagid) FROM tags ORDER BY docid ASC
	# sql_joined_field	= wtags from payload-query; SELECT docid, tag, tagweight FROM tags ORDER BY docid ASC


	# file based field declaration
	#
	# content of this field is treated as a file name
	# and the file gets loaded and indexed in place of a field
	#
	# max file size is limited by max_file_field_buffer indexer setting
	# file IO errors are non-fatal and get reported as warnings
	#
	# sql_file_field		= content_file_path


	# range query setup, query that must return min and max ID values
	# optional, default is empty
	#
	# sql_query will need to reference $start and $end boundaries
	# if using ranged query:
	#
	# sql_query		= \
	#	SELECT doc.id, doc.id AS group, doc.title, doc.data \
	#	FROM documents doc \
	#	WHERE id&gt;=$start AND id&lt;=$end
	#
	# sql_query_range		= SELECT MIN(id),MAX(id) FROM documents


	# range query step
	# optional, default is 1024
	#
	# sql_range_step		= 1000


	# unsigned integer attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# optional bit size can be specified, default is 32
	#
	# sql_attr_uint		= author_id
	# sql_attr_uint		= forum_id:9 # 9 bits for forum_id
	sql_attr_uint		= group_id

	# boolean attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# equivalent to sql_attr_uint with 1-bit size
	#
	# sql_attr_bool		= is_deleted


	# bigint attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# declares a signed (unlike uint!) 64-bit attribute
	#
	# sql_attr_bigint		= my_bigint_id


	# UNIX timestamp attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# similar to integer, but can also be used in date functions
	#
	# sql_attr_timestamp	= posted_ts
	# sql_attr_timestamp	= last_edited_ts
	sql_attr_timestamp	= date_added

	# string ordinal attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# sorts strings (bytewise), and stores their indexes in the sorted list
	# sorting by this attr is equivalent to sorting by the original strings
	#
	# sql_attr_str2ordinal	= author_name


	# floating point attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# values are stored in single precision, 32-bit IEEE 754 format
	#
	# sql_attr_float		= lat_radians
	# sql_attr_float		= long_radians


	# multi-valued attribute (MVA) attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# MVA values are variable length lists of unsigned 32-bit integers
	#
	# syntax is ATTR-TYPE ATTR-NAME 'from' SOURCE-TYPE &#x5B;;QUERY] &#x5B;;RANGE-QUERY]
	# ATTR-TYPE is 'uint' or 'timestamp'
	# SOURCE-TYPE is 'field', 'query', or 'ranged-query'
	# QUERY is SQL query used to fetch all ( docid, attrvalue ) pairs
	# RANGE-QUERY is SQL query used to fetch min and max ID values, similar to 'sql_query_range'
	#
	# sql_attr_multi		= uint tag from query; SELECT docid, tagid FROM tags
	# sql_attr_multi		= uint tag from ranged-query; \
	#	SELECT docid, tagid FROM tags WHERE id&gt;=$start AND id&lt;=$end; \
	#	SELECT MIN(docid), MAX(docid) FROM tags


	# string attribute declaration
	# multi-value (an arbitrary number of these is allowed), optional
	# lets you store and retrieve strings
	#
	# sql_attr_string		= stitle


	# wordcount attribute declaration
	# multi-value (an arbitrary number of these is allowed), optional
	# lets you count the words at indexing time
	#
	# sql_attr_str2wordcount	= stitle


	# combined field plus attribute declaration (from a single column)
	# stores column as an attribute, but also indexes it as a full-text field
	#
	# sql_field_string	= author
	# sql_field_str2wordcount	= title

	
	# post-query, executed on sql_query completion
	# optional, default is empty
	#
	# sql_query_post		=

	
	# post-index-query, executed on successful indexing completion
	# optional, default is empty
	# $maxid expands to max document ID actually fetched from DB
	#
	# sql_query_post_index	= REPLACE INTO counters ( id, val ) \
	#	VALUES ( 'max_indexed_id', $maxid )


	# ranged query throttling, in milliseconds
	# optional, default is 0 which means no delay
	# enforces given delay before each query step
	sql_ranged_throttle	= 0

	# document info query, ONLY for CLI search (ie. testing and debugging)
	# optional, default is empty
	# must contain $id macro and must fetch the document by that id
	sql_query_info		= SELECT * FROM documents WHERE id=$id

	# kill-list query, fetches the document IDs for kill-list
	# k-list will suppress matches from preceding indexes in the same query
	# optional, default is empty
	#
	# sql_query_killlist	= SELECT id FROM documents WHERE edited&gt;=@last_reindex


	# columns to unpack on indexer side when indexing
	# multi-value, optional, default is empty list
	#
	# unpack_zlib		= zlib_column
	# unpack_mysqlcompress	= compressed_column
	# unpack_mysqlcompress	= compressed_column_2


	# maximum unpacked length allowed in MySQL COMPRESS() unpacker
	# optional, default is 16M
	#
	# unpack_mysqlcompress_maxsize	= 16M


	#####################################################################
	## xmlpipe2 settings
	#####################################################################

	# type			= xmlpipe

	# shell command to invoke xmlpipe stream producer
	# mandatory
	#
	# xmlpipe_command		= cat @CONFDIR@/test.xml

	# xmlpipe2 field declaration
	# multi-value, optional, default is empty
	#
	# xmlpipe_field		= subject
	# xmlpipe_field		= content


	# xmlpipe2 attribute declaration
	# multi-value, optional, default is empty
	# all xmlpipe_attr_XXX options are fully similar to sql_attr_XXX
	#
	# xmlpipe_attr_timestamp	= published
	# xmlpipe_attr_uint	= author_id


	# perform UTF-8 validation, and filter out incorrect codes
	# avoids XML parser choking on non-UTF-8 documents
	# optional, default is 0
	#
	# xmlpipe_fixup_utf8	= 1
}


# inherited source example
#
# all the parameters are copied from the parent source,
# and may then be overridden in this source definition
source src1throttled : src1
{
	sql_ranged_throttle	= 100
}

#############################################################################
## index definition
#############################################################################

# local index example
#
# this is an index which is stored locally in the filesystem
#
# all indexing-time options (such as morphology and charsets)
# are configured per local index
index test1
{
	# index type
	# optional, default is 'plain'
	# known values are 'plain', 'distributed', and 'rt' (see samples below)
	# type			= plain

	# document source(s) to index
	# multi-value, mandatory
	# document IDs must be globally unique across all sources
	source			= src1

	# index files path and file name, without extension
	# mandatory, path must be writable, extensions will be auto-appended
	#path			= @CONFDIR@/data/test1
	# 放索引的目录
	path = E:/webserver/sphinx/data
	# document attribute values (docinfo) storage mode
	# optional, default is 'extern'
	# known values are 'none', 'extern' and 'inline'
	docinfo			= extern

	# memory locking for cached data (.spa and .spi), to prevent swapping
	# optional, default is 0 (do not mlock)
	# requires searchd to be run from root
	mlock			= 0

	# a list of morphology preprocessors to apply
	# optional, default is empty
	#
	# builtin preprocessors are 'none', 'stem_en', 'stem_ru', 'stem_enru',
	# 'soundex', and 'metaphone'; additional preprocessors available from
	# libstemmer are 'libstemmer_XXX', where XXX is algorithm code
	# (see libstemmer_c/libstemmer/modules.txt)
	#
	# morphology		= stem_en, stem_ru, soundex
	# morphology		= libstemmer_german
	# morphology		= libstemmer_sv
	morphology		= none

	# minimum word length at which to enable stemming
	# optional, default is 1 (stem everything)
	#
	# min_stemming_len	= 1


	# stopword files list (space separated)
	# optional, default is empty
	# contents are plain text, charset_table and stemming are both applied
	#
	# stopwords		= @CONFDIR@/data/stopwords.txt


	# wordforms file, in &quot;mapfrom &gt; mapto&quot; plain text format
	# optional, default is empty
	#
	# wordforms		= @CONFDIR@/data/wordforms.txt


	# tokenizing exceptions file
	# optional, default is empty
	#
	# plain text, case sensitive, space insensitive in map-from part
	# one &quot;Map Several Words =&gt; ToASingleOne&quot; entry per line
	#
	# exceptions		= @CONFDIR@/data/exceptions.txt


	# minimum indexed word length
	# default is 1 (index everything)
	min_word_len		= 1

	# charset encoding type
	# optional, default is 'sbcs'
	# known types are 'sbcs' (Single Byte CharSet) and 'utf-8'
	# 编码
	#charset_type		= sbcs
	charset_type     = utf-8
	
	# charset definition and case folding rules &quot;table&quot;
	# optional, default value depends on charset_type
	#
	# defaults are configured to include English and Russian characters only
	# you need to change the table to include additional ones
	# this behavior MAY change in future versions
	#
	# 'sbcs' default value is
	# charset_table		= 0..9, A..Z-&gt;a..z, _, a..z, U+A8-&gt;U+B8, U+B8, U+C0..U+DF-&gt;U+E0..U+FF, U+E0..U+FF
	#指定utf-8 的编码表
	charset_table		= 0..9, A..Z-&gt;a..z, _, a..z, U+A8-&gt;U+B8, U+B8, U+C0..U+DF-&gt;U+E0..U+FF, U+E0..U+FF
	#
	# 'utf-8' default value is
	# charset_table		= 0..9, A..Z-&gt;a..z, _, a..z, U+410..U+42F-&gt;U+430..U+44F, U+430..U+44F


	# ignored characters list
	# optional, default value is empty
	#
	# ignore_chars		= U+00AD


	# minimum word prefix length to index
	# optional, default is 0 (do not index prefixes)
	#
	# min_prefix_len		= 0


	# minimum word infix length to index
	# optional, default is 0 (do not index infixes)
	#
	# min_infix_len		= 0


	# list of fields to limit prefix/infix indexing to
	# optional, default value is empty (index all fields in prefix/infix mode)
	#
	# prefix_fields		= filename
	# infix_fields		= url, domain


	# enable star-syntax (wildcards) when searching prefix/infix indexes
	# search-time only, does not affect indexing, can be 0 or 1
	# optional, default is 0 (do not use wildcard syntax)
	#
	# enable_star		= 1


	# expand keywords with exact forms and/or stars when searching fit indexes
	# search-time only, does not affect indexing, can be 0 or 1
	# optional, default is 0 (do not expand keywords)
	#
	# expand_keywords		= 1

	
	# n-gram length to index, for CJK indexing
	# only supports 0 and 1 for now, other lengths to be implemented
	# optional, default is 0 (disable n-grams)
	#简单分词，只支持0 和1 ，如果要搜索中文，请指定为1
	# ngram_len		= 1
	ngram_len		= 1

	# n-gram characters list, for CJK indexing
	# optional, default is empty
	#
	# 需要分词的字符，如果要搜索中文，去掉前面的注释
	# ngram_chars		= U+3000..U+2FA1F
	ngram_chars		= U+3000..U+2FA1F

	# phrase boundary characters list
	# optional, default is empty
	#
	# phrase_boundary		= ., ?, !, U+2026 # horizontal ellipsis


	# phrase boundary word position increment
	# optional, default is 0
	#
	# phrase_boundary_step	= 100


	# blended characters list
	# blended chars are indexed both as separators and valid characters
	# for instance, AT&amp;T will results in 3 tokens (&quot;at&quot;, &quot;t&quot;, and &quot;at&amp;t&quot;)
	# optional, default is empty
	#
	# blend_chars		= +, &amp;, U+23


	# blended token indexing mode
	# a comma separated list of blended token indexing variants
	# known variants are trim_none, trim_head, trim_tail, trim_both, skip_pure
	# optional, default is trim_none
	#
	# blend_mode		= trim_tail, skip_pure


	# whether to strip HTML tags from incoming documents
	# known values are 0 (do not strip) and 1 (do strip)
	# optional, default is 0
	html_strip		= 0

	# what HTML attributes to index if stripping HTML
	# optional, default is empty (do not index anything)
	#
	# html_index_attrs	= img=alt,title; a=title;


	# what HTML elements contents to strip
	# optional, default is empty (do not strip element contents)
	#
	# html_remove_elements	= style, script


	# whether to preopen index data files on startup
	# optional, default is 0 (do not preopen), searchd-only
	#
	# preopen			= 1


	# whether to keep dictionary (.spi) on disk, or cache it in RAM
	# optional, default is 0 (cache in RAM), searchd-only
	#
	# ondisk_dict		= 1


	# whether to enable in-place inversion (2x less disk, 90-95% speed)
	# optional, default is 0 (use separate temporary files), indexer-only
	#
	# inplace_enable		= 1


	# in-place fine-tuning options
	# optional, defaults are listed below
	#
	# inplace_hit_gap		= 0 # preallocated hitlist gap size
	# inplace_docinfo_gap	= 0 # preallocated docinfo gap size
	# inplace_reloc_factor	= 0.1 # relocation buffer size within arena
	# inplace_write_factor	= 0.1 # write buffer size within arena


	# whether to index original keywords along with stemmed versions
	# enables &quot;=exactform&quot; operator to work
	# optional, default is 0
	#
	# index_exact_words	= 1


	# position increment on overshort (less that min_word_len) words
	# optional, allowed values are 0 and 1, default is 1
	#
	# overshort_step		= 1


	# position increment on stopword
	# optional, allowed values are 0 and 1, default is 1
	#
	# stopword_step		= 1


	# hitless words list
	# positions for these keywords will not be stored in the index
	# optional, allowed values are 'all', or a list file name
	#
	# hitless_words		= all
	# hitless_words		= hitless.txt


	# detect and index sentence and paragraph boundaries
	# required for the SENTENCE and PARAGRAPH operators to work
	# optional, allowed values are 0 and 1, default is 0
	#
	# index_sp			= 1


	# index zones, delimited by HTML/XML tags
	# a comma separated list of tags and wildcards
	# required for the ZONE operator to work
	# optional, default is empty string (do not index zones)
	#
	# index_zones		= title, h*, th
}


# inherited index example
#
# all the parameters are copied from the parent index,
# and may then be overridden in this index definition
#index test1stemmed : test1
#{
#	path			= @CONFDIR@/data/test1stemmed
#	morphology		= stem_en
#}


# distributed index example
#
# this is a virtual index which can NOT be directly indexed,
# and only contains references to other local and/or remote indexes
#index dist1
#{
#	# 'distributed' index type MUST be specified
#	type			= distributed
#
#	# local index to be searched
#	# there can be many local indexes configured
#	local			= test1
#	local			= test1stemmed
#
#	# remote agent
#	# multiple remote agents may be specified
#	# syntax for TCP connections is 'hostname:port:index1,&#x5B;index2&#x5B;,...]]'
#	# syntax for local UNIX connections is '/path/to/socket:index1,&#x5B;index2&#x5B;,...]]'
#	agent			= localhost:9313:remote1
#	agent			= localhost:9314:remote2,remote3
#	# agent			= /var/run/searchd.sock:remote4
#
#	# blackhole remote agent, for debugging/testing
#	# network errors and search results will be ignored
#	#
#	# agent_blackhole		= testbox:9312:testindex1,testindex2
#
#
#	# remote agent connection timeout, milliseconds
#	# optional, default is 1000 ms, ie. 1 sec
#	agent_connect_timeout	= 1000
#
#	# remote agent query timeout, milliseconds
#	# optional, default is 3000 ms, ie. 3 sec
#	agent_query_timeout	= 3000
#}


# realtime index example
#
# you can run INSERT, REPLACE, and DELETE on this index on the fly
# using MySQL protocol (see 'listen' directive below)
index rt
{
	# 'rt' index type must be specified to use RT index
	type			= rt

	# index files path and file name, without extension
	# mandatory, path must be writable, extensions will be auto-appended
	#path			= @CONFDIR@/data/rt
	path			= E:/webserver/sphinx/data/rt


	# RAM chunk size limit
	# RT index will keep at most this much data in RAM, then flush to disk
	# optional, default is 32M
	#
	# rt_mem_limit		= 512M

	# full-text field declaration
	# multi-value, mandatory
	rt_field		= title
	rt_field		= content

	# unsigned integer attribute declaration
	# multi-value (an arbitrary number of attributes is allowed), optional
	# declares an unsigned 32-bit attribute
	rt_attr_uint		= gid

	# RT indexes currently support the following attribute types:
	# uint, bigint, float, timestamp, string
	#
	# rt_attr_bigint		= guid
	# rt_attr_float		= gpa
	# rt_attr_timestamp	= ts_added
	# rt_attr_string		= author
}

#############################################################################
## indexer settings
#############################################################################

indexer
{
	# memory limit, in bytes, kiloytes (16384K) or megabytes (256M)
	# optional, default is 32M, max is 2047M, recommended is 256M to 1024M
	mem_limit		= 32M

	# maximum IO calls per second (for I/O throttling)
	# optional, default is 0 (unlimited)
	#
	# max_iops		= 40


	# maximum IO call size, bytes (for I/O throttling)
	# optional, default is 0 (unlimited)
	#
	# max_iosize		= 1048576


	# maximum xmlpipe2 field length, bytes
	# optional, default is 2M
	#
	# max_xmlpipe2_field	= 4M


	# write buffer size, bytes
	# several (currently up to 4) buffers will be allocated
	# write buffers are allocated in addition to mem_limit
	# optional, default is 1M
	#
	# write_buffer		= 1M


	# maximum file field adaptive buffer size
	# optional, default is 8M, minimum is 1M
	#
	# max_file_field_buffer	= 32M
}

# 搜索服务需要修改的部分
#############################################################################
## searchd settings
#############################################################################

searchd
{
	# &#x5B;hostname:]port&#x5B;:protocol], or /unix/socket/path to listen on
	# known protocols are 'sphinx' (SphinxAPI) and 'mysql41' (SphinxQL)
	#
	# multi-value, multiple listen points are allowed
	# optional, defaults are 9312:sphinx and 9306:mysql41, as below
	#
	# listen			= 127.0.0.1
	# listen			= 192.168.0.1:9312
	# listen			= 9312
	# listen			= /var/run/searchd.sock
	listen			= 9312
	listen			= 9306:mysql41

	# log file, searchd run info is logged here
	# optional, default is 'searchd.log'
	# 日志
	#log			= @CONFDIR@/log/searchd.log

	log        = E:/webserver/sphinx/log/searchd.log
	# query log file, all search queries are logged here
	# optional, default is empty (do not log queries)
	#query_log		= @CONFDIR@/log/query.log
	query_log		= E:/webserver/sphinx/log/query.log
	# client read timeout, seconds
	# optional, default is 5
	read_timeout		= 5

	# request timeout, seconds
	# optional, default is 5 minutes
	client_timeout		= 300

	# maximum amount of children to fork (concurrent searches to run)
	# optional, default is 0 (unlimited)
	max_children		= 30

	# PID file, searchd process ID file name
	# mandatory
	#pid_file		= @CONFDIR@/log/searchd.pid
	pid_file	=  E:/webserver/sphinx/log/searchd.pid


	# max amount of matches the daemon ever keeps in RAM, per-index
	# WARNING, THERE'S ALSO PER-QUERY LIMIT, SEE SetLimits() API CALL
	# default is 1000 (just like Google)
	max_matches		= 1000

	# seamless rotate, prevents rotate stalls if precaching huge datasets
	# optional, default is 1
	# windows 下启动searchd 服务一定要注释掉这个
	#seamless_rotate		= 1

	# whether to forcibly preopen all indexes on startup
	# optional, default is 1 (preopen everything)
	preopen_indexes		= 1

	# whether to unlink .old index copies on succesful rotation.
	# optional, default is 1 (do unlink)
	unlink_old		= 1

	# attribute updates periodic flush timeout, seconds
	# updates will be automatically dumped to disk this frequently
	# optional, default is 0 (disable periodic flush)
	#
	# attr_flush_period	= 900


	# instance-wide ondisk_dict defaults (per-index value take precedence)
	# optional, default is 0 (precache all dictionaries in RAM)
	#
	# ondisk_dict_default	= 1


	# MVA updates pool size
	# shared between all instances of searchd, disables attr flushes!
	# optional, default size is 1M
	mva_updates_pool	= 1M

	# max allowed network packet size
	# limits both query packets from clients, and responses from agents
	# optional, default size is 8M
	max_packet_size		= 8M

	# crash log path
	# searchd will (try to) log crashed query to 'crash_log_path.PID' file
	# optional, default is empty (do not create crash logs)
	#
	# crash_log_path		= @CONFDIR@/log/crash


	# max allowed per-query filter count
	# optional, default is 256
	max_filters		= 256

	# max allowed per-filter values count
	# optional, default is 4096
	max_filter_values	= 4096


	# socket listen queue length
	# optional, default is 5
	#
	# listen_backlog		= 5


	# per-keyword read buffer size
	# optional, default is 256K
	#
	# read_buffer		= 256K


	# unhinted read size (currently used when reading hits)
	# optional, default is 32K
	#
	# read_unhinted		= 32K


	# max allowed per-batch query count (aka multi-query count)
	# optional, default is 32
	max_batch_queries	= 32


	# max common subtree document cache size, per-query
	# optional, default is 0 (disable subtree optimization)
	#
	# subtree_docs_cache	= 4M


	# max common subtree hit cache size, per-query
	# optional, default is 0 (disable subtree optimization)
	#
	# subtree_hits_cache	= 8M


	# multi-processing mode (MPM)
	# known values are none, fork, prefork, and threads
	# optional, default is fork
	#
	workers			= threads # for RT to work


	# max threads to create for searching local parts of a distributed index
	# optional, default is 0, which means disable multi-threaded searching
	# should work with all MPMs (ie. does NOT require workers=threads)
	#
	# dist_threads		= 4


	# binlog files path; use empty string to disable binlog
	# optional, default is build-time configured data directory
	#
	# binlog_path		= # disable logging
	# binlog_path		= @CONFDIR@/data # binlog.001 etc will be created there


	# binlog flush/sync mode
	# 0 means flush and sync every second
	# 1 means flush and sync every transaction
	# 2 means flush every transaction, sync every second
	# optional, default is 2
	#
	# binlog_flush		= 2


	# binlog per-file size limit
	# optional, default is 128M, 0 means no limit
	#
	# binlog_max_log_size	= 256M


	# per-thread stack size, only affects workers=threads mode
	# optional, default is 64K
	#
	# thread_stack			= 128K


	# per-keyword expansion limit (for dict=keywords prefix searches)
	# optional, default is 0 (no limit)
	#
	# expansion_limit		= 1000


	# RT RAM chunks flush period
	# optional, default is 0 (no periodic flush)
	#
	# rt_flush_period		= 900


	# query log file format
	# optional, known values are plain and sphinxql, default is plain
	#
	# query_log_format		= sphinxql


	# version string returned to MySQL network protocol clients
	# optional, default is empty (use Sphinx version)
	#
	# mysql_version_string	= 5.0.37


	# trusted plugin directory
	# optional, default is empty (disable UDFs)
	#
	# plugin_dir			= /usr/local/sphinx/lib


	# default server-wide collation
	# optional, default is libc_ci
	#
	# collation_server		= utf8_general_ci


	# server-wide locale for libc based collations
	# optional, default is C
	#
	# collation_libc_locale	= ru_RU.UTF-8


	# threaded server watchdog (only used in workers=threads mode)
	# optional, values are 0 and 1, default is 1 (watchdog on)
	#
	# watchdog				= 1

	
	# SphinxQL compatibility mode (legacy columns and their names)
	# optional, default is 1 (old-style)
	#
	# compat_sphinxql_magics	= 1
}

# --eof--

</pre>
<p><strong>如果想作分词搜索的话，请继续往下看。</strong></p>
<p>使用 CORESEEK 分词：</p>
<p>1 、下载 http://www.coreseek.cn/products/ft_down/  (Coreseek 3.2.13 wind32即可，虽然我是win8 64位，可以向下兼容)。</p>
<p>2 、安装系统依赖的软件包。</p>
<p>系统的基础组件需要如下的软件包：<br />
   &#8211; Active Python 2.5 ( http://www.activestate.com/Products/activepython/ )<br />
   &#8211; MySQL_Python 1.2.2 (http://sourceforge.net/project/showfiles.php?group_id=22307 ） 验证 可以不装</p>
<p>安装完前面两个组件后，系统可以运行，但是需要手工修改配置文件。</p>
<p>安装配置界面需要的软件包：<br />
    &#8211; gtk-dev 2.12.9 (http://sourceforge.net/project/showfiles.php?group_id=98754 ) 验证可以不装<br />
    &#8211; pycairo 1.4.12 (http://ftp.acc.umu.se/pub/GNOME/binaries/win32/pycairo/1.4/ )<br />
    &#8211; pygobject 2.14.1 (http://ftp.acc.umu.se/pub/GNOME/binaries/win32/pygobject/2.14/ )<br />
    &#8211; pygtk 2.12.1 (http://ftp.acc.umu.se/pub/GNOME/binaries/win32/pygtk/2.12 ) )</p>
<p>如果您下载的是完整版，前面提到的全部文件应该能在preq 子目录中找到。<br />
安装前面提到的全部软件包（注意：必须先安装Python 和gtk)<br />
注意: 必须是Active Python ，Python 官方的版本缺少系统需要的Win32 扩展支持，将导致系统无法工作。<br />
注意： 完成本步后，必须重新启动您的计算机。</p>
<p>3 、解压 csft 到你认为的目录</p>
<p>4 、csft 文件内配与 sphinx 的内容大致相同 ( 配置详细见:sphinx+mysql (1) , (2) )</p>
<p>5 、创建词典文件</p>
<p>\bin\mmseg -u \data\unigram.txt    # 词库是动态的，指定目录就可以</p>
<p>·把生成的文件改名为uni.lib ，</p>
<p>6 、导入sample.sql 数据库</p>
<p>7 、建立索引 index.exe &#8211;all   （详情见 sphinx + mysql(1) ）</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
<strong>以下分支说明如下：</strong><br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>A ：</p>
<p>8 、安装SPHINXSE FOR MYSQL</p>
<p>http://www.sphinxsearch.com/downloads/mysql-5.0.45-sphinxse-0.9.8-win32.zip</p>
<p>下载后，解压然后覆盖MYSQL 目录，就OK 。 ( 注意mysql 版本 必须相同)</p>
<p>进入mysql 运行 show engines; 查看表的类型是否存在 sphinx</p>
<p>9 、创建Sphinx 存储引擎表</p>
<p>CREATE TABLE `sphinx` (</p>
<p>`id` int(11) NOT NULL,</p>
<p>`weight` int(11) NOT NULL,</p>
<p>`query` varchar(255) NOT NULL,</p>
<p>`group_id` int(11) NOT NULL,</p>
<p>KEY `Query` (`Query`)</p>
<p>) ENGINE=SPHINX CONNECTION=&#8217;sphinx://localhost:3312/test1&#8242;;</p>
<p>与一般mysql 表不同的是ENGINE=SPHINX CONNECTION=&#8217;sphinx://localhost:3312/test1&#8242;; ，这里表示这个表采用SPHINXSE 引擎，与sphinx 的连接串是&#8217;sphinx://localhost:3312/test1 ，test1 是索引名称</p>
<p>根据sphinx 官方说明，这个表必须至少有三个字段，字段起什么名称无所谓，但类型的顺序必须是integer,integer,varchar ，分别表示记录标识document ID, 匹配权重weight 与查询query ，同时document ID 与query 必须建索引。另外这个表还可以建立几个字段，这几个字段的只能是integer 或TIMESTAMP 类型，字段是与sphinx 的结果集绑定的，因此字段的名称必须与在sphinx.conf 中定义的属性名称一致，否则取出来的将是Null 值。</p>
<p>10 、MySQL SphinxSE 全文检索存储引擎SQL 语句使用方法</p>
<p>安装SphinxSE 存储引擎后首先需新建一张特殊的指定&#8221;ENGINE=SPHINX&#8221; 检索表，如下：</p>
<p>CREATE TABLE ArticleFulltext (</p>
<p>    ID          INTEGER NOT NULL,</p>
<p>    Weight      INTEGER NOT NULL,</p>
<p>    Query      VARCHAR(3072) NOT NULL,</p>
<p>    &#8230;</p>
<p>    INDEX (Query)</p>
<p>) ENGINE=SPHINX CONNECTION=&#8221;sphinx://localhost:3312/test&#8221;;</p>
<p>·其中表名和字段名可以是任意名称，但前三个属性的类型必须为INT 、INT 和VARCHAR 。也可以拥有更多的属性，类型必须为INT 或TIMESTAMP ，名称必须与Sphinx 配置文件对应，用于返回检索结果的更多信息。</p>
<p>·创建该表后即可使用如下的SQL 语句在MySQL 中进行全文检索：</p>
<p>·SELECT * FROM ArticleFulltext WHERE Query=&#8217; 全文检索条件&#8217;;</p>
<p>·查询返回结果即为全文检索的结果，包括文档ID 、权重，若ArticleFulltext 表包含了更多属性还包含命中结果的其它信息。</p>
<p>·通过SQL 联接操作可以很容易的实现融合检索，如：</p>
<p>·SELECT ID, Title</p>
<p>FROM Article, ArticleFulltext</p>
<p>WHERE ArticleFulltext.ID = Article.ID and Query = &#8216; 博客&#8217;</p>
<p>AND PublishTime > &#8216;2007-03-01&#8242; AND ReferCount > 0</p>
<p>ORDER BY Weight * 0.5 + ReferCount * 0.5;</p>
<p>·上述SQL 语句即可检索出2007 年3 月1 日以来包含&#8217; 博客&#8217; 关键字且并引用过的文章，且按全文检索权重和引用数综合计算所得的权重进行排序。</p>
<p>·由此可见，通过将全文检索系统提供的功能以存储引擎的形式嵌入到关系数据库MySQL 中可以很方便的提供融合检索功能，虽然功能限制较多，也不失为一种聪明便捷的方式。</p>
<p>11, 将SPHINX 生成WINDOWS 服务</p>
<p>searchd &#8211;install &#8211;config &#8220;csft.conf&#8221;</p>
<p>12. 启动服务 net start |searchd( 或者其它服务名)</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p>B ：</p>
<p>配置sphinx.conf 文件，支持中文编码</p>
<p>charset_type = zh_cn.utf-8</p>
<p>charset_dictpath = D:\csft3.1\bin   # 分词 lib 库文件的目录</p>
<p>min_infix_len = 0</p>
<p>以上资料均全部经受安装并测试，图没贴全，仅供参考。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mudbest.com/sphinx%e5%9c%a8windows%e4%b8%8b%e5%ae%89%e8%a3%85%e4%bd%bf%e7%94%a8%e6%94%af%e6%8c%81%e4%b8%ad%e6%96%87%e5%85%a8%e6%96%87%e6%a3%80%e7%b4%a2/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Mysql数据库访问权限控制</title>
		<link>https://www.mudbest.com/mysql%e6%95%b0%e6%8d%ae%e5%ba%93%e8%ae%bf%e9%97%ae%e6%9d%83%e9%99%90%e6%8e%a7%e5%88%b6/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Mon, 11 Mar 2013 11:34:12 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1800</guid>

					<description><![CDATA[mysql默认的root是不允许远程访问的，只能localhost本地之间的数据访问，如果要想使外部的任何一个 ... <a title="Mysql数据库访问权限控制" class="read-more" href="https://www.mudbest.com/mysql%e6%95%b0%e6%8d%ae%e5%ba%93%e8%ae%bf%e9%97%ae%e6%9d%83%e9%99%90%e6%8e%a7%e5%88%b6/" aria-label="阅读 Mysql数据库访问权限控制">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>mysql默认的root是不允许远程访问的，只能localhost本地之间的数据访问，如果要想使外部的任何一个ip访问数据权限，可执行以下语句：</p>
<p>也可针对指定ip开放访问权限。</p>
<pre class="brush: sql; title: ; notranslate">
CREATE USER 'root'@'%' IDENTIFIED BY PASSWORD '*7B2F14D9BB629E334CD49A1028BD85750F7D3530';
GRANT ALL PRIVILEGES ON * . * TO 'root'@'%' IDENTIFIED BY PASSWORD '*7B2F14D9BB629E334CD49A1028BD85750F7D3530' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
</pre>
<p>附：</p>
<p>MySQL的Grant命令(MySQL 5.0 及以上版本)。</p>
<p>MySQL 赋予用户权限命令的简单格式可概括为：<span id="more-1800"></span></p>
<pre class="brush: sql; title: ; notranslate">
grant 权限 on 数据库对象 to 用户
</pre>
<p><strong>一、grant 普通数据用户，查询、插入、更新、删除 数据库中所有表数据的权利。</strong></p>
<pre class="brush: sql; title: ; notranslate">
grant select on testdb.* to common_user@'%'
grant insert on testdb.* to common_user@'%'
grant update on testdb.* to common_user@'%'
grant delete on testdb.* to common_user@'%'
</pre>
<p>或者，用一条 MySQL 命令来替代：</p>
<pre class="brush: sql; title: ; notranslate">
grant select, insert, update, delete on testdb.* to common_user@'%'
</pre>
<p><strong>二、grant 数据库开发人员，创建表、索引、视图、存储过程、函数。。。等权限。</strong><br />
grant 创建、修改、删除 MySQL 数据表结构权限。</p>
<pre class="brush: sql; title: ; notranslate">
grant create on testdb.* to developer@'192.168.0.%';
grant alter  on testdb.* to developer@'192.168.0.%';
grant drop   on testdb.* to developer@'192.168.0.%';
</pre>
<p>grant 操作 MySQL 外键权限。</p>
<pre class="brush: sql; title: ; notranslate">
grant references on testdb.* to developer@'192.168.0.%';
</pre>
<p>grant 操作 MySQL 临时表权限。</p>
<pre class="brush: sql; title: ; notranslate">
grant create temporary tables on testdb.* to developer@'192.168.0.%';
</pre>
<p>grant 操作 MySQL 索引权限。</p>
<pre class="brush: sql; title: ; notranslate">
grant index on testdb.* to developer@'192.168.0.%';
</pre>
<p>grant 操作 MySQL 视图、查看视图源代码 权限。</p>
<pre class="brush: sql; title: ; notranslate">
grant create view on testdb.* to developer@'192.168.0.%';
grant show   view on testdb.* to developer@'192.168.0.%';
</pre>
<p>grant 操作 MySQL 存储过程、函数 权限。</p>
<pre class="brush: sql; title: ; notranslate">
grant create routine on testdb.* to developer@'192.168.0.%'; -- now, can show procedure status
grant alter  routine on testdb.* to developer@'192.168.0.%'; -- now, you can drop a procedure
grant execute on testdb.* to developer@'192.168.0.%';
</pre>
<p><strong>三、grant 普通 DBA 管理某个 MySQL 数据库的权限。</strong><br />
其中，关键字 “privileges” 可以省略。</p>
<pre class="brush: sql; title: ; notranslate">
grant all privileges on testdb to dba@'localhost'
</pre>
<p><strong>四、grant 高级 DBA 管理 MySQL 中所有数据库的权限。</strong></p>
<pre class="brush: sql; title: ; notranslate">
grant all on *.* to dba@'localhost'
</pre>
<p><strong></p>
<p>五、MySQL grant 权限，分别可以作用在多个层次上。</strong><br />
1. grant 作用在整个 MySQL 服务器上：</p>
<pre class="brush: sql; title: ; notranslate">
grant select on *.* to dba@localhost; -- dba 可以查询 MySQL 中所有数据库中的表。
grant all on *.* to dba@localhost; -- dba 可以管理 MySQL 中的所有数据库
</pre>
<p>2. grant 作用在单个数据库上：</p>
<pre class="brush: sql; title: ; notranslate">
grant select on testdb.* to dba@localhost; -- dba 可以查询 testdb 中的表。
</pre>
<p>3. grant 作用在单个数据表上：</p>
<pre class="brush: sql; title: ; notranslate">
grant select, insert, update, delete on testdb.orders to dba@localhost;
</pre>
<p>这里在给一个用户授权多张表时，可以多次执行以上语句。例如：</p>
<pre class="brush: sql; title: ; notranslate">
grant select(user_id,username) on smp.users to mo_user@'%' identified by '123345';
grant select on smp.mo_sms to mo_user@'%' identified by '123345';
</pre>
<p>4. grant 作用在表中的列上：</p>
<pre class="brush: sql; title: ; notranslate">
grant select(id, se, rank) on testdb.apache_log to dba@localhost;
</pre>
<p>5. grant 作用在存储过程、函数上：</p>
<pre class="brush: sql; title: ; notranslate">
grant execute on procedure testdb.pr_add to 'dba'@'localhost'
grant execute on function testdb.fn_add to 'dba'@'localhost'
</pre>
<p><strong>六、查看 MySQL 用户权限</strong><br />
查看当前用户（自己）权限：</p>
<pre class="brush: sql; title: ; notranslate">
show grants;
</pre>
<p>查看其他 MySQL 用户权限：</p>
<pre class="brush: sql; title: ; notranslate">
show grants for dba@localhost;
</pre>
<p>七、撤销已经赋予给 MySQL 用户权限的权限。<br />
revoke 跟 grant 的语法差不多，只需要把关键字 “to” 换成 “from” 即可：</p>
<pre class="brush: sql; title: ; notranslate">
grant  all on *.* to   dba@localhost;
revoke all on *.* from dba@localhost;
</pre>
<p>八、MySQL grant、revoke 用户权限注意事项<br />
1. grant, revoke 用户权限后，该用户只有重新连接 MySQL 数据库，权限才能生效。<br />
2. 如果想让授权的用户，也可以将这些权限 grant 给其他用户，需要选项 “grant option“</p>
<pre class="brush: sql; title: ; notranslate">
grant select on testdb.* to dba@localhost with grant option;
</pre>
<p>这个特性一般用不到。实际中，数据库权限最好由 DBA 来统一管理。</p>
<p>遇到 SELECT command denied to user &#8216;用户名&#8217;@&#8217;主机名&#8217; for table &#8216;表名&#8217; 这种错误，解决方法是需要把吧后面的表名授权，即是要你授权核心数据库也要。</p>
<p>我遇到的是SELECT command denied to user &#8216;my&#8217;@&#8217;%&#8217; for table &#8216;proc&#8217;，是调用存储过程的时候出现，原以为只要把指定的数据库授权就行了，什么存储过程、函数等都不用再管了，谁知道也要把数据库mysql的proc表授权。</p>
<p>mysql授权表共有5个表：user、db、host、tables_priv和columns_priv。</p>
<p>授权表的内容有如下用途：<br />
user Table：<br />
user表列出可以连接服务器的用户及其口令，并且它指定他们有哪种全局（超级用户）权限。在user表启用的任何权限均是全局权限，并适用于所有数据库。例如，如果你启用了DELETE权限，在这里列出的用户可以从任何表中删除记录，所以在你这样做之前要认真考虑。</p>
<p>db Table：<br />
db表列出数据库，而用户有权限访问它们。在这里指定的权限适用于一个数据库中的所有表。</p>
<p>host Table：<br />
host表与db表结合使用在一个较好层次上控制特定主机对数据库的访问权限，这可能比单独使用db好些。这个表不受GRANT和REVOKE语句的影响，所以，你可能发觉你根本不是用它。</p>
<p>tables_priv Table：<br />
tables_priv表指定表级权限，在这里指定的一个权限适用于一个表的所有列。</p>
<p>columns_priv Table：<br />
columns_priv表指定列级权限。这里指定的权限适用于一个表的特定列。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mysql内部的一些函数介绍</title>
		<link>https://www.mudbest.com/mysql%e5%86%85%e9%83%a8%e7%9a%84%e4%b8%80%e4%ba%9b%e5%87%bd%e6%95%b0%e4%bb%8b%e7%bb%8d/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Fri, 21 Dec 2012 04:55:19 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[mysql函数]]></category>
		<category><![CDATA[内置函数]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1740</guid>

					<description><![CDATA[算数运算子 +, -, *, / 除于 0 会等于 NULL。 比较运算子 任何东西跟 NULL 比较会等于  ... <a title="Mysql内部的一些函数介绍" class="read-more" href="https://www.mudbest.com/mysql%e5%86%85%e9%83%a8%e7%9a%84%e4%b8%80%e4%ba%9b%e5%87%bd%e6%95%b0%e4%bb%8b%e7%bb%8d/" aria-label="阅读 Mysql内部的一些函数介绍">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p><strong>算数运算子</strong><br />
+, -, *, /<br />
除于 0 会等于 NULL。<br />
比较运算子<br />
任何东西跟 NULL 比较会等于 NULL。<br />
比较字符串通常不需要注意大小写，如果要比较大小写，用 BINARY 关键词。<br />
<span id="more-1740"></span><br />
<strong>程序代码:</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM department
WHERE name = BINARY \'marketing\';
</pre>
<p><strong>代码:</strong></p>
<pre class="brush: sql; title: ; notranslate">
=      相等

!= 或 &lt;&gt;    不相等

&lt;      小于

&lt;=     小或等于

&gt;      大于

&gt;=     大或等于

n BETWEEN

min AND max    测试范围

n IN (set)    set 可以是一系列的数值或子查询。

&lt;=&gt;    可以比较 NULL，如果比较两个 NULL 会传回 1。

n IS NULL    测试 n 是否 NULL。

ISNULL(n)    测试 n 是否 NULL。
</pre>
<p><strong>逻辑运算子</strong></p>
<p>传回的值有 1 (true), 0 (false, 或 NULL。</p>
<p>任何不是 0 或不是 NULL 的值都是 true。</p>
<p>程序代码:</p>
<p>AND 或 &#038;&#038; n &#038;&#038; m       和</p>
<p>true &#038;&#038; true = true</p>
<p>false &#038;&#038; anything = false</p>
<p>其它会等于 NULL</p>
<p>OR 或 ||   n || m       或</p>
<p>true || anything = true</p>
<p>NULL || false = NULL</p>
<p>NULL || NULL = NULL</p>
<p>false || false = false</p>
<p>NOT 或 !    NOT n     不是</p>
<p>!true = false</p>
<p>!false = true</p>
<p>!NULL = NULL</p>
<p>XOR    n XOR m      不包含的 OR</p>
<p>true XOR true = false</p>
<p>true XOR false = true</p>
<p>false XOR true = true</p>
<p>NULL XOR n = NULL</p>
<p>n XOR NULL = NULL</p>
<p><strong>控制流向的函式</strong></p>
<p>IF (e1, e2, e3)</p>
<p>如果 e1 是 true，IF 会传回 e2，不然会传回 e3。</p>
<p>CASE value</p>
<p>WHEN [compare-value] THEN result</p>
<p>[WHEN [compare-value] THEN result &#8230;]</p>
<p>[ELSE result]</p>
<p>END</p>
<p>或是</p>
<p>CASE</p>
<p>WHEN [condition] THEN result</p>
<p>[WHEN [condition] THEN result &#8230;]</p>
<p>[ELSE result]</p>
<p>END</p>
<p>程序代码:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT workdate, CASE

WHEN workdate &lt; 2000-01-01 THEN &quot;archived&quot;

WHEN workdate &lt; 2003-01-01 THEN &quot;old&quot;

ELSE &quot;current&quot;

END

FROM assignment;
</pre>
<p><strong>字符串函式</strong></p>
<p>concat(s1, s2, &#8230;) &#8211; 连接字符串 s1 和 s2&#8230;</p>
<p>conv(n, original_base, new_base) &#8211; 转换数字 n 从本来的 base 到新的 base</p>
<p>length(s) &#8211; 找字符串的长度</p>
<p>load_file(filename) &#8211; 依照字符串传回档案的内容</p>
<p>locate(needle, haystack, position) &#8211; 传回 needle 字符串的开始位置，在 haystack 字符串里，从 position 开始</p>
<p>lower(s) and upper(s) &#8211; 转换 s 到小写或大写</p>
<p>quote(s) &#8211; 跳脱 s 字符串，让它可以安全输入数据库</p>
<p>replace(target, find, replace) &#8211; 传回 target 字符串，将 find 字符串覆盖成 replace 字符串</p>
<p>soundex(s) &#8211; 传回跟 s 类似的 soundex 字符串。soundex 是字符串的发音</p>
<p>substring(s, position, length) &#8211; 传回字符串里的字符串，s 是本来的字符串，position 是开始的位置，length 是传回的字数</p>
<p>trim(s) &#8211; 移除开头跟字尾的空格符。也可以用 rtrim() 或 ltrim()</p>
<p><strong>字符串比较的函式</strong></p>
<p>LIKE &#8211; 利用通配字符来进行比较</p>
<p>RLIKE &#8211; 利用正规表示法来进行比较</p>
<p>STRCMP &#8211; 比较字符串，类似 C 里面的 strcmp()</p>
<p>MATCH &#8211; 进行 full-text 比较</p>
<p>利用通配字符来进行比较</p>
<p>程序代码:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT *

FROM department

WHERE name LIKE \'%research%\';
</pre>
<p>% 会吻合任何字数，包括 0。</p>
<p>_ 会吻合单一字数， _at 会吻合 cat, mat, bat&#8230;</p>
<p>利用正规表示法来进行比较</p>
<p>RLIKE 可以用来吻合正规表示法。</p>
<p>\&#8217;cat\&#8217; 会吻合 \&#8217;catacomb\&#8217; 和 \&#8217;the cat sat on the mat\&#8217;。</p>
<p>如果只要吻合 \&#8217;cat\&#8217;，用 \&#8217;^cat$\&#8217;。</p>
<p>^ 表示在吻合的字符串开头是 \&#8217;cat\&#8217;。</p>
<p>$ 表示在吻合的字符串最后是 \&#8217;cat\&#8217;。</p>
<p>. 可以用来代表通配字符，\&#8217;.at\&#8217; 会吻合 \&#8217;cat\&#8217;, \&#8217;bat\&#8217;, \&#8217;mat\&#8217;。</p>
<p>* 表示字符可以出现零或多次，\&#8217;n*\&#8217; 会吻合 \&#8217;\&#8217;, \&#8217;nn\&#8217;, \&#8217;nnn\&#8217;。</p>
<p>() 会归类字符，\'(cat)*\&#8217; 会吻合 \&#8217;\&#8217;, \&#8217;cat\&#8217;, \&#8217;catcat\&#8217;, \&#8217;catcatcat\&#8217;。</p>
<p>.* 会吻合任何字或字符串。</p>
<p>+ 表示在他之后的字或字符串会重复一或多次。</p>
<p>? 表示吻合一或零次。</p>
<p>列出特定的范围，\'(cat)(2,4)\&#8217; 会吻合 \&#8217;catcat\&#8217;, \&#8217;catcatcat\&#8217;, 和 \&#8217;catcatcatcat\&#8217;。</p>
<p>[] 可以列出一系列的文字，\'[a-z]\&#8217; 会吻合任何字母，\'[a-z]*\&#8217; 会吻合任何数量的字母。</p>
<p>文字类别，[[:alnum:]] 会吻合任何字母和数字的文字。</p>
<p>程序代码:</p>
<p>SELECT *</p>
<p>FROM department</p>
<p>WHERE name RLIKE \&#8217;an\&#8217;;</p>
<p>这会吻合全部有包括 \&#8217;an\&#8217; 的部门。</p>
<p>用 STRCMP() 来比较字符串</p>
<p>STRCMP(s1, s2)</p>
<p>如果字符串相同会传回 0，-1 如果 s1 比 s2 小 (s1 比 s2 早出现)。</p>
<p>1 如果 s1 比 s2 大 (s1 比 s2 晚出现)。</p>
<p><strong>程序代码:</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT STRCMP(\'cat\', \'cat\');
</pre>
<p>// 传回 0</p>
<pre class="brush: sql; title: ; notranslate">
SELECT STRCMP(\'cat\', \'dog\');
</pre>
<p>// 传回 -1</p>
<pre class="brush: sql; title: ; notranslate">
SELECT STRCMP(\'cat\', \'ant\');
</pre>
<p>// 传回 1</p>
<p><strong>数字函式</strong></p>
<p>abs(n) 传回 n 的正数</p>
<p>ceiling(n) n rounded up to the nearest integer</p>
<p>floor(n) n rounded down to the nearest integer</p>
<p>mod(n,m) 和 div 这两个函式会将 n 除于 m。div 传回商数，mod() 会传回剩余数。</p>
<p>power(n,m) n to the power of m</p>
<p>rand(n) 传回 0 到 1 的随意数。n 可以不提供，如果提供会用来产生随意数。</p>
<p>相同的 n 会产生相同的随意数。</p>
<p>round(n[,d]) n rounded to the nearest integer. if supply d, n will be rounded to d decimal places.</p>
<p>sqrt(n) 传回 n 的平方</p>
<p>mod() 可以是 mod(9,2) 或 9 mod 2 或 9 % 2。</p>
<p>div 只能用 9 div 2。</p>
<p><strong>程序代码:</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT 9 mod 2;
</pre>
<p>// 传回 1</p>
<pre class="brush: sql; title: ; notranslate">
SELECT 9 div 2;
</pre>
<p>// 传回 4</p>
<p><strong>日期和时间函式</strong></p>
<p>adddate(date, INTERVAL n type) 和 subdate(date, INTERVAL n type)</p>
<p>这些函式可以用来增加和减少日期。从 date 的日期开始计算，然后增加或减少 INTERVAL 后的日期范围。</p>
<p>你必须提供 n 和他的类型。类型可以是 SECOND, MINUTE, HOUR, DAY, MONTH, YEAR, MINUTE:SECOND (m:s),</p>
<p>HOUR:MINUTE (h:m), DAY_HOUR(d h), YEAR_MONTH (y-m), HOUR_SECOND (h:m:s), DAY_MINUTE (d h:m),</p>
<p>DAY_SECOND (d h:m:s)。</p>
<p>curdate(), curtime(), now()</p>
<p>这些函式会传回目前的日期，目前的时间，还有时间和日期。</p>
<p>date_format(date, format) 和 time_format(time, format)</p>
<p>这些可以用来改变日期和时间的格式。</p>
<p>你必须提供格式的字符串，譬如说 date_format(workdate, \&#8217;%W %D of %M, %Y\&#8217;)，</p>
<p>这会给你 \&#8217;Monday 16th of June, 2003)。</p>
<p>全部可用的格式请看 MySQL 的手册。</p>
<p>dayname(date)</p>
<p>传回日期的名称，例如 Monday。</p>
<p>extract(type FROM date)</p>
<p>传回 date 的日期，譬如说 YEAR，他就会传回那个日期的年数。</p>
<p>函式可用的类型跟 adddate() 和 subdate() 的类型相同。</p>
<p>unix_timestamp([date])</p>
<p>传回目前的 Unix 时间。如果跟 date 一起使用，传回的日期会从 date 的日期开始计算。</p>
<p>范例：</p>
<p><strong>程序代码:</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT adddate(&quot;1999-01-01&quot;, INTERVAL &quot;1-6&quot; YEAR_MONTH);
</pre>
<p>// 传回 2000-07-01</p>
<pre class="brush: sql; title: ; notranslate">
SELECT unix_timestamp(adddate(&quot;1999-01-01&quot;, INTERVAL &quot;1-6&quot; YEAR_MONTH);
</pre>
<p>// 传回 962373600</p>
<p>可以用 PHP 的 date() 函式来将 Unix 的时间格式化。</p>
<p><strong>cast 函式</strong></p>
<p>cast 可以用来改变类型，用 cast() 和 convert() 函式。</p>
<p>两个函式相同，但是不同的语法构造。</p>
<p>cast(expression AS type)</p>
<p>convert(expression, type)</p>
<p>cast() 是依照 ANSI 的规格，convert() 是依照 ODBC 的规格。</p>
<p>类型可以是 BINARY, CHAR, DATE, DATETIME, SIGNED (INTEGER), 和 UNSIGNED (INTEGER)。</p>
<p>通常 MySQL 会自动帮你改变类型。</p>
<p><strong>其它函式</strong></p>
<p>benchmark(count, expression)</p>
<p>这个函式是用来测试查询的速度，只会传回 0 值。</p>
<p>encrypt(s[,salt])</p>
<p>将 s 加密用 Unix 的加密系统。salt 字符串是两个字符的字符串，可以不用。</p>
<p>如果没有 crypt 功能，像在 Windows 系统，这个函式会传回 NULL。</p>
<p>found_rows()</p>
<p>传回字段的数量，如果没有用 LIMIT。</p>
<p>只有在 SELECT 里使用 SQL_CALC_FOUND_ROWS 才能用这个函式。</p>
<p>last_insert_id()</p>
<p>传回最后产生的 AUTO_INCREMENT 值。</p>
<p>md5(s)</p>
<p>传回 128bit MD5 的加密字符串。</p>
<p>password(s)</p>
<p>计算 s 的密码，不建议用这个函式来储存密码。</p>
<p>用于 GROUP BY 的函式</p>
<p>这些还是专门为了 GROUP BY 而写的。</p>
<p>avg(column) &#8211; 传回字段的平均值</p>
<p>count(column) &#8211; 传回字段的数量</p>
<p>min(column) &#8211; 传回字段的最小值</p>
<p>max(column) &#8211; 传回字段的最大值</p>
<p>std(column) &#8211; 传回字段的标准差</p>
<p>sum(column) &#8211; 传回字段的总数 </p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mysql字段的增加和删除</title>
		<link>https://www.mudbest.com/mysql%e5%ad%97%e6%ae%b5%e7%9a%84%e5%a2%9e%e5%8a%a0%e5%92%8c%e5%88%a0%e9%99%a4/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Thu, 20 Dec 2012 11:03:28 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[字段修改]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1738</guid>

					<description><![CDATA[本来就没有记单词的习惯，平时触及Mysql操作不是很多，很多语句也就不怎么记得了，偶尔的处理一下这样的需求，那 ... <a title="Mysql字段的增加和删除" class="read-more" href="https://www.mudbest.com/mysql%e5%ad%97%e6%ae%b5%e7%9a%84%e5%a2%9e%e5%8a%a0%e5%92%8c%e5%88%a0%e9%99%a4/" aria-label="阅读 Mysql字段的增加和删除">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>本来就没有记单词的习惯，平时触及Mysql操作不是很多，很多语句也就不怎么记得了，偶尔的处理一下这样的需求，那就要语句嘛，好吧，下面贴起来。<span id="more-1738"></span></p>
<p>增加字段的语句：</p>
<pre class="brush: sql; title: ; notranslate">
alter table `user_movement_log`   
Add column GatewayId int not null default 0 AFTER `Regionid` (在哪个字段后面添加)
</pre>
<p>删除字段的语句：</p>
<pre class="brush: sql; title: ; notranslate">
alter table `user_movement_log` drop column Gatewayid  
</pre>
<p>调整字段顺序的语句：</p>
<pre class="brush: sql; title: ; notranslate">
ALTER TABLE `user_movement_log` CHANGE `GatewayId` `GatewayId` int not null default 0 AFTER RegionID  

//主键  

alter table tabelname add new_field_id int(5) unsigned default 0 not null auto_increment ,add primary key (new_field_id);//增加一个新列  

alter table t2 add d timestamp;  
alter table infos add ex tinyint not null default '0';//删除列  

alter table t2 drop column c;//重命名列  

alter table t1 change a b integer;  
//改变列的类型  

alter table t1 change b b bigint not null;  
alter table infos change list list tinyint not null default '0';  
//重命名表  

alter table t1 rename t2;加索引  

mysql&gt; alter table tablename change depno depno int(5) not null;  
mysql&gt; alter table tablename add index 索引名 (字段名1&#x5B;，字段名2 …]);  
mysql&gt; alter table tablename add index emp_name (name);加主关键字的索引  

mysql&gt; alter table tablename add primary key(id);加唯一限制条件的索引  

mysql&gt; alter table tablename add unique emp_name2(cardnumber);删除某个索引  

mysql&gt;alter table tablename drop index emp_name;修改表：  
</pre>
<p>控制台增加字段：</p>
<pre class="brush: sql; title: ; notranslate">
mysql&gt; ALTER TABLE table_name ADD field_name field_type;修改原字段名称及类型：  
mysql&gt; ALTER TABLE table_name CHANGE old_field_name new_field_name field_type;删除字段：   
mysql&gt; ALTER TABLE table_name DROP field_name; 
</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>MySQL Workbench的使用</title>
		<link>https://www.mudbest.com/mysql-workbench%e7%9a%84%e4%bd%bf%e7%94%a8/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Wed, 21 Nov 2012 03:18:35 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[分享]]></category>
		<category><![CDATA[MySQL Workbench]]></category>
		<category><![CDATA[数据库]]></category>
		<category><![CDATA[设计]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1672</guid>

					<description><![CDATA[MySQL Workbench 是 MySQL AB 最近释放的可视数据库设计工具。这个工具是设计 MySQL ... <a title="MySQL Workbench的使用" class="read-more" href="https://www.mudbest.com/mysql-workbench%e7%9a%84%e4%bd%bf%e7%94%a8/" aria-label="阅读 MySQL Workbench的使用">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>MySQL Workbench 是 MySQL AB 最近释放的可视数据库设计工具。这个工具是设计 MySQL 数据库的专用工具。<br />
在 MySQL Workbench 中建立的被称之为物理数据模型。一个物理数据模型是针对一个特定 RDBMS 产品的数据模型；本文中的模型将具有一些 MySQL 的独特规范。我们可以使用它生成（forward-engineer）数据库对象，除了包含表和列（字段）外，也可以包含视图。<br />
MySQL Workbench 拥有很多的功能和特性；这篇由 Djoni Darmawikarta写的<span id="more-1672"></span>文章通过一个示例展现了其中的一些。我们将针对一个订单系统建立一个物理数据模型，这里的订单系统可以是销售单也可以是订单，并且使用  forward-engineer（正向引擎） 将我们的模型生成为一个 MySQL 数据库。<br />
我们的示例中使用 MySQL Workbench 创建的物理模型看上去就像下图这样：</p>
<p>小知识:<br />
mysql的pk nn uq bin un zf ai各代表的意思<br />
[intrinsic column flags] (基本字段类型标识)</p>
<p>&#8211; PK: primary key (column is part of a pk) 主键<br />
&#8211; NN: not null (column is nullable) 非空<br />
&#8211; UQ: unique (column is part of a unique key) 唯一<br />
&#8211; AI: auto increment (the column is auto incremented when rows are inserted) 自增</p>
<p>[additional data type flags, depend on used data type] 扩展数据类型标记</p>
<p>&#8211; BIN: binary (if dt is a blob or similar, this indicates that is binary data, rather than text) 二进制(比text更大的二进制数据)<br />
&#8211; UN: unsigned (for integer types, see docs: “10.2. Numeric Types”) 整数<br />
&#8211; ZF: zero fill (rather a display related flag, see docs: “10.2. Numeric Types”)值中最有意义的字节总为0，并且不保存。 </p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image1.png" alt="" title="workbench-article-image1" width="500" height="343" class="alignnone size-full wp-image-1673" /></p>
<p>索引简单介绍：<br />
PRIMARY, INDEX, UNIQUE 这3种是一类<br />
PRIMARY 主键。 就是 唯一 且 不能为空。<br />
INDEX 索引，普通的<br />
UNIQUE 唯一索引。 不允许有重复。<br />
FULLTEXT 是全文索引，用于在一篇文章中，检索文本信息的。</p>
<p>举个例子来说，比如你在为某商场做一个会员卡的系统。<br />
这个系统有一个会员表<br />
有下列字段：<br />
会员编号   INT<br />
会员姓名   VARCHAR(10)<br />
会员身份证号码   VARCHAR(18)<br />
会员电话   VARCHAR(10)<br />
会员住址   VARCHAR(50)<br />
会员备注信息  TEXT</p>
<p>那么这个 会员编号，作为主键，使用 PRIMARY<br />
会员姓名 如果要建索引的话，那么就是普通的 INDEX<br />
会员身份证号码   如果要建索引的话，那么可以选择 UNIQUE （唯一的，不允许重复）<br />
会员备注信息 ， 如果需要建索引的话，可以选择 FULLTEXT，全文搜索。</p>
<p>不过 FULLTEXT 用于搜索很长一篇文章的时候，效果最好。<br />
用在比较短的文本，如果就一两行字的，普通的 INDEX 也可以。</p>
<p>创建订单方案(ORDER Schema)<br />
首先让我们来创建一个保存订单物理模型的方案。点击 + 按钮（红色标注的地方）</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image2.png" alt="" title="workbench-article-image2" width="500" height="343" class="alignnone size-full wp-image-1674" /></p>
<p>更改新的方案默认名称为订单。注意，当你键入方案名时，在 Physical Schemata 上的标签名也会随之改变——这是一个很好的特性。</p>
<p>订单方案被增加到目录（Catalog）中 (图中红色圈住的部分)。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image3.png" alt="" title="workbench-article-image3" width="500" height="343" class="alignnone size-full wp-image-1675" /></p>
<p>重命名方案后关闭 schema 窗口。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image4.png" alt="" title="workbench-article-image4" width="500" height="145" class="alignnone size-full wp-image-1676" /></p>
<p>创建订单表<br />
我们现在创建订单模型中的三个表：ORDER 表以及它的两个子表 SALES_ORDER 和PURCHASE_ORDER。首先，确信你已经选择了 ORDER 方案的标签，这样，我们创建的表才会包含于这个方案。</p>
<p>我们将要创建的表是作为 EER 图表展示的(EER = Enhanced Entity Relationship)。所以，双击 Add Diagram 按钮。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image5.png" alt="" title="workbench-article-image5" width="223" height="265" class="alignnone size-full wp-image-1677" /></p>
<p>单击 Table 图标，然后移动鼠标到 EER Diagram 区域，在你想放置第一个表的位置上单击鼠标。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image6.png" alt="" title="workbench-article-image6" width="194" height="188" class="alignnone size-full wp-image-1678" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image7.png" alt="" title="workbench-article-image7" width="432" height="298" class="alignnone size-full wp-image-1679" /></p>
<p>对于其他两个表，重复上面的操作。你可以通过拖拽来移动表的位置。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image8.png" alt="" title="workbench-article-image8" width="500" height="434" class="alignnone size-full wp-image-1680" srcset="https://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image8.png 500w, https://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image8-495x430.png 495w" sizes="auto, (max-width: 500px) 100vw, 500px" /></p>
<p>下一步，我们要对 table1 做一些操作，这些操作是通过 Workbench 的表编辑器完成的。要打开表编辑器，只需右键选择 table1 并选择 Edit Table 菜单。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image9.png" alt="" title="workbench-article-image9" width="500" height="249" class="alignnone size-full wp-image-1681" /></p>
<p>键入 table1 的表名 ORDER 。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image10.png" alt="" title="workbench-article-image10" width="433" height="335" class="alignnone size-full wp-image-1682" /></p>
<p>接下来，增加列（字段）。选择 Columns 标签。将列名(字段名) idORDER 更改为  ORDER_NO.</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image11.png" alt="" title="workbench-article-image11" width="500" height="154" class="alignnone size-full wp-image-1683" /></p>
<p>在下拉列表框中选择数据类型 INT 。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image12.png" alt="" title="workbench-article-image12" width="500" height="497" class="alignnone size-full wp-image-1684" srcset="https://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image12.png 500w, https://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image12-432x430.png 432w" sizes="auto, (max-width: 500px) 100vw, 500px" /></p>
<p>我们希望 ORDER_NO 列的值可以被 MySQL 数据库自动控制，所以，我们选定 AI 列 (Auto Increment——自增量).</p>
<p>AI 是 MySQL 数据库的一个特性。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image13.png" alt="" title="workbench-article-image13" width="457" height="125" class="alignnone size-full wp-image-1685" /></p>
<p>你也可以指定表的其他物理属性，例如它的 Collation 属性；当然可以指定表的其他高级选项，例如 trigger 和 portioning （分别对应 Trigger 和 Partioning 标签）。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image14.png" alt="" title="workbench-article-image14" width="277" height="156" class="alignnone size-full wp-image-1686" /></p>
<p>注意，这时，在 diagram 中我们表 table1 已经改变为 ORDER，并且，它有一个列（字段）ORDER_NO。在目录中，你也可以看到有三个表。</p>
<p>在表右侧的黑点，表示它们包含在一个图表中。</p>
<p>如果你展开 ORDER ，你可以看到 ORDER_NO 列。因为我们定义它为主键，所以在它左侧有一个 key 图标</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image16.png" alt="" title="workbench-article-image16" width="181" height="163" class="alignnone size-full wp-image-1687" /></p>
<p>回到表设计器，增加其他两列（字段）：ORDER_DATE 和 ORDER_TYPE。ORDER_TYPE 可以有两个值：S 表示销售订单，P 表示采购订单。由于销售订单是更常用的，所以我们指定列（字段）的默认值为 S 。</p>
<p>你可以在最后一列的下面白色区域双击鼠标来增加下一个字段</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image17.png" alt="" title="workbench-article-image17" width="457" height="127" class="alignnone size-full wp-image-1688" /></p>
<p>使用同样的方式来创建 SALES_ORDER 表及其中的列（字段）。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image18.png" alt="" title="workbench-article-image18" width="500" height="337" class="alignnone size-full wp-image-1689" /></p>
<p>最后，创建 PURCHASE_ORDER 表及其中的列（字段）。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image19.png" alt="" title="workbench-article-image19" width="500" height="345" class="alignnone size-full wp-image-1690" /></p>
<p>创建关系<br />
我们已经创建了三个表。到这里并没有结束；我们仍旧需要创建它们的 关系。</p>
<p>SALES_ORDER 是 ORDER 的子表，意味着它们是 1:1 ，SALES_ORDER 为子表， ORDER 为父表，并将 ORDER 的键移动到 SALES_ORDER 。所以，选择（单击）1:1 identifying relationship 图标，然后在 SALES_ORDER 表上单击，再在 ORDER 表上单击。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image20.png" alt="" title="workbench-article-image20" width="278" height="231" class="alignnone size-full wp-image-1691" /></p>
<p>注意，当你在单击表时，图标将变为带有 1:1 关系的手型。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image21.png" alt="" title="workbench-article-image21" width="229" height="219" class="alignnone size-full wp-image-1692" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image22.png" alt="" title="workbench-article-image22" width="217" height="205" class="alignnone size-full wp-image-1693" /></p>
<p>1:1 关系就是这样设置的；ORDER_NO 主键被移动到 SALES_ORDER 表并作为它的主键。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image23.png" alt="" title="workbench-article-image23" width="225" height="278" class="alignnone size-full wp-image-1694" /></p>
<p>下一步，创建 PURCHASE_ORDER 到 ORDER 的关系，它仍旧是 1:1 关系。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image24.png" alt="" title="workbench-article-image24" width="500" height="343" class="alignnone size-full wp-image-1695" /></p>
<p>我们现在已经完成了表及表之间关系的设计；将我们的模型保存为 ORDER.mwb.</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image25.png" alt="" title="workbench-article-image25" width="276" height="408" class="alignnone size-full wp-image-1696" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image26.png" alt="" title="workbench-article-image26" width="500" height="342" class="alignnone size-full wp-image-1697" /></p>
<p>生成 DDL 和数据库<br />
最终在本文设计数据模型的目的是为了建立 MySQL 数据库。我们将首先生成 DDL(SQL CREATE script)，然后执行这个脚本。</p>
<p>从 File | Export 菜单中，选择 Forward Engineer SQL CREATE Script.</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image27.png" alt="" title="workbench-article-image27" width="500" height="356" class="alignnone size-full wp-image-1698" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image28.png" alt="" title="workbench-article-image28" width="500" height="378" class="alignnone size-full wp-image-1699" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image29.png" alt="" title="workbench-article-image29" width="500" height="383" class="alignnone size-full wp-image-1700" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image30.png" alt="" title="workbench-article-image30" width="500" height="283" class="alignnone size-full wp-image-1701" /></p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image31.png" alt="" title="workbench-article-image31" width="500" height="408" class="alignnone size-full wp-image-1702" /></p>
<p>你也可以在其中来查看表是否已经被创建。</p>
<p><img loading="lazy" decoding="async" src="http://www.mudbest.com/wp-content/uploads/2012/11/workbench-article-image32.png" alt="" title="workbench-article-image32" width="333" height="325" class="alignnone size-full wp-image-1703" /></p>
<p>全图文演示了在 MySQL Workbench 中如何可视的建立 MySQL 物理数据模型，并使用它来创建一个 MySQL 数据库。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mysql一些细节性的优化</title>
		<link>https://www.mudbest.com/mysql%e4%b8%80%e4%ba%9b%e7%bb%86%e8%8a%82%e6%80%a7%e7%9a%84%e4%bc%98%e5%8c%96/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Fri, 19 Oct 2012 06:15:48 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[优化]]></category>
		<category><![CDATA[最优]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1586</guid>

					<description><![CDATA[1、对查询进行优化，应尽量避免全表扫描，首先应考虑在 where 及 order by 涉及的列上建立索引。  ... <a title="Mysql一些细节性的优化" class="read-more" href="https://www.mudbest.com/mysql%e4%b8%80%e4%ba%9b%e7%bb%86%e8%8a%82%e6%80%a7%e7%9a%84%e4%bc%98%e5%8c%96/" aria-label="阅读 Mysql一些细节性的优化">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>1、对查询进行优化，应尽量避免全表扫描，首先应考虑在 where 及 order by 涉及的列上建立索引。</p>
<p>2、应尽量避免在 where 子句中对字段进行 null 值判断，否则将导致引擎放弃使用索引而进行全表扫描，如：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num is null
</pre>
<p>可以在num上设置默认值0，确保表中num列没有null值，然后这样查询：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num=0
</pre>
<p>3、应尽量避免在 where 子句中使用!=或<>操作符，否则<span id="more-1586"></span>将引擎放弃使用索引而进行全表扫描。</p>
<p>4、应尽量避免在 where 子句中使用 or 来连接条件，否则将导致引擎放弃使用索引而进行全表扫描，如：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num=10 or num=20
</pre>
<p>可以这样查询：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num=10
union all
select id from t where num=20
</pre>
<p>5、in 和 not in 也要慎用，否则会导致全表扫描，如：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num in(1,2,3)
</pre>
<p>对于连续的数值，能用 between 就不要用 in 了：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num between 1 and 3
</pre>
<p>6、下面的查询也将导致全表扫描：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where name like '%abc%'
</pre>
<p>若要提高效率，可以考虑全文检索。</p>
<p>7、如果在 where 子句中使用参数，也会导致全表扫描。因为SQL只有在运行时才会解析局部变量，但优化程序不能将访问计划的选择推迟到运行时；它必须在编译时进行选择。然而，如果在编译时建立访问计划，变量的值还是未知的，因而无法作为索引选择的输入项。如下面语句将进行全表扫描：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num=@num 
#&lt;mailto:num=@num&gt;
</pre>
<p>可以改为强制查询使用索引：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t with(index(索引名)) where num=@num 
#&lt;mailto:num=@num&gt;
</pre>
<p>8、应尽量避免在 where 子句中对字段进行表达式操作，这将导致引擎放弃使用索引而进行全表扫描。如：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num/2=100
</pre>
<p>应改为:</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where num=100*2
</pre>
<p>9、应尽量避免在where子句中对字段进行函数操作，这将导致引擎放弃使用索引而进行全表扫描。如：</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where substring(name,1,3)='abc'
#-name以abc开头的id
select id from t where datediff(day,createdate,'2005-11-30') = 0 
#-'005-11-30'生成的id
</pre>
<p>应改为:</p>
<pre class="brush: sql; title: ; notranslate">
select id from t where name like 'abc%'
select id from t where createdate &gt;= '2005-11-30' and createdate &lt; '2005-12-1'
</pre>
<p>10、不要在 where 子句中的“=”左边进行函数、算术运算或其他表达式运算，否则系统将可能无法正确使用索引。</p>
<p>11、在使用索引字段作为条件时，如果该索引是复合索引，那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引，否则该索引将不会被使用，并且应尽可能的让字段顺序与索引顺序相一致。</p>
<p>12、不要写一些没有意义的查询，如需要生成一个空表结构：</p>
<pre class="brush: sql; title: ; notranslate">
select col1,col2 into #t from t where 1=0
</pre>
<p>这类代码不会返回任何结果集，但是会消耗系统资源的，应改成这样：</p>
<pre class="brush: sql; title: ; notranslate">
create table #t(…)
</pre>
<p>13、很多时候用 exists 代替 in 是一个好的选择：</p>
<pre class="brush: sql; title: ; notranslate">
select num from a where num in(select num from b)
</pre>
<p>用下面的语句替换：</p>
<pre class="brush: sql; title: ; notranslate">
select num from a where exists(select 1 from b where num=a.num)
</pre>
<p>14、并不是所有索引对查询都有效，SQL是根据表中数据来进行查询优化的，当索引列有大量数据重复时，SQL查询可能不会去利用索引，如一表中有字段sex，male、female几乎各一半，那么即使在sex上建了索引也对查询效率起不了作用。</p>
<p>15、索引并不是越多越好，索引固然可以提高相应的 select 的效率，但同时也降低了 insert 及 update 的效率，因为 insert 或 update 时有可能会重建索引，所以怎样建索引需要慎重考虑，视具体情况而定。一个表的索引数最好不要超过6个，若太多则应考虑一些不常使用到的列上建的索引是否有必要。</p>
<p>16、应尽可能的避免更新 clustered 索引数据列，因为 clustered 索引数据列的顺序就是表记录的物理存储顺序，一旦该列值改变将导致整个表记录的顺序的调整，会耗费相当大的资源。若应用系统需要频繁更新 clustered 索引数据列，那么需要考虑是否应将该索引建为 clustered 索引。</p>
<p>17、尽量使用数字型字段，若只含数值信息的字段尽量不要设计为字符型，这会降低查询和连接的性能，并会增加存储开销。这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符，而对于数字型而言只需要比较一次就够了。</p>
<p>18、尽可能的使用 varchar/nvarchar 代替 char/nchar ，因为首先变长字段存储空间小，可以节省存储空间，其次对于查询来说，在一个相对较小的字段内搜索效率显然要高些。</p>
<p>19、任何地方都不要使用 select * from t ，用具体的字段列表代替“*”，不要返回用不到的任何字段。</p>
<p>20、尽量使用表变量来代替临时表。如果表变量包含大量数据，请注意索引非常有限（只有主键索引）。</p>
<p>21、避免频繁创建和删除临时表，以减少系统表资源的消耗。</p>
<p>22、临时表并不是不可使用，适当地使用它们可以使某些例程更有效，例如，当需要重复引用大型表或常用表中的某个数据集时。但是，对于一次性事件，最好使用导出表。</p>
<p>23、在新建临时表时，如果一次性插入数据量很大，那么可以使用 select into 代替 create table，避免造成大量 log ，以提高速度；如果数据量不大，为了缓和系统表的资源，应先create table，然后insert。</p>
<p>24、如果使用到了临时表，在存储过程的最后务必将所有的临时表显式删除，先 truncate table ，然后 drop table ，这样可以避免系统表的较长时间锁定。</p>
<p>25、尽量避免使用游标，因为游标的效率较差，如果游标操作的数据超过1万行，那么就应该考虑改写。</p>
<p>26、使用基于游标的方法或临时表方法之前，应先寻找基于集的解决方案来解决问题，基于集的方法通常更有效。</p>
<p>27、与临时表一样，游标并不是不可使用。对小型数据集使用 FAST_FORWARD 游标通常要优于其他逐行处理方法，尤其是在必须引用几个表才能获得所需的数据时。在结果集中包括“合计”的例程通常要比使用游标执行的速度快。如果开发时间允许，基于游标的方法和基于集的方法都可以尝试一下，看哪一种方法的效果更好。</p>
<p>28、在所有的存储过程和触发器的开始处设置 SET NOCOUNT ON ，在结束时设置 SET NOCOUNT OFF 。无需在执行存储过程和触发器的每个语句后向客户端发送 DONE_IN_PROC 消息。</p>
<p>29、尽量避免大事务操作，提高系统并发能力。</p>
<p>30、尽量避免向客户端返回大数据量，若数据量过大，应该考虑相应需求是否合理。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>mysql中的unsigned说明</title>
		<link>https://www.mudbest.com/mysql%e7%a7%8d%e7%9a%84unsigned%e8%af%b4%e6%98%8e/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Thu, 18 Oct 2012 04:54:30 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[unsigned]]></category>
		<category><![CDATA[数据类型]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=1570</guid>

					<description><![CDATA[unsigned 既为非负数，用此类型可以增加数据长度! 例如如果 tinyint最大是127，那 tinyi ... <a title="mysql中的unsigned说明" class="read-more" href="https://www.mudbest.com/mysql%e7%a7%8d%e7%9a%84unsigned%e8%af%b4%e6%98%8e/" aria-label="阅读 mysql中的unsigned说明">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p><strong>unsigned </strong> 既为非负数，用此类型可以增加数据长度!</p>
<p>例如如果 tinyint最大是127，那 tinyint unsigned 最大 就可以到 127 * 2</p>
<p><strong>unsigned </strong>属性只针对整型，而binary属性只用于char 和varchar。<br />
<span id="more-1570"></span></p>
<table style="width: 370px; height: 287px;" border="1" cellspacing="1" cellpadding="0">
<tbody>
<tr>
<td>类型</td>
<td>说明</td>
</tr>
<tr>
<td>tinyint</td>
<td>非常小的整数</td>
</tr>
<tr>
<td>smallint</td>
<td>较小整数</td>
</tr>
<tr>
<td>mediumint</td>
<td>中等大小整数</td>
</tr>
<tr>
<td>int</td>
<td>标准整数</td>
</tr>
<tr>
<td>bigint</td>
<td>较大整数</td>
</tr>
<tr>
<td>float</td>
<td>单精度浮点数</td>
</tr>
<tr>
<td>double</td>
<td>双精度浮点数</td>
</tr>
<tr>
<td>decimal</td>
<td>一个串的浮点数</td>
</tr>
</tbody>
</table>
<p>每种数值类型的名称和取值范围如表2所示。</p>
<p>表2：数值列类型的取值范围</p>
<table style="width: 828px; height: 483px;" border="1" cellspacing="1" cellpadding="0">
<tbody>
<tr>
<td>类型说明</td>
<td>取值范围</td>
</tr>
<tr>
<td>tinyint[(m)]</td>
<td>有符号值：-128 到127（- 27 到27 &#8211; 1）<br />无符号值：0到255（0 到28 &#8211; 1） <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>1个字节</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></td>
</tr>
<tr>
<td>smallint[(m)]</td>
<td>有符号值：-32768 到32767（- 215 到215 &#8211; 1）<br />无符号值：0到65535（0 到21 6 &#8211; 1） <wbr><wbr><wbr><wbr><wbr><wbr><wbr>2个字节</wbr></wbr></wbr></wbr></wbr></wbr></wbr></td>
</tr>
<tr>
<td>mediumint[(m)]</td>
<td>有符号值：-8388608 到8388607（- 22 3 到22 3 &#8211; 1 ）<br />无符号值：0到16777215（0 到22 4 &#8211; 1） <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>3个字节</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></td>
</tr>
<tr>
<td>int[(m)]</td>
<td>有符号值：-2147683648 到2147683647（- 231 到231- 1）<br />无符号值：0到4294967295（0 到232 &#8211; 1） <wbr><wbr>4个字节</wbr></wbr></td>
</tr>
<tr>
<td>bigint[(m)]</td>
<td>有符号值：-9223372036854775808 到9223373036854775807（- 263到263-1）<br />无符号值：0到18446744073709551615（0到264 – 1） 8个字节</td>
</tr>
<tr>
<td>float[(m, d)]</td>
<td>最小非零值：±1.175494351e &#8211; 38</td>
</tr>
<tr>
<td>double[(m,d)]</td>
<td>最小非零值：±2.2250738585072014e &#8211; 308</td>
</tr>
<tr>
<td>decimal (m, d)</td>
<td>可变；其值的范围依赖于m 和d</td>
</tr>
</tbody>
</table>
<p>各种类型值所需的存储量如表3所示。</p>
<p>表3：数值列类型的存储需求</p>
<table style="width: 798px; height: 196px;" border="1" cellspacing="1" cellpadding="0">
<tbody>
<tr>
<td>类型说明</td>
<td>存储需求</td>
</tr>
<tr>
<td>tinyint[(m)]</td>
<td>1字节</td>
</tr>
<tr>
<td>smallint[(m)]</td>
<td>2字节</td>
</tr>
<tr>
<td>mediumint[(m)]</td>
<td>3字节</td>
</tr>
<tr>
<td>int[(m)]</td>
<td>4字节</td>
</tr>
<tr>
<td>bigint[(m)]</td>
<td>8字节</td>
</tr>
<tr>
<td>float[(m, d)]</td>
<td>4字节</td>
</tr>
<tr>
<td>double[(m, d)]</td>
<td>8字节</td>
</tr>
<tr>
<td>decimal (m, d)</td>
<td>m字节（mysql &lt; 3.23），m+2字节（mysql &gt; 3.23 ）</td>
</tr>
</tbody>
</table>
<p>mysql提供了五种整型： tinyint、smallint、mediumint、int和bigint。int为integer的缩写。这些类型在可表示的取值范围上是不同的。 整数列可定义为unsigned从而禁用负值；这使列的取值范围为0以上。各种类型的存储量需求也是不同的。取值范围较大的类型所需的存储量较大。</p>
<p><wbr><wbr><wbr><wbr><wbr>mysql 提供三种浮点类型： float、double和decimal。与整型不同，浮点类型不能是unsigned的，其取值范围也与整型不同，这种不同不仅在于这些类型有最大 值，而且还有最小非零值。最小值提供了相应类型精度的一种度量，这对于记录科学数据来说是非常重要的（当然，也有负的最大和最小值）。</wbr></wbr></wbr></wbr></wbr></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
