Join tables when fields aren't equal - PHP MySQL - php

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.

Related

SQL table structure for questions/answer system?

I am making a question posting system. Each question post must contain the Users ID/username and the unique question id
MY TABLES
------------USERS---------------------------------
id
uname
password
fname
lname
-----------QUESTIONS-----------------------------
user_id
question_id
question
description
time
I am a beginner here, please put up with me. I just don't know how I can match my users_ID with question id as they are on separate tables.That way when a question is posted I can retrieve the users ID who posted the question alongside with the question id.
My rationality with combining the tables will not work simply because I can't think of a way to match a users unique id with the question_id. Please help me...really lost
You can use Inner Join to display the matched records in between the two tables:
SELECT
question_id,
question,
id,
uname
FROM Questions A INNER JOIN Users B
ON A.user_id=B.id
If you want to show up your question data with an user_id, it associated with user and question table. you can use inner join like this.
For show up your question data :
select * from questions inner join user on question.user_id=user.id;

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

Display data from multiple tables in MYSQL database

I know there's something wrong here. Can anyone point it out? I am trying to display question_body from questions and answers_body from answers.
EDIT : I got this error: Column 'question_id' in field list is ambiguous
<?php
$auctionSurvey = "SELECT question_id, survey_id, question_body, answer_body FROM questions
INNER JOIN answers ON answers.question_id = questions.question_id
WHERE survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());
while($auctionRow = mysql_fetch_assoc($aucResult)){
echo $auctionRow['question_body']. $auctionRow['answer_body'];
}
?>
It looks like one problem is ambiguous column...
In the SELECT list, I don't think MySQL can figure out which table is referenced by question_id.
The normative pattern whenever two (or more) tables (row sources) are referenced is to QUALIFY every column reference...
SELECT q.question_id
, q.survey_id
, q.question_body
, a.answer_body
FROM questions q
JOIN answers a
ON a.question_id = q.question_id
WHERE q.survey_id='1'
There's two big benefits to this pattern (qualifying column references):
Firstly, it helps future readers "know" which columns are from which table, without having to look at the table definitions and figure out which table has which column name.
Secondly, it helps avoid "breaking" a SQL statement when a new column with the same name as a column in another table is added... having the column references qualified avoids the potential for breaking a SQL statement (causing a working SQL statement to start raising an ambiguous column exception.
Your error indicates that 'question_id' is in both tables. Use an 'alias' to differentiate between the tables, like this:
SELECT Q.question_id, survey_id, question_body, answer_body
FROM questions Q
INNER JOIN answers A ON A.question_id = Q.question_id
WHERE survey_id='1'";
You have to differentiate between the two tables:
SELECT Q.question_id,
A.question_id,
Q.survey_id,
Q.question_body,
A.answer_body
FROM questions Q
INNER JOIN answers A ON A.question_id = Q.question_id
WHERE Q.survey_id='1'

How should I display quiz questions against results table?

I've a simple query that selects all quizzes from DB.
$mysqli->query("SELECT * FROM quizz WHERE quizz_level = $level");
To display this result, I do simple foreach.
I also have a results table where I save outcome of the quizz
result_id, user_id, quizz_id, result_value
Now I'd like to modify original foreach and if result exist for spceific user for specific quizz, mark it differently (as answered).
I intend to do following, SELECT results table and grab all quizz_id's for specific user. Put this into an array. And while doing original foreach to display quizz questions, match it against keys in results array.
Is there a better solution to this problem?
Can it be done via mysql sub-query?
p.s. probably my worst title ever for the question :)
How about
SELECT q.*,case when r.user_id = $user_id then 1 else 0 end case as answered
FROM quizz q
inner join results r on q.quizz_id = r.quizz_id
WHERE q.quizz_level = $level
and then filter on answered on your php code
EDIT
I've changed the left outer to inner as it doesn't make sense the left outer. Also changed the columns of the join to quizz_id
The select is bringing all the records from the table quizz (q.*) and with the inner join is linking to the results table on the quizz_id columns.
Then on the select part I use case to check if the user_id is the one you are looking for
case when r.user_id = $user_id then 1 else 0 end case as answered
Then the recorset will have all the quizz table columns plus a column called answered where if the value is 1 that quizz was answered by the user_id and if its 0 then it wasn't answered by the user_id.

