简体   繁体   English

如何在mysql中设置文本类型的默认值

[英]how to set default value for text type in mysql

CREATE TABLE IF NOT EXISTS `te` (
  `id` int(30) NOT NULL,
  `name` text NOT NULL,
  `address` text NOT NULL,
  `Aboutus` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Here Table 'te' consist 4 fields id, name, address, Aboutus, Aboutus is optional means how can i update default text to the Profile in db , by phpmyadmin sql 这里的表'te'包含4个字段id,name,address,Aboutus,Aboutus是可选的,意味着如何通过phpmyadmin sql将默认文本更新为db中的Profile

I have changed not null to null for about us field 关于我们字段,我已将null更改为null

CREATE TABLE IF NOT EXISTS `te` (
  `id` int(30) NOT NULL,
  `name` text NOT NULL,
  `address` text NOT NULL,
  `Aboutus` text NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Here is your trigger BEFORE INSERT 这是你的BEFORE INSERT触发器

CREATE TRIGGER new_insert
BEFORE INSERT ON `te`
FOR EACH ROW 
SET NEW.`Aboutus` = CASE WHEN NEW.Aboutus IS NULL THEN 'Not Updated' ELSE NEW.Aboutus END
;

Insert without Aboutus 插入没有Aboutus

INSERT INTO `te` (`id`, `name`, `address`) 
VALUES (1, 'name', 'address') ;

Insert with Aboutus 插入Aboutus

INSERT INTO `te` (`id`, `name`, `address`, `Aboutus`) 
VALUES (2, 'name', 'address', 'Aboutus') ;

Insert by passing null Aboutus 通过传递null Aboutus插入

INSERT INTO `te` (`id`, `name`, `address`, `Aboutus`) 
VALUES (3, 'name', 'address', null) ;

Demo 演示

Edit As @garethD pointed a case for update scenario,you also need another trigger on BEFORE UPDATE so if null appears in update then aboutus should be updated as Not Updated 编辑@garethD指出了更新场景的情况,您还需要BEFORE UPDATE上的另一个触发器,因此如果更新中出现null,那么aboutus应该更新为Not Updated

CREATE TRIGGER update_trigger
BEFORE UPDATE ON `te`
FOR EACH ROW 
SET NEW.`Aboutus` = CASE WHEN NEW.Aboutus IS NULL THEN 'Not Updated' ELSE NEW.Aboutus END
;

UPDATE te
SET AboutUs = NULL;

Demo 2 演示2

For Ubuntu 16.04: 对于Ubuntu 16.04:

How to disable strict mode in MySQL 5.7: 如何在MySQL 5.7中禁用严格模式:

Edit file /etc/mysql/mysql.conf.d/mysqld.cnf 编辑文件/etc/mysql/mysql.conf.d/mysqld.cnf

If below line exists in mysql.cnf 如果mysql.cnf中存在以下行

sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Then Replace it with 然后用它替换它

sql_mode='MYSQL40'

Otherwise 除此以外

Just add below line in mysqld.cnf 只需在mysqld.cnf中添加以下行

sql_mode='MYSQL40'

This resolved problem. 这解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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