Home Database Mysql Tutorial How to perform type conversion in mysql

How to perform type conversion in mysql

Jan 05, 2022 pm 02:59 PM
mysql type conversion

Conversion method: 1. Use the " " operator, the syntax is "SELECT 1 'String';"; 2. Use the CAST() function to convert any type to a specified type, the syntax is "CAST(expr AS type)"; 3. Use the DATE_FORMAT() function to convert the date into a string according to the given pattern.

How to perform type conversion in mysql

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

1. The concept of implicit type conversion and explicit type conversion

Implicit type conversion:

To perform operations or comparisons between two values, the data types must first be consistent. Implicit type conversion occurs when two data types are found to be inconsistent. For example, convert a string into a number, or vice versa:

SELECT 1+'1'; – 字符串1转成数字
SELECT concat(2,'test'); – 数字2转成字符串

Explicit type conversion:

Use functions to convert data types

2.Cast function

##CAST(expr AS type)

Convert any type of expression expr into a value of the specified type type. type can be any of the following types:

  • BINARY[(N)]: binary string, the length after conversion is less than N bytes (if the length is less than N, 0x00 will be added at the end)

  • CHAR[(N)]: String, the length after conversion is less than N characters

  • DATE: Date

  • DATETIME: Date and time

  • DECIMAL[(M[,N])]: Floating point number, M is the total number of digits (including the integer part and the decimal part) , N is the number of digits after the decimal point

  • ##SIGNED [INTEGER]: Signed integer
  • TIME: Time
  • UNSIGNED [INTEGER]: Unsigned integer
Convert string to number

When converting to decimal, scan characters from the beginning String up to the first non-numeric character. Round the truncated digit

1) By default, M and N are not limited, converted to an integer, and rounded to the first decimal place:

SELECT cast(‘28.82abc’ AS DECIMAL);

How to perform type conversion in mysql

2) Limit M but not limit N, convert it to an integer (M should be as large as possible):

SELECT cast(‘28.82abc’ AS DECIMAL(4));

How to perform type conversion in mysqlIf M When the length is less than the actual number of digits, it will be converted to the maximum value of the set number of digits. In the following conversion, M is 1, that is, the two-digit number 29 cannot be displayed, and the largest one-digit number, 9

SELECT cast(‘28.82abc’ AS DECIMAL(1));

How to perform type conversion in mysql, is limited to M and N, which must be First satisfy N decimal places after the decimal point. In the following example, 1 decimal place is satisfied first, and then 1 integer is taken:

SELECT cast(‘28.82abc’ AS DECIMAL(2,1));

How to perform type conversion in mysql 2 decimal places are satisfied first, and the integer part is not taken:

SELECT cast(‘28.82abc’ AS DECIMAL(2,2));

SELECT cast(‘28.82abc’ AS UNSIGNED);
How to perform type conversion in mysql

How to perform type conversion in mysql

SELECT cast(’-28abc’ AS SIGNED);

How to perform type conversion in mysql

##String to date

SELECT cast(‘2007-12-25’ AS DATETIME);

SELECT cast(‘2007-12-25’ AS DATE);

How to perform type conversion in mysql

SELECT cast(‘20:20:20’ AS TIME);

How to perform type conversion in mysql

The date format must be 'YYYY-MM-DD'How to perform type conversion in mysql

SELECT cast(‘25-12-2007’ AS DATETIME);
SELECT cast(‘2007-may-25’ AS DATETIME);

How to perform type conversion in mysql
How to perform type conversion in mysql

Number to string

SELECT cast(123 AS CHAR);
 SELECT cast(123 AS BINARY);

Date to string

SELECT cast(now() AS CHAR);

How to perform type conversion in mysql

String to binary string

二进制字符串:二进制字符串被视为一个连续的字节序列,与字符集无关。非二进制字符串(即我们通常所说的字符串)被视为一个连续排列的字符序列,与字符集有关。所谓与字符集无关,是指与MySQL自己的字符集无关,而是按照操作系统的字符集把字符串转换成字节进行存储

两种字符串的比较方式:二进制字符串的比较方式是一个字节一个字节进行的,比较的依据是两个字节的二进制值。因为同一个字母的大小写的数值编码是不一样的,因此它是区分大小写的。另外,由于它和字符集无关,因此也就没有大写和小写字母一说

非二进制字符串的比较方式是一个字符一个字符进行的,比较的依据是两个字符在字符集中的先后顺序。根据使用的校对不同,可以进行区分大小写的比较和不区分大小写的比较

使用CAST(str AS BINARY)将字符串转换成二进制字符串时,通常使用它的快捷方式写法: BINARY str

查看当前字符集和校对规则设置

SHOW VARIABLES LIKE ‘collation_%’;

How to perform type conversion in mysql

在比较表达式中,binary影响后面所有的字符串,并且不会忽略字符串的尾部空格

SELECT ‘a’ = ‘A’ ,BINARY ‘a’ = ‘A’;
 SELECT ‘a’ = 'a ',BINARY ‘a’ = 'a ';

How to perform type conversion in mysql

How to perform type conversion in mysql

Cast(col_name as date_type)

将指定的列或者表达式转换为指定的数据类型

使用场景:当两个值进行比较,但是数据源的表中列的数据不一致,这个时候可以使用cast函数进行转化

3.Convert函数

CONVERT(expr, type), CONVERT(expr USING sharset_name)

convert函数的作用和cast函数几乎相同,但是它可以把字符串从一种字符集转换成另一种字符集。下例将字符串’abc’从默认的字符集转换成utf8字符集

SELECT convert(‘abc’ USING utf8);

How to perform type conversion in mysql

SELECT convert(‘你好’ USING gbk);

How to perform type conversion in mysql

如果目标字符集不能表示该字符,则返回乱码

SELECT convert(‘你好’ USING latin1);

How to perform type conversion in mysql

日期字符串转换函数

DATE_FORMAT(date, format)

将日期date按照给定的模式format转换成字符串。format中可使用以下模式元素
How to perform type conversion in mysql

How to perform type conversion in mysql

SELECT date_format(‘2009-10-04 22:23:00’, ‘%W %M %Y’);

How to perform type conversion in mysql

SELECT date_format(now(), ‘%W %M %Y’);

How to perform type conversion in mysql

SELECT date_format(‘2007-10-04 22:23:00’, ‘%H:%i:%s’);

How to perform type conversion in mysql

TIME_FORMAT(date, format)

format中只可使用时、分、秒和微秒模式元素

SELECT time_format(‘22:23:01’, ‘%H.%i.%s’);

How to perform type conversion in mysql

STR_TO_DATE(str, format)

将字符串str以指定的模式format转换成日期。format中可以包含模式元素和字面量,字面量必须匹配str中的字面量:

SELECT str_to_date(‘01,5,2013’,’%d,%m,%Y’);
SELECT str_to_date(‘May 1, 2013’,’%M %d,%Y’);

How to perform type conversion in mysql
以下在会话变量@@sql_mode设置中包含no_zero_date和no_zero_in_date时转换失败,没有包含这些设置时转换成功

SELECT str_to_date(‘a09:30:17’,‘a%h:%i:%s’);
 SELECT str_to_date(‘09:30:17a’,’%h:%i:%s’);

How to perform type conversion in mysqlHow to perform type conversion in mysql

【相关推荐:mysql视频教程

The above is the detailed content of How to perform type conversion in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization model How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization model Jul 23, 2025 pm 07:21 PM

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

Setting up semi-synchronous replication in MySQL Setting up semi-synchronous replication in MySQL Jul 15, 2025 am 02:35 AM

The steps for setting MySQL semi-synchronous replication are as follows: 1. Confirm the version supports and load the plug-in; 2. Turn on and enable semi-synchronous mode; 3. Check the status and operation status; 4. Pay attention to timeout settings, multi-slave library configuration and master-slave switching processing. It is necessary to ensure that MySQL 5.5 and above versions are installed, rpl_semi_sync_master and rpl_semi_sync_slave plugins, enable corresponding parameters in the master and slave library, and configure automatic loading in my.cnf, restart the service after the settings are completed, check the status through SHOWSTATUS, reasonably adjust the timeout time and monitor the plug-in operation.

how to connect excel to mysql database how to connect excel to mysql database Jul 16, 2025 am 02:52 AM

There are three ways to connect Excel to MySQL database: 1. Use PowerQuery: After installing the MySQLODBC driver, establish connections and import data through Excel's built-in PowerQuery function, and support timed refresh; 2. Use MySQLforExcel plug-in: The official plug-in provides a friendly interface, supports two-way synchronization and table import back to MySQL, and pay attention to version compatibility; 3. Use VBA ADO programming: suitable for advanced users, and achieve flexible connections and queries by writing macro code. Choose the appropriate method according to your needs and technical level. PowerQuery or MySQLforExcel is recommended for daily use, and VBA is better for automated processing.

Automating MySQL Deployments with Infrastructure as Code Automating MySQL Deployments with Infrastructure as Code Jul 20, 2025 am 01:49 AM

To achieve MySQL deployment automation, the key is to use Terraform to define resources, Ansible management configuration, Git for version control, and strengthen security and permission management. 1. Use Terraform to define MySQL instances, such as the version, type, access control and other resource attributes of AWSRDS; 2. Use AnsiblePlaybook to realize detailed configurations such as database user creation, permission settings, etc.; 3. All configuration files are included in Git management, support change tracking and collaborative development; 4. Avoid hard-coded sensitive information, use Vault or AnsibleVault to manage passwords, and set access control and minimum permission principles.

mysql incorrect string value for column mysql incorrect string value for column Jul 15, 2025 am 02:40 AM

MySQL error "incorrectstringvalueforcolumn" is usually because the field character set does not support four-byte characters such as emoji. 1. Cause of error: MySQL's utf8 character set only supports three-byte characters and cannot store four-byte emoji; 2. Solution: Change the database, table, fields and connections to utf8mb4 character set; 3. Also check whether the configuration files, temporary tables, application layer encoding and client drivers all support utf8mb4; 4. Alternative solution: If you do not need to support four-byte characters, you can filter special characters such as emoji at the application layer.

How to set environment variables in PHP environment Description of adding PHP running environment variables How to set environment variables in PHP environment Description of adding PHP running environment variables Jul 25, 2025 pm 08:33 PM

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

How to use PHP to develop product recommendation module PHP recommendation algorithm and user behavior analysis How to use PHP to develop product recommendation module PHP recommendation algorithm and user behavior analysis Jul 23, 2025 pm 07:00 PM

To collect user behavior data, you need to record browsing, search, purchase and other information into the database through PHP, and clean and analyze it to explore interest preferences; 2. The selection of recommendation algorithms should be determined based on data characteristics: based on content, collaborative filtering, rules or mixed recommendations; 3. Collaborative filtering can be implemented in PHP to calculate user cosine similarity, select K nearest neighbors, weighted prediction scores and recommend high-scoring products; 4. Performance evaluation uses accuracy, recall, F1 value and CTR, conversion rate and verify the effect through A/B tests; 5. Cold start problems can be alleviated through product attributes, user registration information, popular recommendations and expert evaluations; 6. Performance optimization methods include cached recommendation results, asynchronous processing, distributed computing and SQL query optimization, thereby improving recommendation efficiency and user experience.

How to build an online customer service robot with PHP. PHP intelligent customer service implementation technology How to build an online customer service robot with PHP. PHP intelligent customer service implementation technology Jul 25, 2025 pm 06:57 PM

PHP plays the role of connector and brain center in intelligent customer service, responsible for connecting front-end input, database storage and external AI services; 2. When implementing it, it is necessary to build a multi-layer architecture: the front-end receives user messages, the PHP back-end preprocesses and routes requests, first matches the local knowledge base, and misses, call external AI services such as OpenAI or Dialogflow to obtain intelligent reply; 3. Session management is written to MySQL and other databases by PHP to ensure context continuity; 4. Integrated AI services need to use Guzzle to send HTTP requests, safely store APIKeys, and do a good job of error handling and response analysis; 5. Database design must include sessions, messages, knowledge bases, and user tables, reasonably build indexes, ensure security and performance, and support robot memory

See all articles