Select rows and display as columns from mySQL database

All,
I've got the following mySQL table structure:
Table dj_feedback_answers: answer_id, gig_id, question_id, answer_id
Table dj_feedback_summary: summary_id, user_id, gig_date, tip, summary, why_poor, why_fair
Table dj_feedback_questions: question_id, question_value, question_display
Table dj_feedback_ratings: rating_id, rating_value, rating_display
I'm basically asking users questions and the questions are stored in the dj_feedback_questions table and allowing them to give a rating for each question. The ratings are stored in the dj_feedback_ratings.
Each form can having variable questions so when I submit the questions I store the answers in the dj_feedback_answers. There are other more static fields on the form and those get svaed into the dj_feedback_summary. The summary_id and the gig_id are the keys that connect the two tables for the answers that the user submitted.
This means that there can be multiple rows in the dj_feedback_answers for a single row in the dj_feedback_summary table.
What I would like to do is basically be able to utilize the results in a PHP table. So I'd like my results to look something like this (assuming there are three questions in the dj_feedback_questions table):
summary_id, user_id, gig_date, tip, summary, why_poor, why_fair, question_1, question_2, question_3
1, 2, 07/23/2012, 5, This is a summary, It was poor, It was fair, 3, 4, 5
The values that would be stored for the questions would be the answer_id from the dj_feedback_answers.
I tried to create the following query to get my results. This works ok but it only can display a single question instead of all of the questions.
Select dj_feedback_summary.summary_id,
dj_feedback_summary.user_id,
dj_feedback_summary.gig_date,
dj_feedback_summary.tip,
dj_feedback_summary.summary,
dj_feedback_answers.question_id,
dj_feedback_answers.rating_id,
dj_feedback_questions.question_value,
users.first_name, users.last_name,
dj_feedback_ratings.rating_value
from dj_feedback_summary
join dj_feedback_answers on dj_feedback_summary.summary_id=dj_feedback_answers.gig_id
join dj_feedback_questions on dj_feedback_answers.question_id=dj_feedback_questions.question_id
join users on dj_feedback_summary.user_id=users.user_id
join dj_feedback_ratings on dj_feedback_ratings.rating_id=dj_feedback_answers.rating_id
where dj_feedback_questions.question_value='Overall Gig'
order by dj_feedback_summary.summary_id DESC
Is there a way to modify my query so it can return my results how I would like them?
Any advice is greatly appreciated!
Thanks
If you need values from multiple rows displayed, and it's not essential that they be in separate columns, then the MySQL GROUP CONCAT function would probably suit your purposes.
That would give you question_1, question_2, and question_3 values concatenated into a single column (if I understand your output intent correctly).
Update: To do a more "genuine" pivot (separating the answers to different questions into different columns), you could use one of the following approaches:
1) Use multiple table aliases: join to the dj_feedback_questions table one time for each question, e.g. something along these lines:
SELECT [...] FROM [...]
LEFT JOIN dj_feedback_questions q1 on q1.question_id = 1
LEFT JOIN dj_feedback_questions q2 on q2.question_id = 2
LEFT JOIN dj_feedback_questions q3 on q2.question_id = 3
You will then need to a) join to dj_feedback_answers similarly (multiple times with aliases), since you get to it via question_id, and you want different questions separated into different columns, and b) aggregate the results and decide how you want to handle nulls, since doing a regular JOIN instead of a LEFT JOIN will cause you to lose the row for any summary that lacks an answer to one or more questions.
2) Break into columns with an IF block: See this SO question (specifically the accepted answer) for an illustration: Transpose mysql query rows into columns

Categories