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

In MySQL, should I quote numbers or not?(在 MySQL 中,我应该引用数字还是不引用数字?)

本文介绍了在 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 中,我应该引用数字还是不引用数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 MySQL 中,我应该引用数字还是不引用数字?

基础教程推荐