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

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

Related

Select all from a table ORDER BY another tables column, with match primary key [duplicate]

This question already has answers here:
PHP/MySQL Order by column in a different table
(2 answers)
Closed 5 years ago.
I've been looking for a while but the query I am trying to accomplish seems fairly hard to find any information or documentation on how to do what I am trying to do.
I have two tables, one of them stores my user accounts and basic information. I then have a second table that holds a little more information about the user.
Both of these tables have primary keys (table one is id and table two is user_id) which I use to know who is who and match records between both tables.
What I am trying to do today is I want to get 10 records from table one, order by a column in table two (room_count) DESC.
Table #1's name is "users" and Table #2's name is "user_information".
What have I tried?
I'm not really sure where to start so I haven't tried anything yet.
How would I got about doing something like this?
Thank you to any answers posted.
For example, let's say I have 4 users, I'll write the username followed by the room_count column in the other table below.
Adam Sandler : 4
Jenny Hang : 9
Peter Foreign : 0
If I was to use the query with ASC it would start with Peter Foreign and end with Jenny Hang
Don't you just need a simple join?
SELECT
FROM users
INNER JOIN user_information ON users.id = user_information.user_id
ORDER BY user_information.room_count DESC
LIMIT 2
Please try this:
SELECT *
FROM users u
INNER JOIN user_info ui
ON u.id = ui.user_id
ORDER BY ui.room_count DESC
LIMIT 10
Try something basic like
select users.*
from
users, user_information
where
users.id =user_information.user_id
order by
user_information.room_count
desc
Limit 10
Edit: changed select users.id to select users.* to better fit the question asked.

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.

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;

Merging 2 tables and comparing different results SQL/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

Retrieving groupings from many-to-many tables

This is kind of hard to explain but I'll do what I can.
I have 2 tables with a many-to-many relationship; there is a linking table defining the relationship. These tables are named Question, QuestionTopic and Topic. Topic has the fields TopicID and TopicName.Question has the fields QuestionID and QuestionText.
I want to retrieve a listing of the topics and the number of questions belonging to that topic. However topics could be grouped together and the count of questions unique to that combination should be known. As an example:
Topic(s) | Count
Topic1,Topic2 | 10
Topic1 | 3
Topic2 | 2
The above implies there are 3 questions unique to topic1 and 10 which have the topics Topic1 and Topic2. The remaining 2 questions have topic2.
I'm using MySQL and PHP. Thanks.
"Cheating" solution, using GROUP_CONCAT(). This will not show the count of questions that are not related to any topic:
SELECT
TopicIds
, COUNT(*) AS QuestionCount
FROM
( SELECT
QuestionId
, GROUP_CONCAT(TopicId ORDER BY TopicId) AS Topics
FROM
QuestionTopic
GROUP BY
QuestionId
) AS grp
GROUP BY
Topics
did u try GROUP_CONCAT?
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
then, u can group by topic id.
GROUP_CONCAT as mentioned above will work. But on the other side as I see your database structure does not really fit to your task. Looks like it too normalized and you need to do some de-normalization and migration.
Since you have groups of topics I suggest you create two more tables:
1) TopicGroups: Group | Topic - to list all unique combinations ("groups") of topics in questions.
2) GroupQuestions: Group | Question - to relate question to group of topics it covers
Then the solution for your task will be simple group by query on GroupQuestions.

Categories