1

I have a problem with an IF() clause on my query statement. I am simply moving an integer to another column that I dynamically create in my query statement but the integer loses its attribute classification and MySQL treats it as a string.

mysql_query('
    SELECT id, statusDate, displayName, earnings,
        IF(statusDate <> "0000-00-00 00:00:00", earnings, "0") as earnings1
    FROM my_table
    ORDER BY statusDate, earnings1 DESC, displayName
');

I have some earnings in the table such as 10, 50, 200, etc.

Since I am doing a descending order by, I am expecting: 200 50 10

But what I am getting is: 10, 200, 50

Any idea on how I can retain earnings as an integer, when moving to earnings1?

Thank you.

4

3 回答 3

3

如果函数中的两个参数IF都是数字,则不应出现此问题。所以如果earnings是数字,试试这个earnings1值:

IF(status <> "0000-00-00 00:00:00", earnings, 0) as earnings1

                                              ^ note no more quotes
于 2013-06-28T19:17:17.227 回答
1

这对你有用吗?

SELECT id, statusDate, displayName, earnings,
    (CAST( IF(statusDate <> "0000-00-00 00:00:00", earnings, 0) AS SIGNED)) as earnings1
于 2013-06-28T19:12:21.097 回答
1

您可能希望使用 CASE 语句,更重要的是,从 0 中删除引号 " 以保留 int 数据类型。

SELECT id, statusDate, displayName, earnings,
    CASE WHEN statusDate <> "0000-00-00 00:00:00" 
    THEN earnings
    ELSE  0 
    END as earnings1
FROM my_table
ORDER BY statusDate, earnings1 DESC, displayName
于 2013-06-28T19:16:52.630 回答