[英]Insert many rows from a table into one unique row in another table
I have a table named order
where there is set a column name list
我有一个名为order
的表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
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! 我想将list
插入到名为confirmation
另一张表中,以使它们都可以在同一行中! 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! 代码如下:我正在使用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);
}
Every time you perform an INSERT
query it creates a new row. 每次执行INSERT
查询时,都会创建一个新行。 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
: 如果要合并项目,请使用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. 注意,您需要用反引号引起表名order
引用,因为这是保留字。 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 请参见由于在MySQL中使用保留字作为表或列名而导致的语法错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.