Your Question

I have a query like this.

SELECT GROUP_CONCAT(distinct concat('max(CASE WHEN attribute_name = "' , attribute_name , '" THEN value END) AS ', attribute_name))INTO @data
    FROM (
            SELECT a.attribute_name,av.value
            FROM ATTRIBUTE_VALUE av,ATTRIBUTE a
            WHERE a.attribute_id = av.attribute_id
    )as t;
    Set data := CONCAT("SELECT product_id, ", @data, "  FROM (
            SELECT pa.product_id,a.attribute_name,av.value,ps.sku, a.type
            FROM PRODUCT_ATTRIBUTE pa
            JOIN ATTRIBUTE_VALUE av
            ON av.attribute_value_id = pa.attribute_value_id
            JOIN ATTRIBUTE a
            ON a.attribute_id = av.attribute_id
            JOIN PRODUCT_SKU ps
            ON pa.product_id = ps.product_id

            ORDER BY pa.product_id
    ) as ta
        GROUP BY product_id");

    PREPARE stmt FROM @data;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

How I use:

Gorm I can't use SET in db.Raw() or db.Exec()

Its work fine on MySQL Workbench, but when I use gorm with Golang, I got this error

 Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Set data := CONCAT("SELECT product_id, ", @data, "  FROM (
                SELECT pa.product_i' at line 7

It got the same error in Raw or Exec. After doing alot of research, I think that I can't use SET like this in gorm. Can someone explain to me how I can solve this problem? Thanks you Gorm version: 1.24.1 DB: MySQL Golang: 1.19.1

The document you expected this should be explained

Expected answer

Comment From: li-jin-gou

refer to https://gorm.cn/docs/sql_builder.html and see exec usage