[英]Check what values doesn't exist in SQL database
I have a question about MySQL table. 我对MySQL表有疑问。
I have 2 tables (users (user_id and other rows) and answers (id, answer_id and user_id)) 我有2个表(用户(user_id和其他行)和答案(id,answer_id和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). 我想检查一下,用户没有回答哪些问题(例如,在答案表中存在5行 - 4,6,8,1,3(但问题是10),我想从数据库值中退出2,5,7,9,10)。
How to write a query like this? 如何编写这样的查询? I've tried with JOIN, but nothing was successful at all!
我尝试过JOIN,但一切都没有成功!
Assuming that you have a questions and an answers table, this is the standard TSQL solution: 假设您有问题和答案表,这是标准的TSQL解决方案:
SELECT Q.QUESTION_ID
FROM QUESTIONS Q LEFT JOIN ANSWERS A ON Q.QUESTION_ID = A.QUESTION_ID
WHERE A.QUESTION_ID IS NULL
I suppose you've got a QUESTION
table: 我想你有一个
QUESTION
表:
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 如果您还没有
QUESTION
表,恕我直言,没有解决方案
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. 没有坐在mySQL数据库的前面,但它应该是一些东西(你没有告诉我们你的问题列在哪里,所以我放入占位符)它似乎你的答案表已经或应该有一个链接到它正在回答的question_id。 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)
Or use LEFT JOIN, it's faster. 或者使用LEFT JOIN,它更快。
SELECT q.id
FROM question q
LEFT JOIN answers a
ON a.question_id = q.id
WHERE a.id IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.