I am looking to combine two MySQL queries so it returns the common results so I know I am not looking to use UNION on this one. I tried writing a subselect statement but that didn't work out
First query:
SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 4 and m.answer = 3 and h.page = 4
Second query:
SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 114 and m.answer = 1 and h.page = 114
Failed merge query:
SELECT s.ses_id FROM session s, multiple, history h
JOIN (
SELECT session.ses_id
FROM session, history, multiple
WHERE multiple.question = 114 and multiple.answer = 1 and history.page = 114 and history.ses_id = session.ses_id and multiple.ses_id=session.ses_id
) q1 ON q1.ses_id = s.ses_id
WHERE s.interview = 'lifestyle' and s.finished = 'y' and multiple.page=4 and multiple.answer = 3 and h.page = 4 and h.ses_id = s.ses_id and multiple.ses_id=s.ses_id
The multiple table contains questions and answers and I am looking to find the ids of those who have answered the two questions with those specific answers.
I realize this should be easy and I am most likely overthinking and/or missing something.
You simply need to join both the history
and multiple
tables an additional time each for the 2nd question/answer combination.
SELECT s.ses_id,
m1.question, m1.answer, h1.page,
m2.question, m2.answer, h2.page
FROM session s
INNER JOIN history h1
ON h1.ses_id = s.ses_id AND h1.page = 4
INNER JOIN multiple m1
ON m1.ses_id = s.ses_id
AND m1.question = 4 AND m1.answer = 3
INNER JOIN history h2
ON h2.ses_id = s.ses_id AND h2.page = 114
INNER JOIN multiple m2
ON m2.ses_id = s.ses_id
AND m2.question = 114 and m2.answer = 1
WHERE s.interview = 'lifestyle' and s.finished = 'y'