I tried to use a prepare
statement, but got 500 error.
I have 2 tables:
1.Sales Record (table_sales_record)
+----------+------------+----------------+
| sales_id | product_id | shipping_status|
+----------+------------+----------------+
| s1 | 1010 | shipping |
| s1 | 1011 | arrived |
| s2 | 1012 | arrived |
| s2 | 1013 | pending |
| s1 | 1014 | pending |
| s2 | 1015 | pending |
+----------+------------+----------------+
Sales Details (table_sales_details)
+------------+------------+ | sales_id | name | +------------+------------+ | s1 | Sales A | | s2 | Sales B | | s3 | Sales C | +------------+------------+
What I need is
+----------+------------+----------+---------+---------+----------+---------+
| sales_id | name | 1015 | 1014 | 1013 | 1012 | 1011 |
| s1 | Sales A | NULL | pending | NULL | NULL | arrived |
| s2 | Sales B | pending | NULL | pending | arrived | NULL |
+----------+------------+----------+---------+---------+----------+---------+
The below SQL is what I have tried:
SELECT CONCAT(
'SELECT `table_sales_record`.sales_id',
GROUP_CONCAT('
, `t_', REPLACE(product_id, '`', '``'), '`.`shipping_status`
AS `', REPLACE(product_id, '`', '``'), '`'
SEPARATOR ''),
' FROM `table_sales_record` ', GROUP_CONCAT('
LEFT JOIN `table_sales_record` AS `t_',
REPLACE(product_id, '`', '``'), '`
ON `table_sales_record`.sales_id = `t_',
REPLACE(sales_id, '`', '``'), '`.sales_id
AND `t_', REPLACE(sales_id, '`', '``'), '`.sales_id = ',
QUOTE(sales_id)
SEPARATOR ''),
' GROUP BY `table_sales_record`.sales_id'
) INTO @qry FROM (SELECT distinct sales_id FROM
`table_sales_record`) t;
PREPARE stmt FROM @qry;
EXECUTE stmt;
I can just finish some part and not yet join table_sales_details
, but I get the 500 error when execute this SQL query.
Do I follow the right direction? Can anyone help, please?