MySQL - Set default value for field as a string concatenation function

后端 未结 3 1953
面向向阳花
面向向阳花 2021-02-05 23:31

I have a table that looks a bit like this actors(forename, surname, stage_name);

I want to update stage_name to have a default value of

forename.\" \".su         


        
3条回答
  •  清歌不尽
    2021-02-06 00:24

    My first thought is if you have the two values in other fields what is the compelling need for redundantly storing them in a third field? It flies in the face of normalization and efficiency.

    If you simply want to store the concatenated value then you can simply create a view (or IMSNHO even better a stored procedure) that concatenates the values into a pseudo actor field and perform your reads from the view/sproc instead of the table directly.

    If you absolutely must store the concatenated value you could handle this in two ways:

    1) Use a stored procedure to do your inserts instead of straight SQL. This way you can receive the values and construct a value for the field you wish to populate then build the insert statement including a concatenated value for the actors field.

    2) So I don't draw too many flames, treat this suggestion with kid gloves. Use only as a last resort. You could hack this behavior by adding a trigger to build the value if it is left null. Generally, triggers are not good. They add unseen cost and interactions to fairly simple interactions. You can, though, use the CREATE TRIGGER to update the actors field after a record is inserted or updated. Here is the reference page.

提交回复
热议问题