ISSUE: Mysql converting Enum to Int

前端 未结 6 689
醉话见心
醉话见心 2021-01-11 18:25

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:



        
6条回答
  •  醉梦人生
    2021-01-11 18:56

    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.

提交回复
热议问题