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 | 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 |
+---------------------------+
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, notWHEREclause:Another alternative is to use derived queries as it was suggested by others