同一 table 内的匹配百分比

percent match within the same table

下面我有一个 MySQL 数据库,其中 "id" 只是每一行的一个 ID。 "question" 显示问题的id。有四道题,11, 12, 13 and 14。对于每个问题,用户都有四个答案选项 (1,2,3 and 4),存储在 "answer" 列中。 "user" 列表示回答的用户。在此示例中,我们有用户 10、11 和 12

id      question    answer      user
1           11          2       10  
2           12          2       10
3           13          3       10
4           14          4       10
5           11          2       11
6           12          2       11
7           13          4       11
8           14          1       11
9           11          2       12          
10          12          2       12  
11          13          1       12
12          14          1       12

假设用户 10 是参考用户,这意味着我想知道用户 10 与其他用户的匹配度。使用 SQL and/or php 代码如何匹配用户的答案,以便我得到最高 [=24] 的匹配百分比=]百分比 首先显示。所以在这个例子中,我正在寻找类似的东西。

        user     percent    
1       11       50%
2       12       75%

我不确定仅使用 SQL 是否可行。例如,可能需要一点 php 才能将计数转换为 %

终于得到你想要的输出
试试这个:

SELECT * ,round(count(*)/(SELECT count(*) FROM `list` where user=10)*100) as
 pecentage FROM `list` as l where l.answer=(SELECT m.answer FROM `list` as m
 where m.user=10 and l.question=m.question) group by (l.user) order by pecentage

它将产生输出

如果你不想要 user 10 值,你可以在 where 条件中添加 l.user!=10