简体   繁体   English

使用MySQL将字符串转换为tinyint(布尔)

[英]using converting string to tinyint (bool) with mysql

Is there a way, using a TRIGGER or preferably some MySql function I'm not aware of, to automatically assign the value of a TINYINT column to '1' if ANY value is passed into it? 有没有办法使用TRIGGER或最好是我不知道的某些MySql函数,如果传递了任何值,则将TINYINT列的值自动分配为“ 1”?

For example if I have columnA ( TINYINT ) and I INSERT "doggybones" into that column: 例如,如果我有columnA( TINYINT ),并且在该列中INSERT “狗骨头”:

INSERT INTO mytable (columnA) VALUES ("doggybones")

... then mysql would automatically assign a value of "1" to columnA instead of kicking up an error about trying to stick a string into a TINYINT column? ...那么mysql将自动为columnA分配一个“ 1”值,而不是引发有关尝试将string粘贴到TINYINT列的错误?

It should also work so that if I insert "" - a blank value but the INSERT statement will still list it, like so: 它也应该起作用,以便如果我插入“”-一个空白值,但INSERT语句仍会列出它,如下所示:

INSERT INTO mytable (columnA) VALUES ("")

... then the column will receive a value of 0. ...则该列将收到值0。

Note: I know I could filter my values to just INSERT 0's and 1's but I'm wondering if there is a way to do this on the mysql side. 注意:我知道我可以将值过滤为仅插入0和1,但是我想知道是否有办法在mysql端执行此操作。

Unfortunately, SQL (all flavours) enforce data types strictly. 不幸的是,SQL(所有类型)都严格执行数据类型。
This happens before any trigger code runs. 这发生在任何触发代码运行之前。

You'll have to test for "" (empty string) 您必须测试“”(空字符串)

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

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