[英]MySQL SELECT query where to find records that are not in the related table
我对编程很陌生,因此在以下情况下我需要一些查询帮助。
用户表
uid (PK)| name | score
------------------
1 | john | 20
2 | mary | 40
3 | david | 60
4 | nancy | 80
question_tb表
qid|question
-------------
1 | a
2 | b
3 | c
4 | d
question_user表
quid | user_id (FK) | question_id (FK)
--------------------------------
1 | 1 | 1
2 | 2 | 1
3 | 1 | 2
4 | 3 | 3
如上所示显示数据库的表结构。 question_user
表保存特定用户已回答的问题。 我想以DESC方式获得未回答特定用户的问题列表。
以下查询应该给您用户未回答的问题。
SELECT *
FROM question_tb as q
LEFT JOIN question_user as qu on q.qid = qu.question_id AND qu.user_id = USER_ID_HERE
WHERE qu.user_id IS NULL;
如果要获取DESC中特定用户未回答的问题,请使用以下查询
SELECT * FROM questions WHERE qid NOT IN (SELECT question_id FROM `question_user` WHERE uid = USER-ID) ORDER BY qid DESC;
尝试这个:
样本数据:
create table users (uid int, name varchar(10), score int);
insert into users values
(1, 'john', 20),
(2, 'mary' , 40),
(3, 'david', 60),
(4, 'nancy', 80);
create table question_tb (qid int, question char(1));
insert into question_tb values
(1, 'a'),
(2, 'b'),
(3, 'c'),
(4, 'd');
create table question_user (quid int, user_id int, question_id int);
insert into question_user values
(1, 1, 1),
(2, 2, 1),
(3, 1, 2),
(4, 3, 3);
T-SQL:
select uid, qid from users u
cross join question_tb q
where not exists(
select 1 from question_user
where u.uid = user_id and q.qid = question_id)
order by uid, qid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.