I tried to learn about MySQL Variable and do command like this
SET @target=`name`;
SELECT @target FROM transaction_product LIMIT 10;
But it is error and said Unknown column 'name' in 'field list'
Why it is error, i'm sure there is column name on my field list
here is the screenshot of the table
2 Answers
you need to use different quotes 'name' for assigning string to a variable and `name` for column names:
SET @target='name';
to get column value you can use INTO clause:
SELECT `name`
INTO @target
FROM transaction_product
LIMIT 1;
to get multiple rows in single variables you can use GROUP_CONCAT:
SELECT GROUP_CONCAT(`name`)
INTO @target
FROM transaction_product
LIMIT 10;
to execute query dynamically:
SET @target='`name`';
SET @query1 = CONCAT('
SELECT ',@target,'
FROM transaction_product
LIMIT 10'
);
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SELECT @target:=`name` FROM transaction_product LIMIT 10;