MySQL的一些技巧
使用RAND()获取随机结果
在ORDER BY语句中可按照如下的随机顺序检索数据行:
mysql> SELECT * FROM tbl_name ORDER BY RAND();
ORDER BY RAND()同 LIMIT 的结合从一组列中选择随机样本很有用:
mysql> SELECT * FROM table1, table2 WHERE a=b AND c<d
-> ORDER BY RAND() LIMIT 1000;
GROUP BY列别名
数据表没有day字段(date型),只有ctime字段(datetime型),但需要按天进行汇总统计:
mysql> select date(ctime) as day, count(*) from league_apply where ctime >= '2011-02-15' and ctime <= '2011-02-28' group by day;
SELECT ... INTO OUTFILE 导出数据
在下面的例子中,导出数据到指定文件,各值使用制表符'\t'分隔,记录之间使用'\r\n'作为换行符(导出的数据格式很容易导入excel表中)
SELECT english, chinese, player_ca INTO OUTFILE '/tmp/players.text'
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\r\n'
FROM player_star_original
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\r\n'
FROM player_star_original
如果想给字符串类型字段值加上双引号'"'作为限定符,可以使用下面的方法:
SELECT english, chinese, player_ca INTO OUTFILE '/tmp/players.text'
FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
FROM player_star_original
FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
FROM player_star_original