1

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

MySQL Table

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

2 Comments

is that mean variable can't use for select field name? i see you hardcoding the name field...
you can't assign column name to variables and use that variable in select clause. for that you can use PREPARE stmt.
0
SELECT @target:=`name` FROM transaction_product LIMIT 10;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.