【问题标题】:Insert many rows from a table into one unique row in another table将一个表中的许多行插入到另一个表中的一个唯一行中
【发布时间】:2016-06-30 00:43:56
【问题描述】:

我有一个名为order 的表,其中设置了一个列名list

TABLE list
id |  list      | price    | date
---------------------------------------
1  | Cigar      |  5.00    | 2016-06-30
2  | Beer       |  6.00    | 2016-06-30
3  | Whiskey    |  20.00   | 2016-06-30
4  | Bacon      |  10.00   | 2016-06-30

我想将list 插入另一个名为confirmation 的表中,以使它们都可以在同一行中!但是,它不起作用并且插入了很多行!

我想要的方式

TABLE confirmation
id |            theorder             
--------------------------------
1  | Cigar, Beer, Whiskey, Bacon

道路正在显现

TABLE confirmation
id |  theorder      
--------------
1  | Cigar,
2  | Beer,
3  | Whiskey,
4  | Bacon,

这是代码:我正在使用 foreach!

$sql     = "SELECT list FROM order";
$result  = $conn->query($sql);
$getList = $result->fetchAll(PDO::FETCH_ASSOC);

foreach($getOrder as $order) {
  $products = $order['theorder'] . ', ';
  $sql      = "INSERT INTO confirmation (theorder) VALUES ('$products')";
  $result   = $conn->query($sql);
}

【问题讨论】:

  • Here 是类似的问题。

标签: php mysql sql foreach row


【解决方案1】:

每次执行INSERT 查询时,它都会创建一个新行。由于您在循环中执行此操作,因此它会为每个产品创建一个新行。

如果要组合项目,请使用GROUP_CONCAT:

INSERT INTO confirmation (theorder)
SELECT GROUP_CONCAT(list SEPARATOR ', ')
FROM `order`

请注意,您需要用反引号引用表名order,因为它是保留字。通常最好避免使用保留字作为表名和列名,因为如果您忘记引用它,您会得到一个令人困惑的语法错误。见Syntax error due to using a reserved word as a table or column name in MySQL

【讨论】:

  • 对。这个 SQL 查询将完成整个事情。
  • 谢谢!我会尽快给它评分! =D
  • @CaioFerrari ,我怀疑你需要按日期分组。
  • @Wizard 我也怀疑。但是他的原始代码没有按日期过滤,它只是获取所有订单。
  • 您可以将文字放在SELECT 列表中:SELECT GROUP_CONCAT(list SEPARATOR ', '), '$theprice', '$thedate' FROM order
猜你喜欢
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 2014-05-22
  • 2012-03-06
相关资源
最近更新 更多