Not the best title, I apologise.
Table structure:
messages
- id – int
- message – varchar
- user – varchar
- date – varchar
- from – varchar
contacts
- contactId – int
- contactUser – varchar
- contactName – varchar
- contactFrom – varchar
My query currently is:
SELECT
messages1.`from`,
messages1.`message`,
messages1.`date` AS d,
messages2.`count`,
contacts.`contactId`,
contacts.`contactName`,
contacts.`contactFrom`
FROM messages AS messages1,
(
SELECT
MAX(`date`) AS maxdate,
`from`,
COUNT(*) AS `c`
FROM messages
WHERE
`user` = 'MYUSER'
GROUP BY `from`
) AS messages2
LEFT JOIN contacts ON
(
contacts.`contactUser` = 'MYUSER' AND
contacts.`contactsFrom` = messages2.`from`
)
WHERE
messages1.`from`= messages2.`from` AND
messages1.`date` = messages2.`date`
ORDER BY `date` DESC;
However, when a user has the same contact ‘from’ for two different users, they will get the same ‘conversation’ twice.
Eg:
If the following data exists:
contacts
| contactId | contactUser | contactName | contactFrom |
|-----------|-------------|--------------|-------------|
| 1 | giggsey | MyNameOne | +1234567890 |
| 2 | giggsey | MySecondName | +1234567890 |
messages
| id | message | user | date | from |
|------|-----------|----------|------------|--------------|
| 1 | h1 | giggsey | 111111111 | +1234567890 |
| 2 | h2 | giggsey | 111111113 | +1234567890 |
| 3 | random | giggsey | 111111116 | +9999992234 |
| 4 | h3 | giggsey | 111111119 | +1234567890 |
Then the query returns:
| from | message | d | count | contactId | contactName | contactFrom |
|-------------|---------|-----------|-------|-----------|--------------|-------------|
| +1234567890 | h3 | 111111119 | 3 | 1 | MyNameOne | +1234567890 |
| +1234567890 | h3 | 111111119 | 3 | 2 | MySecondName | +1234567890 |
| +9999992234 | random | 111111116 | 3 | (NULL) | (NULL) | (NULL) |
As you can see above, it is returning the same ‘conversation’ twice, but once for each duplicate of the contact.
I’m pretty sure it’s because of the JOIN, but I can’t seem to work out why.
Fixed it by using a subquery instead of just reading from the table.