您的问题可以通过运行简单的测试来回答:
drop table if exists golf;
create table golf(id int, int_col int, char_col varchar(50));
insert into golf(id, int_col, char_col) values
(1, 10, '10'),
(2, 20, '20');
select avg(int_col), avg(char_col) from golf;
结果:
avg(int_col) | avg(char_col)
15,0000 | 15
http://rextester.com/NNAZ9432
您可以看到 VARCHAR 列上的 AVG 返回预期结果。
现在添加一行 NULL 和 'disqualified'
drop table if exists golf;
create table golf(id int, int_col int, char_col varchar(50));
insert into golf(id, int_col, char_col)values
(1, 10, '10'),
(2, 20, '20'),
(2, NULL, 'disqualified');
select avg(int_col), avg(char_col) from golf;
现在结果不同了:
avg(int_col) | avg(char_col)
15,0000 | 10
http://rextester.com/RXOQAZ69820
reoson 是:NULL 被 AVG 忽略时,'disqualified' 被转换为 0,结果是 (10 + 20 + 0) / 3 = 10。 p>
要测试性能,您可以使用虚拟数据创建一个大表。在带有序列插件的 MariaDB 中,这可以轻松完成:
drop table if exists golf;
create table golf(id mediumint primary key, int_col smallint, char_col varchar(50));
insert into golf(id, int_col, char_col)
select seq id
, floor(rand(1)*1000) int_col
, floor(rand(1)*1000) char_col
from seq_1_to_1000000;
INT 上的 AVG:
select avg(int_col) from golf;
-- query time: 187 msec
VARCHAR 上的 AVG:
select avg(char_col) from golf;
-- query time: 203 msec
最后但并非最不重要的一点:您不应该将字符串类型用于数值。另一个原因是排序。如果您尝试对存储为字符串的数字进行排序,您将得到类似 [10, 2, 22, 3] 的结果。
您也不应该将一列用于不同的信息类型。在您的情况下,您可以再定义一列,例如status,其值为“已完成”或“不合格”。另一种可能的方法是设置一个标志列disqualified,其值为0 或1。