0
不是最好的標題,我很抱歉。選擇分組行的列表,顯示最近的內容
表結構:
消息
- ID - 詮釋
- 消息 - VARCHAR
- 用戶 - VARCHAR
- 日期 - VARCHAR
- 從 - VARCHAR
接觸
- 的ContactID - 詮釋
- contactUser - VARCHAR
- CONTACTNAME - VARCHAR
- contactFrom - VARCHAR
我的查詢目前是:
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;
但是,當用戶對兩個不同用戶具有相同的'from'聯繫人時,他們將獲得兩次相同的'對話'。
例如:
如果下面的數據中存在:
觸點
| contactId | contactUser | contactName | contactFrom |
|-----------|-------------|--------------|-------------|
| 1 | giggsey | MyNameOne | +1234567890 |
| 2 | giggsey | MySecondName | +1234567890 |
消息
| 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 |
然後該查詢返回:
| 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) |
正如您在上面所看到的,它將兩次返回相同的'會話',但是會爲每個聯繫人的副本返回一次。
我很確定這是因爲加入,但我似乎無法解決原因。
什麼是'sms'表? – 2012-03-13 23:10:55
查詢中的標識符與文本中的標識符不匹配。例如,您的查詢引用了「contacts.from」,但您的文本沒有提及「contacts」上的「from」字段。 – ruakh 2012-03-13 23:28:37
@ruakh與上面相同,複製/粘貼失敗。 – giggsey 2012-03-13 23:39:42