Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name wildcard select columns in MySQL?

I will simplify my scenario - I have these 2 tables:

table_A - id int, id_table_B_one int, id_table_B_two int, name varchar(30)
table_B - id int, name varchar(30), description varchar(30)

Then I have this query:

SELECT
table_A.id, table_A.name, table_B_one.*, table_B_two.* 
FROM
table_A
LEFT JOIN table_B table_B_one ON table_A.id_table_B_one = table_B.id
LEFT JOIN table_B table_B_two ON table_A.id_table_B_two = table_B.id

My problem is that I will get 3 columns with the same names (id and name). I know I can use 'AS' keyword to specify one column's alias. However, I would need to specify each selected column, but I have to use '*' wildcard.

Is there any way how can set alias column name with '*' wildcard ? Something like this:

... table_B_one.* AS table_B_one_* ...

like image 752
Frodik Avatar asked Nov 04 '22 02:11

Frodik


1 Answers

No, there isn't a way set aliases using a wildcard. You need to be explicit.

If your SQL is dynamically generated, then the cost (to you) of being explicit with all the necessary aliases is extremely small - just put the generation of the correct aliases into the code that generates the SQL.

Being explicit with the aliases will help the readability of the code - which is what aliases are there for. However, I'm curious: why do you want aliases if your SQL is dynamically generated?

like image 172
D Mac Avatar answered Nov 07 '22 20:11

D Mac