SQL子句,其中id在备用表中存在X次

时间:2011-06-22 17:53:43

标签: sql if-statement count

我尝试创建一个SQL查询,该查询仅选择来自database1.documents的行doc_id,其database2.documents等于SELECT database1.documents.id, database1.documents.title, database1.documents.date FROM database1.documents WHERE COUNT (database1.documents.id = database2.documents.doc_id) < 3 中出现少于3次的'id'。

Database2.documents使用外部ID(database2.documents.doc_id = database1.documents.id)。

我已将查询减少到基本概念:

+---------------------------+
| Database 1: 'documents'   |
|---------------------------|
| id | title   | date       |
|----+---------+------------|
|  1 | Title 1 | 01/01/2011 |
|  2 | Title 2 | 02/01/2011 |
|  3 | Title 3 | 03/01/2011 |
+---------------------------+
+---------------------------+
| Database 2: 'documents'   |
|---------------------------|
| id | doc_id | date        |
|----+--------+-------------|
|  1 | 2      | 01/01/2011  |
|  2 | 3      | 02/01/2011  |
|  3 | 2      | 03/01/2011  |
|  4 | 2      | 04/01/2011  |
+---------------------------+
+---------------------------+
| Result                    |
|---------------------------|
| id | title   | date       |
|----+---------+------------|
|  1 | Title 1 | 01/01/2011 |
|  3 | Title 3 | 03/01/2011 |
+---------------------------+

以下是所需结果的示例:

{{1}}

它不起作用,我该如何实现这一目标?非常感谢您的指导,谢谢。 :3

3 个答案:

答案 0 :(得分:1)

基于聚合函数的条件应放在HAVING中,而不是WHERE子句中:

SELECT d1.id, d1.title, d1.date, COUNT(*)
FROM database1.documents d1
LEFT JOIN database2.documents d2 ON (d1.id = d2.doc_id)
GROUP BY d1.id, d1.title, d1.date 
HAVING COUNT(*) < 3

另一种选择是使用其他人建议的派生查询

答案 1 :(得分:0)

--  here's how to get the docid's from d2 that happen 3 times.

select *
from database1.document d1,
(
select count(*), d2.documentid
from database2.document d2
group by d2.documentid
having count(*) >= 3
) ds2
where ds2.documentid = d1.documentid

答案 2 :(得分:0)

试试这个:

SELECT *
  FROM database1.documents a LEFT JOIN 
       (
         SELECT  doc_id, COUNT(1) cnt_docs
           FROM  database2.documents 
          GROUP BY   doc_id
       ) b
    ON a.id = b.doc_id 
   AND b.cnt_docs < 3