MySQL - 根据另一个表的列计数从一个表中获取记录

问题描述 投票:0回答:2

我有一张名为students的桌子和一张名为documents的桌子。每个学生可以在documents表中包含任意数量的文档条目,但也可能没有文档条目。有些文件可能已获批准,有些则未获批准。

表1:students,表2 documentsstudent PK是user_iddocument PK是document_id,而document表也有user_iddocument表有列approved,可以包含是或否。所以这两个表由user_id链接

如何编写MySQL查询(甚至更好,在Code Igniter的Active Record样式中),可以列出所有至少有1个未批准文档的学生?

php mysql codeigniter activerecord
2个回答
1
投票
mysql> create table students (student_number int, student_first_name char(25), student_Last_name char(25));

查询正常,0行受影响(0.34秒)

mysql> create table documents (student_number int, document_name char(25), approved bool);

查询OK,0行受影响(0.32秒)

mysql> insert into students values (1,"F1","L1"),(2,"F2","L2"),(3,"F3","L3");

查询正常,3行受影响(0.19秒)记录:3重复:0警告:0

mysql> insert into documents values (1,"D1",0),(1,"D2",1),(3,"D3",1);

查询正常,3行受影响(0.16秒)记录:3次重复:0警告:0

mysql> select * from students where student_number in (select student_number from documents where !approved);

+ ---------------- + -------------------- + ----------- -------- + | student_number | student_first_name | student_Last_name | + ---------------- + -------------------- + ----------- -------- + | 1 | F1 | L1 | + ---------------- + -------------------- + ----------- -------- + 1排(0.02秒)


0
投票
select distinct students.name from students join documents on 
students.user_id=documents.user_id where documents.user_id is No
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.