如何使用单个查询计算 SQL (MySQL) table 中行的出现概率?

How to compute occurence probability of rows inside a SQL (MySQL) table using a single query?

我有一个 table 包含一些代表游戏对象的类似行。我使用此 table 作为随机 select 对象的一种方式。当然,我忽略了table的大小。我的问题是我想有一个查询 return 是 select 每个对象的概率,但我不知道如何继续。

我可以得到我的对象总数 table:

select count(id) from objects_desert_tb;

哪个returns

+-----------+
| count(id) |
+-----------+
|        81 |
+-----------+
1 row in set (0.00 sec)

我有一个查询 return table 中每个对象的出现次数:

select name, (count(name)) from objects_desert_tb group by name;

给出:

+-------------------+---------------+
| name              | (count(name)) |
+-------------------+---------------+
| carrots           |             5 |
| metal_scraps      |            14 |
| plastic_tarpaulin |             8 |
| rocks_and_stones  |            30 |
| wood_scraps       |            24 |
+-------------------+---------------+
5 rows in set (0.00 sec)

计算每个对象的概率只需将 (count(name)) 除以 table 中的总行数。例如,对于胡萝卜行,只需根据上面给出的两个查询计算 5/81。我想要一个 return:

的查询
+-------------------+---------------+
| carrots           |             5/81 = 0.06172839
| metal_scraps      |            0.1728...
| plastic_tarpaulin |            0.09876...
| rocks_and_stones  |            0.37...
| wood_scraps       |            0.29...
+-------------------+---------------+

有没有办法将 table 的大小用作 SQL 查询中的变量?也许通过嵌套几个查询?

交叉连接您的查询:

select c.name, c.counter / t.total probability
from (
  select name, count(name) counter 
  from objects_desert_tb 
  group by name
) c cross join (
  select count(id) total 
  from objects_desert_tb 
) t 

在 MySQL 8+ 中,您只需使用 window 函数:

select name, count(*) as cnt,
       count(*) / sum(count(*)) over () as ratio
from objects_desert_tb 
group by name;