如果所有数据都相同,如何显示一次行

时间:2012-11-11 14:06:00

标签: mysql sql

我的查询如下:

$questionquery = "
SELECT DISTINCT q.QuestionContent, o.OptionType, q.NoofAnswers, GROUP_CONCAT(DISTINCT Answer ORDER BY Answer SEPARATOR '') AS Answer, r.ReplyType, 
q.QuestionMarks, q.SessionId
FROM Answer an 
INNER JOIN Question q ON q.QuestionId = an.QuestionId and an.SessionId = q.SessionId
JOIN Reply r ON q.ReplyId = r.ReplyId 
JOIN Option_Table o ON q.OptionId = o.OptionId 
WHERE ".implode(" AND ", array_fill(0, $numTerms, "q.QuestionContent LIKE ?"))."
GROUP BY an.SessionId, an.QuestionId
ORDER BY ".implode(", ", array_fill(0, $numTerms, "IF(q.QuestionContent LIKE ?, 1, 0) DESC"))."
";

现在,下面是每个数据库表的样子:

会议桌:

SessionId  SessionName
1          AAA
2          AAB
3          AAC

问题表:

SessionId  QuestionId QuestionContent              ReplyId OptionId
1          1          Here is a single answer      2       1
2          3          Here is a single answer      2       1
3          3          Here is a single answer      2       1

答案表:

AnswerId  SessionId QuestionId Answer
1         1         1          True
2         2         3          True
3         3         3          True

回复表:

ReplyId  ReplyType
1        Single
2        Multiple

选项表:

OptionId  OptionType
1         True or False

现在我遇到的问题是,在数据库中,我有三个完全相同的问题并且具有相同的答案,相同的标记,相同的选项类型等,所有相同的都没问题。但在查询中我想要做的是,如果有多个行的列都匹配,那么只显示一次。所以目前它正在显示以下作为查询输出:

Here is a single answer     True or False   1   True    Multiple    5   
Here is a single answer     True or False   1   True    Multiple    5   
Here is a single answer     True or False   1   True    Multiple    5

但由于问题的所有细节都是相同的,所以它应该只显示一次如下:

Here is a single answer     True or False   1   True    Multiple    5 

如果有多行具有完全相同的数据,如何让查询显示一行?

更新

   $questionquery = "
SELECT DISTINCT q.QuestionContent, o.OptionType, q.NoofAnswers, Answer, r.ReplyType, 
q.QuestionMarks
 FROM
(
SELECT DISTINCT q.QuestionContent, o.OptionType, q.NoofAnswers, GROUP_CONCAT(DISTINCT Answer ORDER BY Answer SEPARATOR '') AS Answer, r.ReplyType, 
q.QuestionMarks, q.SessionId
FROM Answer an 
INNER JOIN Question q ON q.QuestionId = an.QuestionId and an.SessionId = q.SessionId
JOIN Reply r ON q.ReplyId = r.ReplyId 
JOIN Option_Table o ON q.OptionId = o.OptionId 
WHERE ".implode(" AND ", array_fill(0, $numTerms, "q.QuestionContent LIKE ?"))."
GROUP BY an.SessionId, an.QuestionId
)
AS tmpresult
ORDER BY ".implode(", ", array_fill(0, $numTerms, "IF(q.QuestionContent LIKE ?, 1, 0) DESC"))."
";

2 个答案:

答案 0 :(得分:0)

展开您的GROUP BY子句,将您想要考虑的行添加为重复行,如下所示

GROUP BY an.SessionId, an.QuestionId, QuestionContent,  
         OptionType, q.NoofAnswers, Answer, q.QuestionMarks

答案 1 :(得分:0)

强大的疯狂想法,但仍然值得尝试,从您的主要查询中创建一个子查询,并使用DISTINCT进行另一个选择:

 SELECT DISTINCT {yourcolumns}
 FROM
 (
        your current code
 ) as tmp