dqhsv0147421 2018-06-28 22:48
浏览 62
已采纳

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

I have a table called students and a table called documents. Each student can have any amount of document entries in the documents table, but might also have no document entries. Some of the documents might've been approved, others not.

table 1: students, table 2 documents. student PK is user_id and document PK is document_id, and document table has user_id in it as well. document table has column approved which can contain either a Yes or a No. So these two tables are linked by 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?

  • 写回答

2条回答 默认 最新

  • dougang5088 2018-06-28 23:11
    关注
    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)

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

    Query OK, 0 rows affected (0.32 sec)

    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

    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

    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 row in set (0.02 sec)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?