我需要计算表的行数,然后对结果进行子串。为了得到我需要的东西,我尝试了这个:
SELECT substring(count(1),1,1) FROM users
以下查询返回85
:
SELECT count(1) FROM users
当预期值为38
时,第一个查询会返回8
。为什么会这样?
答案 0 :(得分:1)
应该是
SELECT substring(cast(count(1) as char), 1, 1) FROM users
答案 1 :(得分:1)
为什么会发生这种情况是因为substring
的结果被隐式转换为binary
(由于不同的字符集,我没有得到38)。
select count(1) from users;
| count(1) |
|----------|
| 85 |
如果我使用与您相同的方法:
select substring(count(1),1,1) from users;
| substring(count(1),1,1) |
|-------------------------|
| OA== |
与将结果转换为二进制文件相同:
select cast(substring(count(1),1,1) as binary) from users;
| cast(substring(count(1),1,1) as binary) |
|-----------------------------------------|
| OA== |
但如果我将结果转换为char,我得到正确的结果:
select cast(substring(count(1),1,1) as char) from users;
| cast(substring(count(1),1,1) as char) |
|---------------------------------------|
| 8 |
如果我将count(1)转换为char:
select substring(cast(count(1) as char),1,1) from users;
| substring(cast(count(1) as char),1,1) |
|---------------------------------------|
| 8 |