MYSQL中将搜索结果导出至文件

1.修改mysql导出数据本地所在位置

a.找到mysql的安装目录 

b.打开my.ini文件 

c.找到secure_file_priv="E:/MYSQL" 

d.修改导出路径

2.导出单文件

示例表:

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50714
Source Host           : localhost:3306
Source Database       : cpptest

Target Server Type    : MYSQL
Target Server Version : 50714
File Encoding         : 65001

Date: 2018-10-18 15:14:49
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`type` smallint(6) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'admin', '1');
INSERT INTO `users` VALUES ('2', 'ppc', '2');
INSERT INTO `users` VALUES ('3', 'aaa', '1');
INSERT INTO `users` VALUES ('4', 'bbb', '2');

sql语句导出表数据(带标题行)

a.导出csv

SELECT * FROM ( select '编号','姓名','类型' 
		union select id,username,type from users WHERE type=1) a 
INTO OUTFILE 'E:/MYSQL/orders1.csv'
FIELDS TERMINATED BY ',' 
LINES TERMINATED BY '\n';

b.导出Excel

SELECT * FROM ( select '编号','姓名','类型' 
		union select id,username,type from users WHERE type=1) a 
INTO OUTFILE 'E:/MYSQL/orders1.xls';

3.根据分组导出文件

示例:导出Excel(存储过程使用游标完成循环)

create procedure cursor_test()
BEGIN  
    DECLARE df1 smallint(6);
    DECLARE done INT DEFAULT FALSE;
    DECLARE cur CURSOR FOR SELECT type FROM users GROUP BY type;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;
    OPEN cur;
    read_loop : LOOP
        FETCH cur INTO df1;
        IF done THEN
            LEAVE read_loop;
        END IF;

        SET @sql_cpp = CONCAT("SELECT * FROM ( select '编号','姓名','类型' 
				union select id,username,type from users WHERE type=",df1,") temp 
        INTO OUTFILE 'E:/MYSQL/orders",df1,".xls'");

        PREPARE sqlcpp FROM @sql_cpp;
        EXECUTE  sqlcpp;
        COMMIT;
        END LOOP read_loop;
	CLOSE cur;
END
--------------------------------
调用存储过程:
call `cursor_test`();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值