MYSQL - 获取所有具有同一ID的多个记录的记录

4

如果我没有正确解释,我提前道歉。我甚至很难用英语来解释,更不用说在mysql查询中了。

我正在尝试获取具有多个记录的question_idresponse_set_ids列表。

这是我的数据示例:

+----+-----------------+-------------+-----------+
| id | response_set_id | question_id | answer_id |
+----+-----------------+-------------+-----------+
|  1 |              10 |           1 |         4 |
|  2 |              10 |           2 |         5 |
|  3 |              10 |           3 |         6 |
|  4 |              10 |           3 |         7 |
|  5 |              11 |           1 |         8 |
|  6 |              11 |           2 |         9 |
|  7 |              11 |           3 |        10 |
+----+-----------------+-------------+-----------+

我想要一个查询,返回一个包含 response_set_id 的列表,而在这个特定的示例中,我期望被返回 10,因为该 response_set 具有多次出现的 question_id -> 3
如果您需要任何进一步的信息来帮助我,请告诉我。
我已经尝试过这个查询: select response_set_id, count(question_id) from responses group by response_set_id; 但这只给我返回每个 response_set 中问题的数量。
提前感谢!

请见下方答案: - Daniel Marcus
3个回答

1
select distinct response_set_id from (
    select  response_set_id , question_id  
    from 
    responses
    group by 
    response_set_id, question_id
    having count(*)>1) a

谢谢!但这个也不起作用 :( 它没有返回任何结果,本应至少返回 1 条记录。我会思考一下,如果我弄清楚了为什么它不工作,我会回来告诉你的。 - Kashlin
抱歉,移除了ID - 现在应该可以工作了 - 请参见上面的更新。 - Daniel Marcus
1
随时 - 如果您需要其他任何帮助,请告诉我。 - Daniel Marcus

1

最简单的方法不使用子查询:

SELECT DISTINCT response_set_id
FROM responses
GROUP BY response_set_id, question_id
HAVING COUNT(*) > 1;

这是极少数情况之一,select distinctgroup by(适当地)一起使用。

更好了!运行得很好。谢谢。 - Kashlin

0

我相信这个问题以前已经被问过了,但是由于我的声望不够,我无法添加评论:

SELECT DISTINCT response_set_id
FROM responses
GROUP BY question_id
HAVING COUNT(question_id) > 1

2
我相信已经有成千上万次了。 - Daniel Marcus
这个方法不起作用,它返回了与我想要的不匹配的记录。如果这已经被问了成千上万次,那么请原谅我,因为我找不到有效的解决方案。我需要查找具有相同question_id的response_set_id。question_id可能会在其他response_set_id中使用。 - Kashlin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接