MySQL query, how to use string in multiple ways?
I'm trying to create a MySql query which will construct a string using the CONCAT function within 2 loops.
I'm wondering if a string can be used both as a variable and a reference to a field in a table?
My code so far is below, which is returning some syntax error near the UPDATE line:
...
WHILE x <= 5 DO
WHILE y <= 3 DO
SELECT @str_data = CONCAT(str,'data_',x);
SELECT @str_data = CONCAT(str,'_',y);
SELECT @variable:= @str_data FROM sometable WHERE id = '@counter + y';
UPDATE anothertable SET @str_data = @variable WHERE id = '@counter + y';
SET y = y + 1;
END WHILE;
SET x = x + 1;
SET @counter = counter + 3;
END WHILE;
I've checked all 开发者_运维问答variables are set.
On a side note I may not be using the concat correctly, since I saw it being used differently in multiple examples. I intend for the format to end up as: 'data_x_y'. (By adding the '_y' to the end of the current string. := ?)
Lets start at the beginning: Change this code:
SELECT @str_data = CONCAT(str,'data_',x);
SELECT @str_data = CONCAT(str,'_',y);
To :
SET @str_data = CONCAT(str, 'data_',x,'_',y);
I'm wondering why you are mixing DECLARE variables (str) with @vars *(@str_data)*, it looks very confused.
So this code: SELECT @variable:= @str_data FROM sometable WHERE id = @counter + y;
Does not do what you think it does. It just selects @str_data
0 or more times, whilst setting @variable.
You need to remove the '
quotes from that if you want MySQL to add @counter + y
because with a quote it will just evaluate to 0 and not match.
This code is incorrect:
UPDATE anothertable SET @str_data = @variable WHERE id = '@counter + y';
Change it to:
UPDATE anothertable SET fieldx = @variable WHERE id = @counter + y;
Note that SQL is not php, you cannot use @vars as placeholders for dynamic column names.
It really makes no sense.
I guess you are trying to come up with a string holding a dynamic column name and doing a update on that column.
Forget about using this approach, it will never work in SQL, also this is not the way SQL is supposed to work.
What to do instead
Change your table into this format
Table proper
x integer
y integer
value varchar
otherfields .....
Now you can just update with
UPDATE proper SET value = @var WHERE x = 1 and y = 2;
Much cleaner and much faster.
精彩评论