mysql select查询查找不在相关表中的记录的位置

3xiyfsfu  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(283)

我是安静的编程新手,所以我需要一些帮助在下面的情况下查询。
用户表

uid (PK)| name  | score
------------------
   1    | john  | 20
   2    | mary  | 40
   3    | david | 60
   4    | nancy | 80

问题表

qid|question
-------------
1  | a     
2  | b     
3  | c     
4  | d

问题用户表

quid | user_id (FK) | question_id (FK)
--------------------------------
1    | 1            | 1
2    | 2            | 1
3    | 1            | 2
4    | 3            | 3

上面显示了数据库的表结构。 question_user 表包含特定用户已回答的问题。我想以描述的方式得到特定用户尚未回答的问题列表。

t98cgbkg

t98cgbkg1#

试试这个:
样本数据:

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
yxyvkwin

yxyvkwin2#

如果你想在desc中得到特定用户没有回答的问题,那么使用下面的查询

SELECT * FROM questions WHERE qid NOT IN (SELECT question_id FROM `question_user` WHERE uid = USER-ID) ORDER BY qid DESC;
alen0pnh

alen0pnh3#

下面的查询应该会给出用户尚未回答的问题。

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;

相关问题