basic6
basic6

Reputation: 3811

MYSQL dynamic field with content from other fields

let's say I have 2 columns in a table, a and b (both plain text). Is there any way to create a third column c in the same table, with the content of those other columns a and b?

Example:

a/0 = "Peter", b/0 = "Griffin" => c/0 = "Peter Griffin" (space if a != empty)

a/1 = "", b/1 = "The Giant Chicken" => c/1 = "The Giant Chicken" (no delimiter)

This dynamic column c would obviously have to be a read-only field, because there is no way to determine if a space is a delimiter or a regular character.



I use a simple PHP function for getting the contents of a field, so I could have this function check if field c is requested and, if so, return a, maybe a space and b... But I feel like this isn't the best place to do this check - is there a way to have SQL run this combine procedure?

Upvotes: 0

Views: 509

Answers (1)

Nicola Cossu
Nicola Cossu

Reputation: 56397

Concatenate them with a simple select

select trim(concat_ws(' ',a,b)) from table

You can adapt my select to an update statement if you need it.

Upvotes: 1

Related Questions