Php 下面的问题可以更正吗
在查询中,我需要一些帮助,我不知道我是否包含正确的GROUP BY子句,并在SELECT子句中从正确的表中选择字段: 以下是数据库表: 会话表Php 下面的问题可以更正吗,php,sql,mysqli,Php,Sql,Mysqli,在查询中,我需要一些帮助,我不知道我是否包含正确的GROUP BY子句,并在SELECT子句中从正确的表中选择字段: 以下是数据库表: 会话表 SessionId SessionName 1 AAA 2 AAB SessionId QuestionId QuestionContent QuestionMarks 1 1 What is 2+2? 2 1
SessionId SessionName
1 AAA
2 AAB
SessionId QuestionId QuestionContent QuestionMarks
1 1 What is 2+2? 2
1 2 What is 4+4? 3
2 1 What is 10+10 and 11+11? 5
2 2 What is 15+15? 5
2 3 What is 20+20 and 40+40? 7
AnswerId SessionId QuestionId Answer
1 1 1 B
2 1 2 C
3 2 1 A
4 2 1 D
5 2 2 A
6 2 3 D
7 2 3 E
问题表
SessionId SessionName
1 AAA
2 AAB
SessionId QuestionId QuestionContent QuestionMarks
1 1 What is 2+2? 2
1 2 What is 4+4? 3
2 1 What is 10+10 and 11+11? 5
2 2 What is 15+15? 5
2 3 What is 20+20 and 40+40? 7
AnswerId SessionId QuestionId Answer
1 1 1 B
2 1 2 C
3 2 1 A
4 2 1 D
5 2 2 A
6 2 3 D
7 2 3 E
答案表
SessionId SessionName
1 AAA
2 AAB
SessionId QuestionId QuestionContent QuestionMarks
1 1 What is 2+2? 2
1 2 What is 4+4? 3
2 1 What is 10+10 and 11+11? 5
2 2 What is 15+15? 5
2 3 What is 20+20 and 40+40? 7
AnswerId SessionId QuestionId Answer
1 1 1 B
2 1 2 C
3 2 1 A
4 2 1 D
5 2 2 A
6 2 3 D
7 2 3 E
以下是查询:
$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, GROUP_CONCAT(DISTINCT Answer SEPARATOR '') AS Answer, q.QuestionMarks
FROM Session s
INNER JOIN Question q ON s.SessionId = q.SessionId
JOIN Answer an ON q.QuestionId = an.QuestionId
WHERE SessionName = "AAB"
GROUP BY an.SessionId, an.QuestionId
";
我想显示属于会话“AAB”的每个问题。因此,它应该显示问题ID、问题内容、答案和问号,如下所示:
QuestionId QuestionContent Answer QuestionMarks
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
目前,如果我正在搜索会话“AAB”中的lets say问题,它将显示以下内容:
QuestionId QuestionContent Answer QuestionMarks
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
您的答案表中有一个会话ID,看起来您在加入时错过了该ID。此外,您不应该在组中使用DISTINCT,除非您多次存储同一问题/会话的同一答案是偶然的,在这种情况下,我将解决该意外,而不是在查询中编码变通方法
SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, GROUP_CONCAT(DISTINCT Answer SEPARATOR '') AS Answer, q.QuestionMarks
FROM Session s
INNER JOIN Question q ON s.SessionId = q.SessionId
JOIN Answer an ON q.QuestionId = an.QuestionId
AND an.sessionID = s.sessionID
WHERE SessionName = "AAB"
GROUP BY an.SessionId, an.QuestionId
您没有提到您的查询应该做什么。一个你期望的结果表会有帮助。输出和期望的结果是什么?在phpmyadmin中玩比猜测更容易:)分组不能只用于聚合函数?肯定需要更好地理解a)这些数据代表什么,b)你期望从查询中得到什么行为,c)你得到什么行为。是的,很抱歉,当你们在输出上发表评论时,我更新了这个问题,我更新了问题以包含输出wantedHi,是的,我也算出了,与您的答案完全相同。我正要发布我自己的答案,但幸运的是看到了你的答案。无论如何,最好的答案是给你