11

I have a very simple rating system in my database where each rating is stored as an enum('1','-1'). To calculate the total I tried using this statement:

SELECT SUM(CONVERT(rating, SIGNED)) as value from table WHERE _id = 1

This works fine for the positive 1 but for some reason the -1 are parsed out to 2's.

Can anyone help or offer incite?

Or should I give up and just change the column to a SIGNED INT(1)?

6 Answers 6

24

this is what you want

select enum+0 as enum
Sign up to request clarification or add additional context in comments.

1 Comment

you will add 0 to value sequence order value of your enum type : 1st, 2nd, 3rd, etc ... CAST(CAST(rating AS CHAR) AS SIGNED) is the right solution
17

This conversion to int in MySQL for enum is only possible:

CAST(CAST(`rating` AS CHAR) AS SIGNED) as value from table WHERE _id = 1

Comments

6

Yes, I'd suggest to change the type of the column. The issue becomes clear when you read the doc about enum type (which strongly recommends not to use numbers as enumeration values!) - the index of the enum item is returned, not the enum value itself.

3 Comments

Well, it'd be even more descriptive to change the enum values to up and down!
Perhaps, but if he needs to do a lot of this kind of "rating arithmetic" it quickly becomes tedious (and slow)... much simpler to operate with "plain integer values".
yea I went ahead and changed it after posting this question. Thanks for the explanation tho. Very helpful
2

Ok guys,

Just had a bit of a mere of a time with this one. I learned that i shouldn't use ENUMs where integers are the values. However We had years worth of data and i couldn't alter the database.

This bad boy worked (turning it into a character, then into a signed int).

CAST(CAST(`rating` AS CHAR) AS SIGNED) as value from table WHERE _id = 1

Comments

0

use

SELECT SUM( IF( columnname >0, CAST( columnname AS CHAR ) , NULL ) ) AS vals
FROM `tableName` 

1 Comment

Hi! How does this help? Feel free to explain a bit more and to use code formatting.
0

I wouldn't use enum here too, but it is still possible in this case to get what is needed

Creating table:

CREATE TABLE test (
    _id INT PRIMARY KEY,
    rating ENUM('1', '-1')
);

Filling table:

INSERT INTO test VALUES(1, "1"), (2, "1"), (3, "-1"), (4, "-1"), (5, "-1");

Performing math operations on enums converts them to indexes, so it is possible just to scale the result value:

SELECT 
    SUM(3 - rating * 2)
FROM
    test;

Result: -1 which is true for the test case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.