获取具有最大出现次数的外键

时间:2015-12-19 10:46:29

标签: mysql database

我有以下表格。

用户
enter image description here

选项
enter image description here

问题
enter image description here

答案
enter image description here

我想获取以下记录

  1. 按用户分组的答案数
  2. 按用户分组的回答最多的选项
  3. 我尝试使用以下查询

    SELECT
        u.id,
        u.email,
        COUNT(a.question_id) as number_of_answers
    FROM
        user u
    LEFT JOIN
        answer a ON (a.user_id = u.id)
    GROUP BY
        u.id;
    

    这给了我以下结果

    enter image description here

    我现在想要获取每个用户最常用的选项,参考上面的图片,我期待以下结果

    -----------------------
    user_id  |   option_id
    -----------------------
    1        |   null
    2        |   3
    3        |   null
    -----------------------
    

    如何去做?

    感谢。

    更新:

    此查询为我提供了最接近的结果

    SELECT
        u.id,
        u.email,
        COUNT(a.question_id) as number_of_answers,
        (SELECT a2.option_id FROM answer a2 WHERE a2.user_id = u.id GROUP BY a2.option_id ORDER BY COUNT(a2.option_id) DESC LIMIT 1) as option_id
    FROM
        user u
    LEFT JOIN
        answer a ON (a.user_id = u.id)
    GROUP BY
        u.id;
    

    现在的问题是它没有按照我的预期订购option_id,如果有相同数量的最大出现次数,我希望最后一次出现option_id,参考下图中的内容。

    enter image description here

    它给了我以下结果

    +-----------+-----------+
    | option_id | occurence |
    +-----------+-----------+
    |         5 |         2 |
    +-----------+-----------+
    

    我期待以下

    +-----------+-----------+
    | option_id | occurence |
    +-----------+-----------+
    |         1 |         2 |
    +-----------+-----------+
    

    原因是,option_id是最后记录的选项。我在这里缺少的任何暗示?

0 个答案:

没有答案
相关问题