简体   繁体   English

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

[英]MySQL - Get records from one table based on count of another table's column

I have a table called students and a table called documents . 我有一张叫students的桌子,还有一张叫documents的桌子。 Each student can have any amount of document entries in the documents table, but might also have no document entries. 每个学生在documents表中可以有任意数量的文档条目,但也可能没有文档条目。 Some of the documents might've been approved, others not. 有些文件可能已经获得批准,有些则没有。

table 1: students , table 2 documents . 表1: students ,表2 documents student PK is user_id and document PK is document_id , and document table has user_id in it as well. student PK是user_iddocument PK是document_iddocument表中也包含user_id document table has column approved which can contain either a Yes or a No. So these two tables are linked by user_id document表具有approved列,其中可以包含是或否。因此,这两个表通过user_id链接

How can I write a MySQL query (or even better, in Active Record style for Code Igniter) that can list all students that have at least 1 unapproved document? 如何编写一个MySQL查询(甚至更好,以Active Record的Code Igniter风格),该查询可以列出所有具有至少1个未经批准的文档的学生?

mysql> create table students (student_number int, student_first_name char(25), student_Last_name char(25));

Query OK, 0 rows affected (0.34 sec) 查询正常,受影响的0行(0.34秒)

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

Query OK, 0 rows affected (0.32 sec) 查询正常,受影响的0行(0.32秒)

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

Query OK, 3 rows affected (0.19 sec) Records: 3 Duplicates: 0 Warnings: 0 查询正常,受影响的3行(0.19秒)记录:3重复:0警告:0

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

Query OK, 3 rows affected (0.16 sec) Records: 3 Duplicates: 0 Warnings: 0 查询正常,受影响的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_first_name | student_Last_name | 学生姓氏| +----------------+--------------------+-------------------+ | + ---------------- + -------------------- + ----------- -------- + | 1 | 1 | F1 | F1 | L1 | L1 | +----------------+--------------------+-------------------+ 1 row in set (0.02 sec) + ---------------- + -------------------- + ----------- -------- +设置1行(0.02秒)

select distinct students.name from students join documents on 
students.user_id=documents.user_id where documents.user_id is No

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

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