mysql 在结果集外创建一个SQL语句

d7v8vwbk  于 2023-11-16  发布在  Mysql
关注(0)|答案(2)|浏览(150)

我有一个SQL脚本,它从Clickhouse表中返回大约23k行的数据。我想将确切的数据插入到MySQL中的表中。由于它们是两个不同的DB,并且没有代理可以使用(所以没有INSERT INTO SELECT),似乎我唯一的选择就是用我拥有的确切数据创建一个插入脚本,这样我就可以复制它并在另一个DB上运行。
换句话说,假设我有一个剧本

  1. SELECT date, name, sumIf(events>0) ev
  2. FROM t1
  3. GROUP BY date, name

字符串
它返回数据

  1. 2023-10-31 'George' 1261169
  2. 2023-11-01 'Alan' 1261370
  3. 2023-11-02 'Peter' 1261361


我如何修改我的脚本,使它返回类似于

  1. INSERT INTO t2 VALUES (2023-10-31, 'George', 1261169), (2023-11-01, 'Alan', 1261370), (2023-11-02, 'Peter', 1261361);


a6b3iqyw

a6b3iqyw1#

下面是生成所需插入语句的代码

  1. select concat('INSERT INTO t2 VALUES ', substring(tmp, 2, length(tmp) - 2))
  2. from (
  3. select replaceAll(toString(groupArray(concat('(', toString(date), ',', name, ',', toString(sum), ')'))), '\'', '') as tmp
  4. from (
  5. (select toDate('2023-10-31') as date, 'George' as name, 1261169 as sum)
  6. union all
  7. (select toDate('2023-11-01') as date, 'Alan' as name, 1261370 as sum)
  8. union all
  9. (select toDate('2023-11-02') as date, 'Peter' as name, 1261361 as sum)
  10. ) as t
  11. ) as t2

字符串
输出量:

  1. INSERT INTO t2 VALUES (2023-10-31,George,1261169),(2023-11-01,Alan,1261370),(2023-11-02,Peter,1261361)


你可以使用clickhouse playground来测试:https://play.clickhouse.com/play?user=play#c2VsZWN0IDE=
不幸的是,由于某些原因,playground中没有arrayFold函数,该函数可以简化代码,但我使用字符串操作进行了特别的解决方案

展开查看全部
uttx8gqw

uttx8gqw2#

有一个更优雅的方法。

  1. SELECT date, name, sumIf(events>0) ev
  2. FROM t1
  3. GROUP BY date, name
  4. FORMAT SQLInsert
  5. SETTINGS
  6. output_format_sql_insert_max_batch_size = 3,
  7. output_format_sql_insert_table_name = 't2'

字符串
输出将是这样的:

  1. INSERT INTO t2 VALUES
  2. (2023-10-31, 'George', 1261169),
  3. (2023-11-01, 'Alan', 1261370),
  4. (2023-11-02, 'Peter', 1261361);

奖金

您可以在ClickHouse和MySQL示例之间创建链接,并使用MySQL表引擎直接将数据插入MySQL:

  1. CREATE TABLE t2
  2. (
  3. ...
  4. )
  5. ENGINE = MySQL('localhost:3306', 'test', 'test', 'bayonet', '123');
  6. INSERT INTO t2
  7. SELECT date, name, sumIf(events>0) ev
  8. FROM t1
  9. GROUP BY date, name

展开查看全部

相关问题