简体   繁体   English

MySQL从表左选择与CSV导出联接

[英]Mysql select from table left join with csv export

I have tables that are on different mysql instances. 我有在不同的mysql实例上的表。 I want to export some data as csv from a mysql instance, and perform a left join on a table with the exported csv data. 我想从mysql实例中将某些数据导出为csv,并使用导出的csv数据在表上执行左连接。 How can I achieve this? 我该如何实现?

Quite surprisingly that is possible with MySQL, there are several steps that you need to go through. 令人惊讶的是,使用MySQL可以实现,您需要完成几个步骤。

  1. First create a template table using CSV engine and desired table layout. 首先使用CSV引擎和所需的表格布局创建模板表格。 This is the table into which you will import your CSV file. 这是您要导入CSV文件的表。 Use CREATE TABLE yourcsvtable (field1 INT NOT NULL, field2 INT NOT NULL) ENGINE=CSV for example. 例如,使用CREATE TABLE yourcsvtable (field1 INT NOT NULL, field2 INT NOT NULL) ENGINE=CSV Please note that NULL values are not supported by CSV engine. 请注意, CSV引擎不支持NULL值。
  2. Perform you SELECT to extract the CSV file. 执行“ SELECT以提取CSV文件。 Eg SELECT * FROM anothertable INTO OUTFILE 'temp.csv' FIELDS TERMINATED BY ','; 例如SELECT * FROM anothertable INTO OUTFILE 'temp.csv' FIELDS TERMINATED BY ',';
  3. Copy temp.csv into your target MySQL data directory as yourcsvtable.CSV . temp.csv作为yourcsvtable.CSV复制到目标MySQL数据目录。 Location and exact name of this file depends on your MySQL setup. 该文件的位置和确切名称取决于您的MySQL设置。 You cannot perform the SELECT in step 2 directly into this file as it is already open - you need to handle this in your script. 您无法直接在此文件中执行第2步中的SELECT ,因为该文件已经打开-您需要在脚本中进行处理。
  4. Use FLUSH TABLE yourcsvtable; 使用FLUSH TABLE yourcsvtable; to reload/import the CSV table. 重新加载/导入CSV表。

Now you can execute your query against the CSV file as expected. 现在,您可以按预期对CSV文件执行查询。

Depending on your data you need to ensure that the data is correctly enclosed by quotation marks or escaped - this needs to be taken into account in step 2. 根据您的数据,您需要确保将数据正确地用引号引起来或将其转义-这需要在步骤2中加以考虑。

CSV file can be created by MySQL on some another server or by some other application as long as it is well-formed. CSV文件可以由MySQL在其他服务器或其他应用程序上创建,只要格式正确即可。

If you export it as CSV, it's no longer SQL, it's just plain row data. 如果将其导出为CSV,则不再是SQL,而只是纯行数据。 Suggest you export as SQL, and import into the second database. 建议您导出为SQL,然后导入第二个数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM