在 MySQL 中,我应该引用数字还是不引用数字?

2023-04-28数据库问题
4

本文介绍了在 MySQL 中,我应该引用数字还是不引用数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

例如 - 我从 cli 创建数据库和一个表并插入一些数据:

For example - I create database and a table from cli and insert some data:

CREATE DATABASE testdb CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
USE testdb;
CREATE TABLE test (id INT, str VARCHAR(100)) TYPE=innodb CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
INSERT INTO test VALUES (9, 'some string');

现在我可以做到这一点,并且这些示例确实有效(因此 - 引号似乎不会影响任何事情):

Now I can do this and these examples do work (so - quotes don't affect anything it seems):

SELECT * FROM test WHERE id = '9';
INSERT INTO test VALUES ('11', 'some string');

因此 - 在这些示例中,我通过 string 选择了一行,该行实际上在 mysql 中存储为 INT,然后我在 INT 列中插入了一个 string.

So - in these examples I've selected a row by a string that actually stored as INT in mysql and then I inserted a string in a column that is INT.

我不太明白为什么这里的工作方式如此.为什么允许在 INT 列中插入字符串?

I don't quite get why this works the way it works here. Why is string allowed to be inserted in an INT column?

我可以将所有 MySQL 数据类型作为字符串插入吗?

Can I insert all MySQL data types as strings?

这种行为是否跨不同 RDBMS 的标准?

Is this behavior standard across different RDBMS?

推荐答案

MySQL 与 PHP 非常相似,并且会尽其所能自动转换数据类型.由于您使用的是 int 字段(左侧),因此它也会尝试将参数的右侧透明地转换为 int,因此 '9' 只需变成9.

MySQL is a lot like PHP, and will auto-convert data types as best it can. Since you're working with an int field (left-hand side), it'll try to transparently convert the right-hand-side of the argument into an int as well, so '9' just becomes 9.

严格来说,引号是不必要的,强制MySQL做类型转换/转换,所以浪费了一点CPU时间.实际上,除非您运行的是 Google 规模的操作,否则这种转换开销将非常小.

Strictly speaking, the quotes are unnecessary, and force MySQL to do a typecasting/conversion, so it wastes a bit of CPU time. In practice, unless you're running a Google-sized operation, such conversion overhead is going to be microscopically small.

这篇关于在 MySQL 中,我应该引用数字还是不引用数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12