简体   繁体   中英

Using column names as value for row in SQL

I have the following sql script:

CREATE TABLE  `akalogixDB`.`users` (
`user_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`priv_id` INT NOT NULL DEFAULT  '3',
`username` VARCHAR( 40 ) NOT NULL ,
`password` VARCHAR( 40 ) NOT NULL ,
`email` VARCHAR( 40 ) NOT NULL ,
`first_name` VARCHAR( 40 ) NULL ,
`last_name` VARCHAR( 40 ) NULL ,
`avatar` VARCHAR( 100 ) NULL DEFAULT 'images/avatars/no_avatar.jpg',
`mini_avatar` VARCHAR( 100 ) NULL DEFAULT 'images/avatars/no_avatar_mini.jpg',
`about` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL ,
`user_folder` VARCHAR(100) NOT NULL DEFAULT ====> #here is the problem
UNIQUE (
`username` ,
`email`)
) ENGINE = MYISAM ;

I would like to give the default value for user_folder the following: 'users/folders/'+user_id + current timestamp How can I do this, I know that I can do it with PHP, but is there way of doing with sql instructions.

You could use a trigger. Something like:

CREATE TRIGGER `before_users_insert`
    BEFORE INSERT ON `users` FOR EACH ROW
    BEGIN
        IF NEW.user_folder IS NULL THEN
            SET NEW.user_folder = CONCAT('users/folders/',NEW.user_id,  UNIX_TIMESTAMP());
        END IF;
    END

You'd need to figure out what value would trigger your default value as a NULL (as I've coded it) may not work because you have a NOT NULL on that column. It's a sound approach though and I hope this gives you the general idea.

What you'll need is a triger: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html try something like this:

create trigger t_users_bi 
before insert on users 
for each row BEGIN
   SET new.user_folder = CONCAT('users/folders/', new.user_id, current_timestamp);
END;

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