2011-06-22 41 views
1

我試過創建一個SQL查詢,它只從database1.documents中選擇一行,該行的doc_id等於database2.documents中出現少於3次的'id'。SQL子句where id exists X times in alternate table

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

我有我的查詢砍倒在基本概念:

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

這裏是理想的結果的一個例子:

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

它不工作,我該如何去實現這一目標?一句指導將非常感謝,謝謝。 :3

回答

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 

另一種方法是使用派生的查詢,因爲它被他人建議

+0

像魅力一樣工作,謝謝! :d – escproxy

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

group by需要你允許你統計多少次t他的身份證存在。用於篩選出發生少於3次的記錄。我把它放在表單中的一個子查詢中,將它與d1結合起來。並且連接是一個內部連接,它會將結果限制爲匹配的結果。 –

+0

語法的工作方式是錯誤的,而只給了我那些在database2中的doc_id。無論如何謝謝你^ _^ – escproxy

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