我有桌子:
+---------------+------------------------------+-----+------+
| id_order | id_product | qty | size |
+---------------+------------------------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2,PRD-0412-17-11 | 2,3 | M,S |
+---------------+------------------------------+-----+------+
我想有这样的输出:
+---------------+---------------+-----+-------+
| id_order | id_product | qty | size |
+---------------+----------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2 | 2 | M |
| ORD-0413-17-1 | PRD-0412-17-11 | 3 | S |
+---------------+----------------+-----+------+
我怎么能这样做?
答案 0 :(得分:2)
这是从'数据'构建规范化'结果'的一种方法......我使用的是一个简单的整数实用程序表(0-9),但你可以使用一堆UNION代替。
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id_order VARCHAR(20) NOT NULL
,id_product VARCHAR(255) NOT NULL
,qty VARCHAR(30) NOT NULL
,size VARCHAR(30) NOT NULL
);
INSERT INTO my_table VALUES
('ORD-0413-17-1','PRD-0408-17-2,PRD-0412-17-11','2,3','M,S');
DROP TABLE IF EXISTS ints;
CREATE TABLE ints(i INT NOT NULL PRIMARY KEY);
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
SELECT DISTINCT id_order
, SUBSTRING_INDEX(SUBSTRING_INDEX(id_product,',',i+1),',',-1) id_product
, SUBSTRING_INDEX(SUBSTRING_INDEX(qty,',',i+1),',',-1) qty
, SUBSTRING_INDEX(SUBSTRING_INDEX(size,',',i+1),',',-1) size
FROM my_table,ints;
id_order id_product qty size
ORD-0413-17-1 PRD-0408-17-2 2 M
ORD-0413-17-1 PRD-0412-17-11 3 S
答案 1 :(得分:-1)
在我的情况下,我在类php中使用方法,这是方法:
public function user_checkout($params){
$date = new DateTime(date('Y-m-d'));
$date->modify('+3 day');
$query = "SELECT * FROM cart WHERE id_session='".$params['id_user']."'";
$sql = $this->db->query($query);
$data1 = array();
$data2 = array();
$data3 = array();
while($result = $sql->fetch_assoc()){
$data1[] = $result['id_product'];
$data2[] = $result['qty'];
$data3[] = $result['size'];
}
$data_insert = array(
"id_order" => $params['id_order'],
"id_product" => implode(',', $data1),
"id_user" => $params['id_user'],
"qty" => implode(',', $data2),
"size" => implode(',', $data3),
"account_name" => $params['name_of_account'],
"account_number" => $params['no_rekening'],
"amount" => $params['amount'],
"total_price" => $params['total_price'],
"out_of_date" => $date->format('Y-m-d'),
"order_date" => date('Y-m-d')
);
$insert = "INSERT INTO `order_product`(`id_order`, `id_product`, `id_user`, `qty`,`size`, `account_name`, `account_number`, `amout`, `total_price`, `out_of_date`, `order_date`, `status`) VALUES ('".$data_insert['id_order']."','".$data_insert['id_product']."','".$data_insert['id_user']."','".$data_insert['qty']."','".$data_insert['size']."','".$data_insert['account_name']."','".$data_insert['account_number']."','".$data_insert['amount']."','".$data_insert['total_price']."','".$data_insert['out_of_date']."','".$data_insert['order_date']."',0)";
$sql_insert = $this->db->query($insert);
$delete = "DELETE FROM cart WHERE id_session = '".$params['id_user']."'";
$sql_delete = $this->db->query($delete);
return true;
}