How can I use int in MySQL 5.1?

I am moving from SQL Server to MySQL 5.1 and it seems to have worked, trying to create a table using the select statement so that the column is a bit.

Ideally, the following:

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

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

+7
source share
4 answers

You can not!

CAST and CONVERT only work:

  • BINARY [(N)],
  • CHAR [(N)],
  • DATE
  • Datetime
  • DECIMAL [(M [, D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

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

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

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

To try it yourself, you can create a view with several transformations, for example:

 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) 

... and then describe it!

 DESCRIBE view_bit; 

Ted!! Now all the bit (1) !!!

+9
source

Try CONV(N,from_base,to_base)

Converts numbers between different base numbers. Returns a string representation of the number N, converted from base from_base to base to_base. Returns NULL if any argument is NULL. The argument N is interpreted as an integer, but can be specified as an integer or string. The minimum base is 2, and the maximum base is 36. If to_base is a negative number, N is considered a signed number. Otherwise, N is considered unsigned. CONV() works with 64-bit precision.

eg.

 select CONV(9, 10, 2); 
+2
source

Try specifying the length for the bit data type.

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

Try using a case:

 CREATE TABLE myNewTable AS SELECT (case myIntThatIsZeroOrOne when 1 then true else false end) AS myBit FROM myOldtable 
+1
source

All Articles