简体   繁体   English

从MySQL数据库相关表输出数据

[英]Output data from MySQL database related tables

Limited MySQL knowledge. 有限的MySQL知识。 I need to extract related data from multiple tables in a database to a csv/spreadsheet. 我需要将数据库中多个表中的相关数据提取到csv /电子表格中。

Three tables: 三个表:

  • Customers, 顾客,
  • Orders, 命令,
  • OrderItems OrderItems

An OrderItem is related to an Order via a unqiue ID. OrderItem通过Unqiue ID与订单相关。 Each Order can have one or more OrderItems. 每个订单可以具有一个或多个OrderItems。

The Order is related to a Customer via a unique ID. 订单通过唯一ID与客户相关。 Each customer can have one more more Orders. 每个客户可以再有一个订单。

I've attempted this query based on the advice below - thanks: 我根据以下建议尝试了此查询-谢谢:

SELECT * FROM user u
JOIN order o
ON u.id = o.userid
JOIN orderarticles a
ON o.id = a.orderid;

However, getting an error: 但是,出现错误:

 Duplicate column name 'OXID'

I cannot change the field names/structure. 我无法更改字段名称/结构。 How can I resolve this? 我该如何解决?

I want a spreadsheet containing all the customers, with their associated purchase history. 我想要一个包含所有客户及其相关购买历史的电子表格。 Time or payment is not so important as simply knowing what each customer purchased. 时间或付款并不仅仅知道每个客户购买了什么就重要。

Looking forward to some pro tips! 期待一些专业提示!

Lets say you have 3 tables: customer_table, order_table, order_items_table. 假设您有3个表格:customer_table,order_table,order_items_table。 Following has to be the basic structure of your table: 以下必须是表的基本结构:

  1. customer_table should have a primary key say customer_id customer_table应该有一个主键,说是customer_id
  2. order_table has a primary key say order_id and needs to have a foreign key-->customer_id referring to customer_key order_table有一个主键,例如order_id,需要有一个外键-> customer_id引用了customer_key
  3. order_items_table has a primary key say item_id and a foreign key-->order_id referring to order_table. order_items_table有一个主键(例如item_id)和一个外键-> order_id(引用order_table)。

After having such a kind of structure you can refer to the links posted by Mohit. 具有这种结构后,您可以参考Mohit发布的链接。

Perform a join query that will specify the fields you want and indicate an outfile that will hold your data - for example: 执行联接查询,该联接查询将指定所需的字段并指示将保存您的数据的输出文件,例如:

SELECT [Fields] FROM `customers` `c` 
JOIN `orders` `o`
ON `c`.`customer_id`=`o`.`customer_id`
JOIN `order_items` `oi`
ON `o`.`order_id`=`oi`.`order_id`
INTO OUTFILE "C:\tmp\file.csv"
FIELDS ENCLOSED BY '"'
TERMINATED BY ','
ESCAPED BY '"'
LINES TERMINATED BY '\r\n';

Then navigate to "C:\\tmp" and open "file.csv" with excel 然后导航到“ C:\\ tmp”并使用excel打开“ file.csv”

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

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