Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MySQL中查找缺少的值_Sql_Mysql - Fatal编程技术网

在MySQL中查找缺少的值

在MySQL中查找缺少的值,sql,mysql,Sql,Mysql,我试图写一个查询,以找出哪些用户没有注册某些课程 我有两张桌子;课程和用户。两者都包含字段“id”,然后分别包含“coursename”和“username” 现有系统使用这两个表将用户添加到第三个表中,该表称为已登记的用户。每个用户占用一行。例如,如果用户id“1”在4门课程上,则注册的_用户如下所示: ----------------------- | user_id | course_id | ----------------------- | 1 | 1 |

我试图写一个查询,以找出哪些用户没有注册某些课程

我有两张桌子;课程和用户。两者都包含字段“id”,然后分别包含“coursename”和“username”

现有系统使用这两个表将用户添加到第三个表中,该表称为已登记的用户。每个用户占用一行。例如,如果用户id“1”在4门课程上,则注册的_用户如下所示:

-----------------------
| user_id | course_id |
-----------------------
|     1   |     1     |
|     1   |     2     |
|     1   |     3     |
|     1   |     4     |
-----------------------
正如您所看到的,此表数据不是建立在关系上的,它是在PHP中使用两个表“courses”和“users”生成的

如果有10门课程,我不知道如何编写查询,找出用户“1”未注册的课程,但我们可以看到用户“1”只注册了课程1-4

我应该使用类似于“喜欢”或“不喜欢”的东西吗

SELECT u.id, c.id, ec.user_id, ec.course_id
FROM users u, courses c, enrolled_courses ec
WHERE u.id = ec.user_id
AND c.id = ec.course_id
AND u.id = '1'
我试过使用!=但这并没有说明我需要什么;用户未注册的课程列表

对不起,如果我含糊不清,试图让我的头围绕它


使用MySQL 5.0,在我无法修改的现有系统上,目前只能从中查询。

只需使用not in和sub select

select * from courses c where c.id not in 
   (select  course_id  from enrolled_courses  where  user_id='1') 

只需使用not in和sub select

select * from courses c where c.id not in 
   (select  course_id  from enrolled_courses  where  user_id='1') 

如果您要查找特定的单个用户ID,请确保将该ID条件作为WHERE子句的一部分,否则,将其留空,因为用户和课程表之间没有直接连接,因此它将为您提供所有未通过笛卡尔积注册所有可能课程的人员。。如果尝试为每个人跑步,并且您的课程表是100个课程,其中有人只参与2-3-4个课程,那么这可能会非常大/耗时

select 
      u.id,
      c.id CourseID
   from 
      users u,
      courses c
   where
          u.id = 1
      AND c.id NOT IN 
           ( select ec.Course_ID
                from enrolled_courses ec
                where ec.user_id = u.id )

如果您要查找特定的单个用户ID,请确保将该ID条件作为WHERE子句的一部分,否则,将其留空,因为用户和课程表之间没有直接连接,因此它将为您提供所有未通过笛卡尔积注册所有可能课程的人员。。如果尝试为每个人跑步,并且您的课程表是100个课程,其中有人只参与2-3-4个课程,那么这可能会非常大/耗时

select 
      u.id,
      c.id CourseID
   from 
      users u,
      courses c
   where
          u.id = 1
      AND c.id NOT IN 
           ( select ec.Course_ID
                from enrolled_courses ec
                where ec.user_id = u.id )

想法是在course.id为null的位置执行左连接并添加想法是在course.id为null的位置执行左连接并添加write概念,但用户表没有课程id。。。这就是注册课程是forCheers Nix,它的目的是:从课程c中选择*其中c.id不在从注册课程中选择课程id,其中用户id='1'编写概念,但用户表没有课程id。。。这就是注册课程forCheers Nix的目的:从课程c中选择*其中c.id不在从注册课程中选择课程id,其中用户\u id='1'