dshgnt2008 2016-06-30 00:43
浏览 46
已采纳

将表中的许多行插入另一个表中的一个唯一行

I have a table named order where there is set a column name 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

I'd like to insert the list into another table named confirmation in a way that all of them could be in a same row! However, it doesn't work and is inserting in many rows!

The way I want

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

The way is showing

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

Here is the code: I'm working with 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);
}
  • 写回答

1条回答 默认 最新

  • doujue6196 2016-06-30 00:48
    关注

    Every time you perform an INSERT query it creates a new row. Since you're doing this in a loop, it creates a new row for each product.

    If you want to combine items, use GROUP_CONCAT:

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

    Notice that you need to quote the table name order with backticks because it's a reserved word. It's generally best to avoid using reserved words as table and column names, since if you forget to quote it you'll get a confusing syntax error. See Syntax error due to using a reserved word as a table or column name in MySQL

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误