SQL加入条件为

时间:2016-02-05 13:36:59

标签: php mysql sql

我有这个问题:

SELECT * 
FROM `classes` 
JOIN `classes_students` 
ON `classes`.`id` = `classes_students`.`class`

我需要添加条件来选择只有类,其中当前没有记录的学生(用户ID不在与类ID相关联的classes_students中),还要计算该班级中有多少学生。

表格结构:     类:id,name等     classes_students:class_id,user_id等

表格数据:

classes: 
1 | test 
2 | test2
3 | test3

classes_students:
1 | 1
1 | 2
2 | 3
3 | 4
3 | 5

如果id为1的用户,则预期输出: 班级名称(学生人数):

2 (1 student)
3 (2 students)

所有这一切都在一个查询中。有可能的?如果有,怎么样?

3 个答案:

答案 0 :(得分:0)

Select classid, count(*)
from class
  left join student on student.classid = class.classid
group by classid

很高兴帮助你

答案 1 :(得分:0)

尝试此查询:

$user_id = 1; // current user_id

$query = "SELECT `classes`.`id`, `classes`.`name`, COUNT(*) as students FROM `classes` 
          JOIN `classes_students` 
          ON `classes`.`id` = `classes_students`.`class_id`
          AND `classes_students`.`user_id` != $user_id 
          GROUP BY `classes_students`.`class_id`
          ";

答案 2 :(得分:0)

我明白了! :) 谢谢你们的帮助。

$user_id = 1; // current user_id

$query = "SELECT `classes`.`id`, `classes`.`name`, COUNT(*) as students FROM `classes` 
          LEFT JOIN `classes_students` 
          ON `classes`.`id` = `classes_students`.`class_id`
          WHERE `classes`.`id` NOT IN (SELECT `class_id` FROM `classes_students` WHERE `user_id`='.$user_id.')
          GROUP BY `classes_students`.`class_id`
          ";