I have two tables:
Members
( member_id
, member_info
)
Question_Answers
( Question_id
, Answer
)
If there are two questions, I need to find out which member only answered one of the questions, and not both.
I have tried to use GROUP BY
, but have not gotten the results I am looking for.
Closest I've gotten was with this query:
SELECT DISTINCT(qa.question_id), mem.member_id
FROM question_answers qa
LEFT JOIN members mem ON mem.member_id = qa.member_id
This gets me the results for questions answered by user, but it includes results where the members answered both questions.
I am looking for advice on how to SELECT
the member that only answered one of the questions.
EDIT: I have gotten closer, but would like to make it better.
SELECT IF( COUNT( DISTINCT( qa.question_id ) ) = 2, 'TWO', 'ONE' ), mem.member_id, MAX( qa.question_id )
FROM question_answers qa
JOIN members mem ON qa.member_id = mem.member_id
WHERE mem.type = 9
GROUP BY mem.member_id
ORDER BY `mem`.`member_id` ASC
This is a hacky way because the question ID's are currently on 0 and 1, but if anyone has a recommendation on how to return the question_id from the SELECT IF(
then that would help out a lot.
Personally, I would have a third table to hold the data of who has answered which questions.
In my example I have called this table Answered
.
Here is how I would solve this, maybe you can glean some ideas off this example if you don't want to do it this way: [DEMO HERE] .
SELECT m1.*, qa.*
FROM Members m1
INNER JOIN Answered a ON m1.member_id = a.member_id
INNER JOIN Question_Answers qa ON a.question_id = qa.question_id
WHERE m1.member_id IN (
SELECT m2.member_id
FROM Members m2
INNER JOIN Answered a ON m2.member_id = a.member_id
INNER JOIN Question_Answers qa ON a.question_id = qa.question_id
GROUP BY m2.member_id
HAVING COUNT(m2.member_id) = 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.