简体   繁体   中英

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM