Mysql入门技能树-数据类型

数据类型

数值的隐式类型转换

Joe 需要使用下列表做一项数值计算

create table points(
    id int primary key auto_increment,
    x int,
    y int
);

计算查询为:

select id, (x^2 + y^2)/2 as result from points;

得到的结果集中,result 列的类型应该是:

答案是:A
^(位异或)对两个整数值执行“位异或”运算.它会将第一个操作数的每一位与第二个操作数中对应的每一位进行比较.如果一位是 0,另一对应位是 1,则相应结果位设置为 1.如果两位都是 0 或两位都是 1,则相应结果位设置为 0.两个条件必须都为有符号的整数数据类型,或都为无符号的整数数据类型。
下面我们开始验证:

select id,x,y,x^2,y^2, (x^2 + y^2)/2 as result from points;
create table temp_points as
select id,x,y,x^2,y^2, (x^2 + y^2)/2 as result from points;

select column_name, data_type, ordinal_position
from information_schema.columns
where table_name = 'temp_points';

时间默认值

Joe 写了一个订单表的创建语句:

create table orders (
    id int primary key auto_increment,
    item_id int,
    amount int,
    unit_price decimal(12, 4),
    price decimal(12, 4)
);

现在,Joe 需要给这个表加入下单时间,即订单写入数据库的时间,那么他应该将这个语句修改为:


答案是:C
但是在我看来D也是对的,那么我们来验证下datetime

drop table if exists orders;
create table orders (
id int primary key auto_increment,
item_id int,
amount int,
unit_price decimal(12, 4),
price decimal(12, 4),
ts datetime default now()
);
insert into orders(id,item_id,amount,unit_price,price) values(1,2,3,4,5);
select * from orders;

再来看看timestamp

drop table if exists orders;
create table orders (
id int primary key auto_increment,
item_id int,
amount int,
unit_price decimal(12, 4),
price decimal(12, 4),
ts timestamp default now()
);
insert into orders(id,item_id,amount,unit_price,price) values(1,2,3,4.2,5.2);
select * from orders;

所以datetime和timestamp都正确

文本字段

Joe 在设计订单表,他已经完成了下列内容:

create table orders (
    id int primary key auto_increment,
    item_id int,
    amount int,
    unit_price decimal(12, 4),
    price decimal(12, 4),
    ts timestamp default now()
);

现在他需要给订单表加入一个 description 字段,这个字段需要保存订单的文字说明,这些文本不会超过两千字节, Joe 应该把建表语句修改为:


答案是:C
A中首先TINYTEXT用法错误,创建时不能指定长度,其次最多TINYTEXT可以存储255个字符,当订单文本说明超过255个字符时无法保存;
B中指定了长度256,当订单文本说明超过256个字符时也无法保存;
D中text定义时通常不用指定长度,所以是错的。
MySQL中,文本字符串总体上分为CHAR、VARCHAR、TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT、ENUM、SET和JSON等类型,每种存储类型所占的存储空间如表9-8所示。

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空空star

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值