如果有值,如何选择count(),但如果值为0,则不选择任何内容

时间:2019-03-23 16:22:26

标签: mysql sql mysql-python

我正在为一个项目编写预订系统,目前正在努力获取一些内置的报表功能。无论是否有预订,我都需要返回今天日期的所有课程的清单。

我得到的问题是没有预订时,我从sql查询中什么都没得到,但是有预订时,我得到了正确的信息。如果我不选择预订,而一切都可以,但是我需要所有这些信息。

SELECT
    class_instances.instance_sdate,
    classes.class_name,
    classes.class_max,
    users.user_name_first,
    users.user_name_last,
    COUNT(bookings.booking_id)
FROM
    `computing-project`.class_instances class_instances,
    `computing-project`.classes classes,
    `computing-project`.users users,
    `computing-project`.bookings bookings
WHERE
    DATE(class_instances.instance_sdate) = DATE(NOW()) AND
    class_instances.class_id = classes.class_id AND
    classes.teacher_id = users.user_id AND
    bookings.instance_id = class_instances.instance_id

数据集:https://imgur.com/JDjkK0G

以上代码仅在某人预订课程后才有效。班级没有预定的成员时就不会。

我仍然将计数返回为0,但其他列没有其他结果

  • 希望这是有道理的。

预期产量

+-----------------------+------------+-----------+-----------------+----------------+----------------------------+
|    instance_sdate     | class_name | class_max | user_name_first | user_name_last | count(bookings.booking_id) |
+-----------------------+------------+-----------+-----------------+----------------+----------------------------+
| 2019-03-23 16:38:00.0 | Test       |        11 | Louis           | Simpson        |                          0 |
| 2019-03-23 16:39:00.0 | Test2      |        12 | Louis           | Simpson        |                          0 |
+-----------------------+------------+-----------+-----------------+----------------+----------------------------+

1 个答案:

答案 0 :(得分:1)

如果您还希望不预订,则需要左联接(外联接)

您应避免基于位置使用旧的隐式联接sintax,应使用显式联接sintax并使用此左联接进行预订

SELECT
    class_instances.instance_sdate,
    classes.class_name,
    classes.class_max,
    users.user_name_first,
    users.user_name_last,
    COUNT(bookings.booking_id)
FROM `computing-project`.class_instances class_instances
INNER JOIN  `computing-project`.classes classes ON class_instances.class_id = classes.class_id 
INNER JOIN  `computing-project`.users users ON  classes.teacher_id = users.user_id 
LEFT  JOIN  `computing-project`.bookings bookings ON bookings.instance_id = class_instances.instance_id 
WHERE  DATE(class_instances.instance_sdate) = DATE(NOW())
GROUP BY  class_instances.instance_sdate,
    classes.class_name,
    classes.class_max,
    users.user_name_first,
    users.user_name_last