开发者

MySQL: How to Select All Results That Don't Match LEFT JOIN

My SELECT statement is essentially:

SELECT *, user.user, response.survey FROM survey, user, response ORDER BY survey.added

However, I am trying to select only surveys that haven't been answered. The 'response' table contains 4 relevant columns (user ID [of use开发者_开发问答r responding to survey], answer, question [same as survey ID if single question, if multi, corresponds to question ID], and survey ID)

I'm trying to write an SQL statement that selects all surveys that don't have a response from an arbitrary user ID ($_SESSION['userId'])... Tried going about this using various LEFT JOIN as well as nested SELECT commands, but haven't been able to figure it out.

Can anyone shed some light on how to go about this?


Or, just left join and check the column on the right for null:

SELECT *, user.user, response.survey FROM user 
LEFT JOIN response ON response.user=user.user 
LEFT JOIN survey ON survey.surveyID=response.surveyID 
WHERE user.user=[userID from session] AND response.user IS NULL ORDER BY survey.added

Because if the matching column from the response table is missing, response.user would be NULL.


This Select statement you wrote:

SELECT *, user.user, response.survey FROM survey, user, response ORDER BY survey.added

Is doing a cross-join (getting all possible combinations of user,response and survey) and it's clearly not the way the data is referenced between the tables; therefore is wrong. You would need to join the 3 tables by a common key.

But to answer your question...

If there's a table with responses from a particular user; then do something LIKE this:

select * from survey s where s.survey_id not in (
select survey_id from response where userId=<particular_user_id>)
and s.user_id=<particular_user_id>

And that will return all surveys that the user has not responded.

I hope the idea is clear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