Merging 2 tables and comparing different results SQL/PHP - php

I'm really struggling here to do this. I've looked online but I just don't understand what other people are doing and how it would work for my situation.
I have a questions table with questions (Columns: question_id, question, answer1, answer2, questioner_id), then I have a table (questions_answered) with rows of who answered what question. (Columns: user_id and question_id)
I need to grab questions for the user but make sure that I don't pick questions that the user has already answered by comparing the user_id and question_id.
I'm racking my head over how to do this. I've tried to do two sets of queries and comparing the arrays to no avail.
I'm now trying to do it in 1 query but I'm just so unsure of how.
Please may anyone help me?
If you need any more information just say
Kindest Regards

Try this with subquery
SELECT * FROM questions q
WHERE q.question_id NOT IN
(SELECT qa.question_id FROM questions_answered qa WHERE qa.user_id ='1')
or use NOT EXISTS
SELECT * FROM questions q
WHERE NOT EXISTS
(SELECT * FROM questions_answered qa WHERE qa.user_id ='1')
or
SELECT * FROM questions q
WHERE NOT EXISTS
(SELECT * FROM questions_answered qa WHERE qa.question_id =q.question_id AND qa.user_id ='1')
Subqueries with EXISTS or NOT EXISTS

Related

Join tables when fields aren't equal - PHP MySQL

I created two tables, one stores the questions of a quiz, and the other one stores all the answers, that users made.
The first table called "questions" contains the questions:
Field names: id|question
Eg. contents:
1|what's your fav color?
2|what's your fav animal?
The second table named "answers" stores all the answers, that users made:
Fields names: id|questionid|userid|answer
Eg. contents:
1|1|1|Red
1|1|3|Magenta
1|1|4|Green
I'd like to select those questions, that haven't been answered yet by a user.
I store the current user's id in a $_SESSION['id'] session. I tried so many ways, to get these questions, the closest query I've made, was this:
$query = SELECT questions.*, answers.* FROM questions LEFT JOIN answers ON questions.id=answers.questionid WHERE answers.id IS NULL OR answers.userid <> '.$_SESSION['id'];
This won't work, because if there's another userid in the answers table at the same question id, it still selects that row. What could be the problem? Where did I mess up my query?
Thanks in advance for all of your help!
Your user condition is in the wrong place. Since you'll want to try to find a match between the specific user and the question and detect a non match, the user part needs to go inside the ON clause with a null check in the WHERE clause;
SELECT q.*
FROM questions q
LEFT JOIN answers a
ON q.id = a.questionid
AND a.userid = YOUR_USER_ID
WHERE a.id IS NULL
An SQLfiddle to test with.

MySQL - SELECT / JOIN from two tables - inverted or negative

i want to make survey on my site and i want to every survey question is displayed to user (registered and logged in) only once (if answered). So i made 2 tables.
surveyQuestions (table 1 with data for each questions):
surveyId
question
etc
surveyAnswers (table 2 with answers of each user to questions):
surveyId (= surveyId from table 1)
userId
etc...
What i need is to select 1 question from table surveyQuestions which has not been yet answered from logged user (answers are stored in surveyAnswers). UserId in browser is handled using $_SESSION['id'].
I have tried different JOIN methods, but without luck and i am lost now.
Thank you very much.
assuming you have distinct questions in your questions table and multiple duplicates of each question for different users in your answers table you should be able to do it like this.. get survey id's for all answered questions for a particular user and then look at the questions they havent answered by using NOT IN
SELECT whatever_you_want
FROM surveyQuestions
WHERE surveyId NOT IN(
SELECT surveyId
FROM surveyAnswers
WHERE userId = $id -- # -- whatever your filtering id is here
)
LIMIT 1

MySql operator complexity

