如何在 MySQL 5.1 中将 int 转换为一点?

How can I cast an int to a bit in MySQL 5.1?(如何在 MySQL 5.1 中将 int 转换为一点?)

本文介绍了如何在 MySQL 5.1 中将 int 转换为一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 SQL Server 过渡到 MySQL 5.1,并且似乎在尝试使用 select 语句创建表时遇到了困难,以便该列有点.

I am transitioning from SQL Server to MySQL 5.1 and seem to be tripped up trying to create a table using a select statement so that the column is a bit.

理想情况下,以下方法可行:

Ideally the following would work:

CREATE TABLE myNewTable AS
SELECT cast(myIntThatIsZeroOrOne as bit) AS myBit
FROM myOldtable

然而,sql 对转换有点不满意.我如何告诉它选择一个 int 列(我知道它只有 0 和 1)?

However sql is very unhappy at casting as a bit. How can I tell it to select an int column (which I know only has 0s and 1s) as a bit?

推荐答案

你不能!

CAST 和 CONVERT 仅适用于:

CAST and CONVERT only work to:

  • 二进制[(N)]
  • CHAR[(N)]
  • 日期
  • 日期时间
  • 十进制[(M[,D])]
  • 签名 [整数]
  • 时间
  • 无符号[整数]

没有空间用于:BIT、BITINT、TINYINT、MEDIUMINT、BIGINT、SMALLINT、......

No room for: BIT, BITINT, TINYINT, MEDIUMINT, BIGINT, SMALLINT, ...

但是,您可以创建自己的函数 cast_to_bit(n):

However, you can create your own function cast_to_bit(n):

DELIMITER $$

CREATE FUNCTION cast_to_bit (N INT) RETURNS bit(1)
BEGIN
    RETURN N;
END

要自己尝试,您可以创建包含多种转换的视图,例如:

To try it yourself, you can create view with several conversions like:

CREATE VIEW view_bit AS
    SELECT
        cast_to_bit(0),
        cast_to_bit(1),
        cast_to_bit(FALSE),
        cast_to_bit(TRUE),
        cast_to_bit(b'0'),
        cast_to_bit(b'1'),
        cast_to_bit(2=3),
        cast_to_bit(2=2)

...然后描述它!

DESCRIBE view_bit;

呸!!现在每个人都位(1)!!!

Ta-dah!! Everyone is bit(1) now!!!

这篇关于如何在 MySQL 5.1 中将 int 转换为一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 MySQL 5.1 中将 int 转换为一点?

基础教程推荐