Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL CONCAT - Funny characters - but I'm not laughing

I am using this query to produce a blog archive menu, like so:

SELECT CONCAT( MONTHNAME(published) , ' ' , YEAR(published)) AS monthyear, 
COUNT(*) AS total
FROM blog_articles
WHERE status = 'Online' AND Year(published) = 2012
GROUP BY CONCAT( MONTHNAME(published) , ' ' , YEAR(published))

Expected result:

January 2012        103
February 2012       87
March 2012          23
April 2012          99

Actual result:

enter image description here

The count is correct but instead of the mental oriental, it should read:

May 2012       1

How can I get rid of the funny characters and have English instead?

When I run this query in phpMyAdmin, the characters are fine.

UPDATE

I have just tried running conn.Execute("SET lc_time_names = 'en_US';") and didn't solve the problem. To check, I used conn.Execute("SELECT @@lc_time_names;") and it returned "en_US".

ANOTHER UPDATE

Searching on MySQL forums for related issues, I found another guy whining about the same issue. A MySQL guru said:

"This is the famous (infamous) server returns wrong types for CONCAT of a number and a string. One has to use the (cast) form for this to work, the driver can't tell what the real type is."

I'm not sure what cast is or how to fix this issue.

like image 970
TheCarver Avatar asked Jul 01 '12 22:07

TheCarver


People also ask

How do I concatenate 3 columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

How do I concatenate two columns in SQL?

SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function. This method will change the original table.


1 Answers

Silly server, math is for numbers.

CAST() CAST(enum_col AS CHAR) - cast a value as a certain type

 SELECT CONCAT( CAST(MONTHNAME(published) as char) , ' ' , CAST(YEAR(published)) as char) AS monthyear, 
 COUNT(*) AS total
 FROM blog_articles
 WHERE status = 'Online' AND Year(published) = 2012
 GROUP BY CONCAT( MONTHNAME(published) , ' ' , YEAR(published))

DATE_FORMAT() You might also try DATE_FORMAT(YEAR(published), '%Y') function instead of CAST.

like image 149
user1166147 Avatar answered Oct 23 '22 14:10

user1166147