I have a pet project on feedback system with to tables, one caputres the questions of customers and another caputures the answeers of help desk.
////////////////////////////////////////////////////////////////////////
Customers_Question table AND helpdesk_answers includes:
Qst_id(pk), Qst_id(pk)(FK)
qst_title, helpdesk_answer
qst_comment,
qst_customer_name,
qst_date
to get answers mysql query is:
SELECT*from customers_question, helpdesk_answers
WHERE customers_qst.Qst_id = helpdesk_answers(FK Qst_id)
i get all questions that already answered.
QUESTION: HOW DO I GET OR COUNT UNANSWERED QUESTION?
SELECT q.*
from customers_question q
left join helpdesk_answers a on q.Qst_id = a.Qst_id
where a.Qst_id is null
See this great explanation of joins
using IS NULL ->
SELECT cq.* FROM customers_question cq
LEFT JOIN helpdesk_answers ha
ON cq.Qst_id = ha.Qst_id
WHERE ha.Qst_id IS NULL
OR
using NOT IN() ->
SELECT * FROM customers_question
WHERE Qst_id NOT IN
(SELECT DISTINCT Qst_id FROM helpdesk_answers)
You can use the code given in the other answers to get the questions.
In order to count the rows returned you can see this answer.

Check what values doesn't exist in SQL database

I have a question about MySQL table.
I have 2 tables (users (user_id and other rows) and answers (id, answer_id and user_id))
I would like to check, which questions the user hasn't answered (for example, in answers table exists 5 rows - 4,6,8,1,3 (but questions are 10), I would like to get out from database values 2,5,7,9,10).
How to write a query like this?
I've tried with JOIN, but nothing was successful at all!
Assuming that you have a questions and an answers table, this is the standard TSQL solution:
SELECT Q.QUESTION_ID
FROM QUESTIONS Q LEFT JOIN ANSWERS A ON Q.QUESTION_ID = A.QUESTION_ID
WHERE A.QUESTION_ID IS NULL
Or use LEFT JOIN, it's faster.
SELECT q.id
FROM question q
LEFT JOIN answers a
ON a.question_id = q.id
WHERE a.id IS NULL
not sitting in front of a mySQL DB but it should be something to the point of (you didn't tell us where your questions are listed so I put in a placeholder) It also seems like your answer table HAS to have or should have a link to the question_id it is answering. If I made any incorrect assumptions please let me know and I will edit as needed.
Select question_id from question_table
where question_id not in (select question_id from answers)
I suppose you've got a QUESTION table:
select *
from question
where not exists(
select 'x'
from answer
where answer.question_id = question.id
)
If you haven't got a QUESTION table, IMHO there's no solution

Complex (ish) SQL join and count query

I'm trying to create a simple poll function using php and sql.
I have three tables:
Questions
Which simply contains each question asked
question_id | question_text | created_at
Answers
Which contains each answer for each question
question_id | answer_id | answer_text
Answered Questions
Which records who has voted for each option
question_id | answer_id | user_ip
I'm trying to write a query which will return a single question (the most recent) along with all the possible answers to that question and finally a count of each answer to each question. I know I will have to use a GROUP BY clause and possible LEFT OUTER JOIN, but the exact syntax is eluding me atm.
Any advice would be greatly appreciated. Thanks.
This is very similar to the logic in this article http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/.
Essentially you need a subquery which selects the single record / question you are interested in, as well as an outer query to select the information related to that record that you are interested in
(I could post another SQL statement to add to the nice collection that have already been posted, but I thought I'd try and shed some light onto how the other posted queries work)
This query should work on most DBMSs:
select q.question_id, question_text, a.answer_id, a.answer_text, count(user_ip)
from questions q
inner join answers a on (q.question_id = a.question_id)
left join answered_questions aq on (a.question_id = aq.question_id
and a.answer_id = aq.answer_id)
where created_at = (select max(created_at)
from questions
)
group by q.question_id, a.answer_id, q.question_text, a.answer_text
Assuming you're usnig MySQL:
SELECT q.* ,
(
SELECT COUNT(*)
FROM answered_questions aq
WHERE aq.answer_id = a.answer_id
AND aq.question_id = q.question_id
) AS votes
FROM (
SELECT *
FROM question
ORDER BY
created_at DESC
LIMIT 1
) q
LEFT OUTER JOIN
answers a
ON a.question_id = q.question_id
SELECT
questions.question_id,
questions.question_text,
answers.answer_id,
answers.answer_text,
COUNT(answered_questions.user_ip)
FROM
questions,answers,
answered_questions
WHERE
questions.question_id=answers.question_id
AND
questions.question_id=
(SELECT
question_id
FROM questions
ORDER BY questions.created_at
LIMIT 1
)
AND
answered_questions.question_id=questions.question_id
GROUP BY
questions.question_id
should work (although I haven't tested it).

Categories