Question

I'm looking to create a new column with values that correspond with keywords in an existing column in mysql.

I'm trying to determine if a practice is private or public based on keywords in their establishment's name.

In plain english what i'm trying to get is a new column called Practice and insert value private if keywords are specialist, gleneagles.

Would appreciate any help on this matter.

Was it helpful?

Solution

If I understand what you're asking, you want to add a column to an existing table and then set that column's value (for each row) based on another column's value in that same row?

First, to create the column named Practice you can use MySQL's ALTER TABLE command:

ALTER TABLE YourTable ADD Practice VARCHAR(20);

I'm not sure what type you are aiming for here, so I'm just going with VARCHAR(20); you may also benefit from an enum based on the values you're using (or even a foreign-key to a lookup table).

After you've created your column, you can set its value:

UPDATE YourTable
SET Practice = CASE
    WHEN SomeColumn = 'specialist' THEN
        'private'
    WHEN SomeColumn = 'gleneagles' THEN
        'private'
    ELSE
        'public'
END

If you don't want records that don't match to be set, simply drop the ELSE 'public' and they'll be defaulted to null.

UPDATE (to select with wildcards)

If you need to update rows with the related data being contained within larger text and you need wildcards, you can use MySQL's LIKE operator:

UPDATE YourTable
SET Practice = CASE
    WHEN SomeColumn LIKE '%specialist%' THEN
        'private'
    WHEN SomeColumn LIKE '%gleneagles%' THEN
        'private'
    ELSE
        'public'
END

Alternatively, if you're only going to update to a single-value based on text containing multiple values, you can use a Regular Expression (via REXEXP) instead:

UPDATE YourTable
SET Practice = CASE
    WHEN SomeColumn REGEXP 'specialist|gleneagles' THEN
        'private'
    ELSE
        'public'
END

OTHER TIPS

You are asking about denormalization, which means storing derived data. My initial reaction would be to not add another column, unless there were significant performance problems, instead I would create a view that gas the calculated value.

However, if you need the column, I would create a boolean column:

alter table mytable 
add is_private boolean;

Then populate it like this:

update mytable 
set is_private = (name like '%specialist%' or 
                  name like '%gleneagles%')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top