简体   繁体   中英

Create Table and assign a query as default value to a field

CREATE TABLE `williamhill` (
    `id` VARCHAR(50) NULL,
    `nick` VARCHAR(50) NULL,
    `password` VARCHAR(50) NULL DEFAULT (SELECT default_password FROM person p WHERE p.id = id),
    `Colonna 4` VARCHAR(50) NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB

How can i do something like that in MYSQL? I'm trying to assign a default value from another table if no value has been specified during the creation of new row.

Is it possible like that or should i use a trigger/procedure?

MySQL is quite explicit that this cannot be done. To begin with, the syntax for default is called default value . A value is expected.

Here is how the documentation describes this:

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

(The one exception is CURRENT_TIME which most people probably don't even realize is a function.)

Many databases do allow function calls here. None -- as far as I know -- allow query expressions. However, that can often be emulated in a user-defined function.

The work-around is to use a trigger. Looking up a value in another table is a fairly common use of triggers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM