首页 > 解决方案 > sql语句中有多个where子句?

问题描述

我有一个简单的sessions表格,如下所示:

   sid  watchtime
    1   01:07:00
    2   01:07:00
    3   01:34:00
    4   01:36:00
    5   01:36:00
    6   01:59:00
    7   01:59:00
    8   00:00:00
    9   00:00:00
    10  03:42:00
    11  00:16:00
    12  00:49:00
    13  00:55:00
    14  00:00:00
    15  00:05:00
    16  00:05:00

现在,我想显示 watchtime>=5和 watchtime的计数<5。我尝试了以下解决方案:

SELECT count(watchtime) as lessthan_five FROM sessions 
WHERE watchtime <=5 
AND count(watchtime) as morethan_five 
         from sessions WHERE watchtime >5";

我收到以下错误:

1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 1 行的 'as morethanfive from sessions where WHERE watchtime >=5"' 附近使用

我在我的代码中做错了什么?

标签: mysqlsqldatabasephpmyadmin

解决方案


您可以使用条件聚合来获得所需的结果,利用 MySQL 在数字上下文中将布尔值视为 1 或 0:

SELECT SUM(watchtime <= '00:05:00') AS lessthan_five,
       SUM(watchtime >  '00:05:00') AS morethan_five
FROM sessions

输出:

lessthan_five   morethan_five
5               11

dbfiddle 上的演示


推荐阅读