在Sql中执行/(a + b)

时间:2018-06-18 05:35:06

标签: mysql sql mysqli

我正在执行以下代码,但我无法获得正确的百分比作为输出

Select
name,
fans,
useful,
funny,
(useful/(Select (useful+funny) from user)) As useful_percent
From user
Order by fans desc
limit 10

输出就像这样,

+-----------+------+--------+--------+----------------+
| name      | fans | useful |  funny | useful_percent |
+-----------+------+--------+--------+----------------+
| Amy       |  503 |   3226 |   2554 |             36 |
| Mimi      |  497 |    257 |    138 |              2 |
| Harald    |  311 | 122921 | 122419 |           1381 |
| Gerald    |  253 |  17524 |   2324 |            196 |
| Christine |  173 |   4834 |   6646 |             54 |
| Lisa      |  159 |     48 |     13 |              0 |
| Cat       |  133 |   1062 |    672 |             11 |
| William   |  126 |   9363 |   9361 |            105 |
| Fran      |  124 |   9851 |   7606 |            110 |
| Lissa     |  120 |    455 |    150 |              5 |
+-----------+------+--------+--------+----------------+

有人请解释一下代码出了什么问题?

3 个答案:

答案 0 :(得分:1)

您的选择应该会导致错误,因为(Select (useful+funny) from user)会返回多行。

你可能想要

Select
  name,
  fans,
  useful,
  funny,
  100.0 * useful/(useful+funny) As useful_percent
From user
Order by fans desc
limit 10

答案 1 :(得分:1)

我建议你使用nullif()来避免被零除的问题:

Select name, fans, useful, funny,
       useful / nullif(useful + funny, 0) As useful_percent
From user
Order by fans desc
limit 10;

如其他答案所述,子查询不合适。

答案 2 :(得分:0)

尝试这个简单的查询。

Select
  name,
  fans,
  useful,
  funny,
  (useful/(useful+funny)) As useful_percent
From user
Order by fans desc
limit 10

或者useful_percent(%)值然后使用像

这样的查询
Select
  name,
  fans,
  useful,
  funny,
 ((useful/(useful+funny)) * 100.0)  As useful_percent
From user
Order by fans desc
limit 10