计算来自两个表的匹配记录

时间:2015-06-18 10:23:54

标签: php mysql join

我有两张桌子。 “question_answers”包含question列和answer列。     “question_attempts”包含questionidresponsesummary

示例:question = 4,其中有5条来自“question_answers”的记录。 “question_attempts”中的questionid相同,并在“question_attempts”中找到并获取匹配记录的计数

“question_answers”enter image description here “question_attempts”enter image description here

1 个答案:

答案 0 :(得分:1)

如果我可以在这里获得这些表的样本会更容易,但尝试一下

SELECT 
    answers.id AS 'answer id',
    count(attempts.id) AS 'number of attempts'    
FROM
    question_attempts AS attempts
JOIN
    question_answers AS answers ON answers.answer = attempts.responsessummary
WHERE 
    question_answers.question = 1
GROUP BY 
    answers.id;

如果它正常工作,您应该会收到一个答案ID表,其中包含该答案的尝试次数。

但是您需要在这两个字段中完全匹配。回答来自question_anstets的question_attempts和responsessummary。

如果无法解决方法是使用 LIKE 子句:

SELECT 
    answers.id AS 'answer id',
    count(attempts.id) AS 'number of attempts'    
FROM
    question_attempts AS attempts
JOIN
    question_answers AS answers ON answers.answer 
        LIKE CONCAT('%', attempts.responsessummary , '%')
WHERE 
    question_answers.question = 1
GROUP BY 
    answers.id;