具有值条件的Mysql Count Query

时间:2014-02-18 15:38:45

标签: mysql sql

假设我有以下定义的表Student

+-----------------+-----------------+-----------------+
|id               |paperId          |readFlag         |
+-----------------+-----------------+-----------------+
|1                |1                |1                |
+-----------------+-----------------+-----------------+
|2                |2                |1                |
+-----------------+-----------------+-----------------+
|3                |3                |1                |
+-----------------+-----------------+-----------------+
|4                |1                |0                |
+-----------------+-----------------+-----------------+
|5                |2                |1                |
+-----------------+-----------------+-----------------+
|6                |3                |1                |
+-----------------+-----------------+-----------------+
|7                |4                |1                |
+-----------------+-----------------+-----------------+

我想知道有多少paperId只有一条记录或两条记录,其中两条记录的readFlag都设置为1

对于示例数据,答案是3(paperId' s 2,3和4)。

如何编写查询来执行此操作?

编辑:

我不想使用子查询,因为我有数百万条记录,执行子查询需要太多时间。

5 个答案:

答案 0 :(得分:1)

试试这个:

 SELECT COUNT(DISTINCT(paperId)) from STUDENT 
        WHERE paperId NOT IN 
        (SELECT DISTINCT(paperId) 
        from STUDENT where readFlag = 0);

OR

 SELECT (SELECT COUNT(DISTINCT(paperID)) from student) - 
        (SELECT COUNT(DISTINCT(paperID)) from student where readFlag=0);

答案 1 :(得分:0)

不便。像这样:

SELECT COUNT(paperID)  
FROM Student  
WHERE readFlag=1  
GROUP BY paperId

答案 2 :(得分:0)

也许是这样的?

SELECT 
    paperID
FROM
    student
WHERE
    id > 0
AND readFlad > 0

答案 3 :(得分:0)

这样的事情:

select count(distinct(paperId)) as Winners 
  from table
where readFlag = 1 
and paperId not in(select distinct paperId where readFlag = 0);

答案 4 :(得分:0)

最后我得到了解决方案

select 
distinct s1.paperId 
from Student s1
left join Student s2
on 
(s1.paperId = s2.paperId)
and 
s2.readFlag = 1
group by s1.paperId having sum(s1.readFlag) >1 or count(s1.readFlag)=1 ;