我想将100个表从MySql转换为MongoDb
所以我认为最简单的方法是将数据导入为JSON
在不使用PHP / ruby / Python的情况下将MySql数据转换为JSON格式的任何通用查询?
SELECT CONCAT(CONCAT('{"CompanyId":', company_id),"}") AS JSON FROM company;
答案 0 :(得分:3)
试试这个:
SET @schema = 'test_db';
SET @table = 'test';
SELECT CONCAT(
'SELECT CONCAT(TRIM(TRAILING ', QUOTE(','), ' FROM CONCAT(', QUOTE('{'), ',',
GROUP_CONCAT(QUOTE('"'), ',', QUOTE(COLUMN_NAME), ',',
QUOTE('"'), ',', QUOTE(':'), ',', QUOTE('"'), ',', COLUMN_NAME, ',',
QUOTE('"'),',', QUOTE(',')),
')), ''}'') FROM ', @table
)
INTO @qry FROM
(SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table) t;
SELECT @qry;
PREPARE stmt FROM @qry;
EXECUTE stmt;
以上查询以JSON格式生成表数据。使用该查询,您可以准备一个存储过程,将数据库和表名作为输入参数并填充数据。如果要排除表中的某些列,只需修改从INFORMATION_SCHEMA
数据库中选择数据的查询,如SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS c WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND COLUMN_NAME NOT IN (**columns to exclude**)
。
答案 1 :(得分:2)
我扩展了oardic的答案,创建了一个mysql过程,从表名生成json以及null检查。此键设置为值null
而不是空字符串。
create procedure createJSON (IN tabelSchema varchar(255), IN tableName varchar(255), IN whereCondition varchar(255), OUT outJson longtext)
BEGIN
DROP TEMPORARY TABLE IF EXISTS RowJson;
SELECT CONCAT(
'CREATE TEMPORARY TABLE RowJson AS SELECT CONCAT(TRIM(TRAILING ', QUOTE(','), ' FROM CONCAT(', QUOTE('{'), ',',
GROUP_CONCAT(QUOTE('"'), ',', QUOTE(COLUMN_NAME), ',',
QUOTE('"'), ',', QUOTE(':'), ',', 'IF(ISNULL(', COLUMN_NAME, '), "null", CONCAT(',QUOTE('"'),",", COLUMN_NAME, ",", QUOTE('"'),')),',
QUOTE(',')),
')), ''}'') as json FROM ', tableName, ' WHERE ', whereCondition
)
INTO @qry FROM
(SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_SCHEMA = tabelSchema AND TABLE_NAME = tableName) t;
PREPARE stmt FROM @qry;
EXECUTE stmt;
SELECT json into outJson FROM RowJson;
END;