开发者

SQL clause where id exists X times in alternate table

I've attempted creating an SQL query which only selects rows from database1.documents which has a doc_id which is equal to the 'id' that appears less than 3 times in database2.documents.

Database2.documents uses a foreign ID (database2.documents.doc_id = database1.documents.id).

I have cut down my query to the basic concept:

SELECT database1.documents.id, database1.documents.title, database1.documents.date
  FROM database1.documents
 WHERE COUNT (database1.documents.id = database2.documents.doc_id) < 3

Here's an example of the desired outcome:

+---------------------------+
| Database 1: 'documents'   |
|---------------------------|
| id | title   | date       |
|----+---------+------------|
|  1 | Title 1 | 01/01/2011 |
|  2 | Title 2 | 02/01/2011 |
|  3 | 开发者_如何学PythonTitle 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 |
+---------------------------+

It doesn't work, how do I go about achieving this? A word of guidance would be most appreciated, thank you. :3


Condition based on aggregate functions should be put in HAVING, not WHERE clause:

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

Another alternative is to use derived queries as it was suggested by others


--  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


Try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