Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

aggregate functions - Weird behaviour of SUM and CONCAT in MySql

If I want to make a sum of a specific numeric column in MySQL, I do

SELECT SUM(MyColumn) FROM MyTable WHERE 1;

This returns for example number 100.

But I'd like to prepend some text to the sum value, so I do

SELECT CONCAT('Sum is: ',SUM(MyColumn)) FROM MyTable WHERE 1;

but instead of getting Sum is: 100 I get something like 546573743a20343030.

Is this a bug or a feature? What am I doing wrong?

UPDATE

SELECT CONCAT('Sum is: ',CAST(SUM(MyColumn) AS varchar(20))) FROM MyTable WHERE 1;

Casting to varchar doesn't work: getting SQL syntax error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As FreshPrinceOfSO suggested in the comments below my question, MySQL server doesn't handle casts to varchar.

So even though the query

SELECT CONCAT('Sum is: ',CAST(SUM(MyColumn) AS varchar(20))) FROM MyTable WHERE 1;

results in syntax error, casting to char instead works just fine:

SELECT CONCAT('Sum is: ',CAST(SUM(MyColumn) AS char(20))) FROM MyTable WHERE 1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...