我正在使用PHP,我有以下两个表:
REVIEWS
| id | Item | editor_rating | user_votes |
------------------------------------------------
| 1 | item_1 | 18.1 | 415 |
| 2 | item_2 | 17.1 | 371 |
| 3 | item_3 | 14.7 | 111 |
| 8 | item_8 | 15.3 | 215 |
| 9 | item_9 | 17.7 | 119 |
| 10 | item_10 | 17.0 | 66 |
FILTERS
| id | Item | published |
----------------------------------
| 1 | item_1 | 1 |
| 2 | item_2 | 1 |
| 3 | item_3 | 1 |
| 8 | item_8 | 1 |
| 9 | item_9 | 1 |
| 10 | item_10 | 1 |
以下查询正常工作并返回所有行:
SELECT * FROM reviews AS r
JOIN filters AS f ON (r.id = f.id)
WHERE f.published = 1
所以我的方式正确。 现在我想对记录做一些数学运算。例如 sum 字段 editor_rating 和 user_votes ,并列出DESC排序的行。我尝试了以下但它返回不正确的结果(不是MySQL错误,总和错误):
SELECT *, r.editor_rating+r.user_votes AS total FROM reviews AS r
JOIN filters AS f ON (r.id = f.id)
WHERE f.published = 1 ORDER BY total DESC
上表包含实际的dB数据。通过总结 editor_rating 和 user_votes ,我应该按如下方式订购一个列表:
18.1 + 415 = 433.1 = Item_1
17.1 + 371 = 388.1 = Item_2
15.3 + 215 = 230.3 = Item_8
而是我得到以下列表:
Item_8
Item_9
Item_10
答案 0 :(得分:0)
首先检查这些值是否为varchar,然后必须先将其强制转换:
SELECT *, cast(r.editor_rating as unsigned )+ cast(r.user_rating as unsigned ) AS total FROM reviews AS r JOIN filters AS f ON (r.id = f.id) WHERE f.published = 1 ORDER BY total DESC
当我首先将它转换为无符号整数时,它会为我运行..