SQLite Forum

SELECT question
Login
There are two ways of doing this, both of which rely on essentially the same principle.

The first step is to phrase the problem in it's simplest form in common English, then translate the English to SQL.

The simplest way I can describe your request is:
Give me the first 5 recent-most titles
To each of those, join all their keywords.

The simplest way to say that first statement in SQL is:

```
SELECT id, title, author, source
  FROM docs
  ORDER BY id DESC
  LIMIT 5
```
Now that should work as expected, showing exactly 5 rows of unique recent-most docs.

The second part of the problem then is to link the keywords to the above selection, so we can make the above into a sub-query or CTE (I will show both ways below) and join the keywords to it. Note in both cases that I re-use the above query verbatim.


*Example 1. - Sub-Query:*

```
SELECT D.id, D.title, D.author, D.source, K.keyword, K.authorid
  FROM (SELECT id, title, author, source
          FROM docs
         ORDER BY id DESC
         LIMIT 5
        ) AS D
  JOIN keywords AS K ON K.docid = D.id
```
That should do it. By the way, your additional filters and be transposed like this: "and K.authorid=D.authorid etc." but they make no sense unless a single document can have multiple authors AND you link keywords by Author. which I doubt. It looks like the kind of nonsense an MSSQL query editor would produce.


*Example 2. - Same solution using CTE:*

```
WITH D AS (
    SELECT id, title, author, source
      FROM docs
     ORDER BY id DESC
     LIMIT 5
)
SELECT D.id, D.title, D.author, D.source, K.keyword, K.authorid
  FROM D,keywords AS K
 WHERE K.docid = D.id
```

There's no major advantage to using either way, just two tools in your toolbox, though I find the CTE's to generally be more human-readable and they can be re-used multiple times in a long query whereas a sub-query has to be re-stated, but that's an opinion/preference based distinction - the query engine treats them mostly the same.

One more example, this time getting only 5 lines of output with the keywords concatenated together into a comma-separated list:


```
WITH D AS (
    SELECT id, title, author, source
      FROM docs
      ORDER BY id DESC
     LIMIT 5
)
SELECT D.id, MAX(D.title) AS title, MAX(D.author) AS author,
       MAX(D.source) AS source, GROUP_CONCAT(K.keyword)
  FROM D,keywords AS K
 WHERE K.docid = D.id
 GROUP BY D.id
```

If keywords repeat or appear many time, you can use: 
<code>GROUP_CONCAT(DISTINCT K.keyword)</code>


Hope that helps!

PS: The above is all typed from memory and not tested, but it should work. If not, feel free to ask again, someone here will correct my mistake!