简体   繁体   中英

Output data from MySQL database related tables

Limited MySQL knowledge. I need to extract related data from multiple tables in a database to a csv/spreadsheet.

Three tables:

  • Customers,
  • Orders,
  • OrderItems

An OrderItem is related to an Order via a unqiue ID. Each Order can have one or more OrderItems.

The Order is related to a Customer via a unique 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. Following has to be the basic structure of your table:

  1. customer_table should have a primary key say 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
  3. order_items_table has a primary key say item_id and a foreign key-->order_id referring to order_table.

After having such a kind of structure you can refer to the links posted by 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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