P粉0463871332023-08-23 11:13:47
我有一個稍微不同的方法來完成這個任務,與接受的答案不同。這種方法可以避免使用預設情況下有1024個字元限制的GROUP_CONCAT,並且如果你有很多字段,它將無法工作,除非你改變限制。
SET @sql = ''; SELECT @sql := CONCAT(@sql,if(@sql='','',', '),temp.output) FROM ( SELECT DISTINCT CONCAT( 'MAX(IF(pa.fieldname = ''', fieldname, ''', pa.fieldvalue, NULL)) AS ', fieldname ) as output FROM product_additional ) as temp; SET @sql = CONCAT('SELECT p.id , p.name , p.description, ', @sql, ' FROM product p LEFT JOIN product_additional AS pa ON p.id = pa.id GROUP BY p.id, p.name, p.description'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;#
P粉7680455222023-08-23 00:34:41
在MySQL中,唯一動態執行此操作的方法是使用預處理語句。以下是一篇關於它們的好文章:
#你的程式碼將如下所示:
SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'MAX(IF(pa.fieldname = ''', fieldname, ''', pa.fieldvalue, NULL)) AS ', fieldname ) ) INTO @sql FROM product_additional; SET @sql = CONCAT('SELECT p.id , p.name , p.description, ', @sql, ' FROM product p LEFT JOIN product_additional AS pa ON p.id = pa.id GROUP BY p.id, p.name, p.description'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
查看示範
注意:GROUP_CONCAT函數的字元限制為1024個字元。請參閱參數group_concat_max_len