A
A
Alexander Batukhtin2013-08-20 12:01:16
MySQL
Alexander Batukhtin, 2013-08-20 12:01:16

How (and is it possible) to add fields with calculated names to a table in bare MySQL?

Yes, not just with calculated ones, but based on data from other tables.
There is a language table:

id name
one Russian
2 English

And there is a table, say, countries:
id guide
one Russia
2 france

We need to add two more fields to the countries table to store names in the corresponding languages:
id guide name_1 name_2
one Russia
2 france


Is it real on pure MySQL?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2013-08-20
@0lorin

copist: It's not very clear what exactly should be in the name_1 name_2 columns

0lorin: In the future, country names in languages ​​from the first table.

That is, when a new record appears in languages, in the countries table, add a field equal to `name_` + languages.id?
I will answer that it is impossible with a naked Mayskul. :-)
Because you can hang up auto-creation in fact only on a trigger. And he is not friendly with gluing field names from variables ( CONCAT ). I fought with it myself. I even tried to create a function that would refer to the field, the name of which should be assembled from component parts. But the triggers sent me to the forest, saying that "what a tricky one, we see that you create a field from variables in a function."
Neither create nor even refer to such a field.
If the creation of the field will be performed by php, and not MySQL, then the niko83 option will suit you there.
But I would still do as boodda advises. Over the years, I've come to that conclusion. Especially when I started using the jungi ORM. It's just that on an HL project you shouldn't tie everything to MySQL. Many things, especially if they are lists. Sometimes it's easier to pull it out of the database and sort through the code already. Well, things like MongoDB or noSQL help to process large lists.

N
niko83, 2013-08-20
@niko83

Try the approach like here forums.mysql.com
(example from the link page)

set @addcoltext = concat('ALTER TABLE nick.mytable ADD COLUMN ',concat('day',dayofmonth(curdate() - interval 1 day)),' INTEGER UNSIGNED;');
prepare addcol from @addcoltext;
execute addcol;
deallocate prepare addcol; 

I
ivnik, 2013-08-20
@ivnik

Can it be possible to solve the problem using view?

B
boodda, 2013-08-20
@boodda

Do you really need it?
Perhaps you approached the solution of the problem from the wrong side?
I mean, perhaps it's easier for you to make a third table in which to store
country.id | language.id | name
?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question