I have two tables which contain data that should be combined. One contains contacts and the other defines lists of contacts. I would like to have the contacts of a specific list returned first, then followed by the remaining contacts.
To illustrate, here a working example:
These are the two tables:
Contacts Lists
+--------------+ +-------------------------+
| id | name | | id | list | contacts_id |
+--------------+ +-------------------------+
| 1 | george | | 1 | 1 | 1 |
| 2 | lisa | | 2 | 1 | 3 |
| 3 | fred | | 3 | 1 | 6 |
| 4 | duncan | | 4 | 2 | 1 |
| 5 | edward | | 5 | 2 | 3 |
| 6 | sally | | 6 | 3 | 1 |
| 7 | alice | | 7 | 3 | 7 |
| 8 | chuck | | 8 | 1 | 2 |
+--------------+ | 9 | 5 | 2 |
| 10 | 5 | 8 |
+-------------------------+
Assuming I focus on List #1, the desired result is this:
Result
+----------------+
| list | name |
+----------------+
| 1 | fred |
| 1 | george |
| 1 | lisa |
| 1 | sally |
| NULL | alice |
| NULL | chuck |
| NULL | duncan |
| NULL | edward |
+----------------+
To explain: The selected contacts from the list (in the example, list '1') should appear on top in alphabetical order. The other contacts - whether in a list or not - should appear below, avoiding duplicate names.
This is the statement I got so far:
SELECT
Contacts.*,
Lists.*
FROM
Contacts
LEFT JOIN Lists ON
Contacts.id = Lists.contacts_id
ORDER BY
field(Lists.list, 1) DESC,
ROW_NUMBER() OVER (PARTITION BY Contacts.id ORDER BY Contacts.name)
It shows contacts from list 1 on top, but it returns some names from that list again below the top results. I also tried adding GROUP BY contacts_id
, but that seems to remove too many results.
How can I get the statement done in such a way that it returns every name in the contact table once and those from a specified list on top?