How to set up a field using three others?

Posted on

Question :

I have the following fields in the database:

| id| estados | cidades | categoria |      todosjuntos      |
| 1 | mg      | sao paul| informati | mg/saopaulo/informati |

The first 4 are populated, but I would like to insert in the todosjuntos the same data of the 3. Is it possible to do direct via SQL?

Update tabela set todosjuntos = estados / cidades / categoria Where todosjuntos=' '

Would it be there?


Answer :

   todosjuntos = CONCAT( estados, " ", cidades, " ", categoria )
   todosjuntos = "";

But if you run the first time, you do not even need to WHERE todosjuntos = ""

Remember that you can use other characters in place of space in CONCAT .

MySQL has CONCAT_WS as well, but allows you to set the tab only once. Usually% traditional% gives more freedom to work on this issue:

todosjuntos = CONCAT_WS( "/", estados, cidades, categoria)

If you do not use the field very often, you could just pick up the data at select time, like this:

SELECT CONCAT( estados, " / ", cidades, " / ", categoria ) AS todos FROM tabela;
SELECT CONCAT_WS( " / ", estados, cidades, categoria ) AS todos FROM tabela;

So you would not have to create a field just for that.


Leave a Reply

Your email address will not be published. Required fields are marked *