简体   繁体   English

MySQL:如何选择与左联接不匹配的所有结果

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

My SELECT statement is essentially: 我的SELECT语句本质上是:

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 user responding to survey], answer, question [same as survey ID if single question, if multi, corresponds to question ID], and survey ID) “响应”表包含4个相关列(用户ID [响应调查的用户的用户ID],答案,问题[与调查ID相同(如果单个问题,如果是多个问题,则对应于问题ID)和调查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. 我正在尝试编写一条SQL语句,该语句从任意用户ID($ _SESSION ['userId'])中选择所有没有响应的调查...尝试使用各种LEFT JOIN和嵌套SELECT进行此操作命令,但无法弄清楚。

Can anyone shed some light on how to go about this? 任何人都可以阐明该如何做吗?

Or, just left join and check the column on the right for null: 或者,只需左联接,然后检查右侧的列是否为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. 因为如果缺少响应表中的匹配列,则response.user将为NULL。

This Select statement you wrote: 您编写的此Select语句:

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. 您将需要通过一个公用键来连接3个表。

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. 我希望这个主意很清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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