【问题标题】:Select Multiple rows mysqli from different tables to combine and export in CSV从不同的表中选择多行 mysqli 以在 CSV 中合并和导出
【发布时间】:2019-08-02 16:41:36
【问题描述】:

我必须为订单导出一个 csv 文件,但一个订单的这些信息存储在不同的表中。所以我在一个表中有买家的姓名,他在另一个表中购买了什么,我必须导出在我的 csv 文件的一行中.. 是这样的

table1: entity_id, billing_name, created_at, grand_total, status 

table2: 
    sku, name, price, base_price, original_price, tax_percent,
    tax_amount, discount_percent, discount_amount, price_incl_tax, order_id

table1.entity_id=table2.order_id (is the way I can GROUP BY)

导出部分对我来说很清楚...我只是不知道如何组合这些信息来创建一行 感谢您的帮助!

【问题讨论】:

  • 您开始编写查询了吗,如果是,请将其添加到您的问题中
  • 如果你想让别人为你写这篇文章,知道你想将哪些列发送到 csv 也很有用
  • table1.entity_id=table2.order_id 是您可能必须加入表格的方式。看看 MySQL 在线指南上的 JOIN 语句
  • 您可以单独导出 table2 的每一行(如果您不想处理 JSON),也可以将 table2 中的所有相应行合并到 table1 中的单行中(使用 JSON_ARRAY 和 JSON_OBJECT 函数作为描述scotch.io/tutorials/working-with-json-in-mysql)

标签: php mysql database csv mysqli


【解决方案1】:

根据提供的信息,这里是一个返回所提到的列的查询。

您需要将两个表JOIN 放在一起,您可以使用JOIN table2 t2 ON t2.order_id = t1.entity_id 执行此操作,其中这些表还具有t1t2 的别名。 JOIN信息可见here

此外,可以使用 t1.grand_total AS total 为这些列命名以更改 CSV 客户端的列名

SELECT
  t1.entity_id,
  t1.billing_name,
  t1.created_at,
  t1.grand_total,
  t1.status,
  t2.sku,
  t2.name,
  t2.price,
  t2.base_price,
  t2.original_price,
  t2.tax_percent,
  t2.tax_amount,
  t2.discount_percent,
  t2.discount_amount,
  t2.price_incl_tax,
  t2.order_id
FROM
  table1 t1
  JOIN table2 t2 ON t2.order_id = t1.entity_id

【讨论】:

  • 谢谢!这种方式我试过很多次了,但是没有用……问题出在输出查询中,而不是语法 t2.order_id.. 所以现在可以了,谢谢
  • 你知道如何用标题导出这些行吗?谢谢!
  • 我可以帮忙。您使用的是什么 RDBMS?你有试过的代码吗?
  • 您希望 Web 服务器返回 CSV 文件,还是通过 CLI 执行此操作?
  • 我做到了:fp = fopen("lista-ordini.csv","w"); if ($rs = $db->query("SELECT sales_flat_order_grid.entity_id, sales_flat_order_grid.billing_name, sales_flat_order_grid.created_at, , sales_flat_order_grid.grand_total FROM sales_flat_order_grid, sales_flat_order_item WHERE sales_flat_order_grid.entity_id=order_id GROUP BY entity_id")) { while ($row = $rs->fetch_assoc()) { fputcsv($fp, array_values($row)); } $rs->close(); } fclose($fp); ?> 在一个 php 文件中。现在我想在 csv 列中添加标题非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2013-11-28
  • 2013-09-18
相关资源
最近更新 更多