lundi 28 décembre 2015

SQL JOIN with two tables and with a condition for one table, in a single SQL statement

I have an sqlite database which has a table of documents (journal articles), where each document has a unique id. All the authors are listed in another table, with corresponding document id's, and with unique author id's as well. The problem is that articles have different number of authors. If there is one author, I should retrieve just his name. If there are two, I should retrieve both names. If there are more than two, I need to retrieve only the first author and append "et al." to it.

In the following example, I need to produce records of the type "Authors - Title". For Document Title1 I shoud have "Name101 et al. - Title1", for Title2 - "Name201 - Title2", for Title3 - "Name301 & Name302 - Title3".

DocsTable
Title   |  DocId
Title1  |  10
Title2  |  20
Title3  |  30

AuthorsTable
Name      | AuthorId  | DocId
Name101   |    101    | 10
Name102   |    102    | 10
Name103   |    103    | 10
Name201   |    201    | 20
Name301   |    301    | 30
Name302   |    302    | 30

I certainly might do that with at least two queries, but how might I do that in a single statement?

Another related problem is that I'd like to sort the result by author names with accent-insensitive order (where, e.g., ú = ü = u). I am aware about COLLATE Latin1_General_CI_AI, and it works fine in LIKE clause, however when I write ORDER BY names COLLATE Latin1_General_CI_AI, the statement returns error.

Aucun commentaire:

Enregistrer un commentaire