简体   繁体   中英

How to set a variable for (select * from) in mysql

I'm trying to set a variable for x.* and y.* like this:

("SELECT x.* as x_var, y.* as y_var 
  FROM table_x x 
  INNER JOIN table_y y on x.id = y.id WHERE x.id='1'");

But the code gives an error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as table_x, y.* as y_var FROM table_x x INNER JOIN table_y d ON x.id = y.id WH' at line 1

How can I fix it?

With respect, your use of "variable" is ambiguous. Please read this: MySQL: @variable vs. variable. What's the difference?

If you mean column aliases, you do

 SELECT col1 a, col2 b, col3 c
   FROM whatever

You tried to assign multiple aliases with SELECT * AS alias . You Can't Do That™.

If you mean local variables you want

 SELECT @a := col1, @b := col1

And, you can't do SELECT @a: = * either.

Pro tip: Avoid using SELECT * whenever you can. Instead give a list of column names you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM