Jump to content

Referencing user-defined variables in a sub select, possible?


s0c0

Recommended Posts

I think I will have to write some code or a very fancy query to accomplish this, but thought I would ask.  We have a log that stores changes to tables.  The field_name is the column name, the name_table is the table name, and the name_pk is the primary key.  id_row is the value for the primary key and the snapshot is what the value was.  I am able to select the snapshot, but within the same query I would like to return what the current value is.  Below I attempt using udv's within a sub query, but I don't believe MySQL will support this. 

 

Of course I try to do it without code and without multiple queries first, prospects look dismal.  Any suggestions?

 

SELECT 
@field:= field_name, id_row, change_type, @tbl:= name_table, @pk:= name_pk, snapshot, 
(SELECT @field FROM @tbl WHERE @pk = log_record_change.id_row) as current_value 
FROM
log_record_change 
INNER JOIN
log_field_change ON log_field_change.id_record_change = log_record_change.id 
INNER JOIN 
log_table ON log_table.id = log_record_change.id_table 
WHERE
log_record_change.id_change = 36 

Link to comment
Share on other sites

User defined variables can only be used where a value/variable would be used in expressions. They cannot be used as a table/column name.

 

User variables are intended to provide data values. They cannot be used directly in an SQL statement as an identifier or as part of an identifier, such as in contexts where a table or database name is expected, or as a reserved word such as SELECT.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.