需要查询帮助才能从表中获取不同的记录。 这是为了在收件箱区域显示。
SELECT DISTINCT(from_id),to_id,message,sent_date,status,message_status from messages where to_id='$mid'
有了这个,我得到了两个from_id
的记录SSM5130 testing 7 December
SSM4228 testing 9 December
SSM4228 testing 7 December
SSM12 Hai 7 December
SSM5130 aaaaaaaaaaaaaaaaaaaaaa 6 December
但我需要得到这样的东西。
SSM5130 testing 7 December
SSM4228 testing 9 December
SSM12 Hai 7 December
我的数据库是这样的........
mes_id to_id from_id message date read_status message_status
----------------------------------------------------------------------------------------------
1 SSM11 SSM13 dfsdfsfsfsdfsdfsd 2013-12-06 10:49:44 1 0
2 SSM11 SSM5130 aaaaaaaaaaaaaaaaaaaaaa 2013-12-06 10:52:01 1 0
3 SSM11 SSM5130 aaaaaaaaaaaaaaaaaaaaaa 2013-12-06 10:52:14 1 0
4 SSM11 SSM4228 aaaaaaaaaaaaaaaaaaaaaa 2013-11-01 09:30:30 1 0
41 SSM11 SSM12 Hai 2013-12-07 12:50:13 1 0
43 SSM11 SSM5130 aaaaaaaaaaaaaaaaaaaaaa 2013-11-07 09:30:30 1 0
44 SSM11 SSM100 aaaaaaaaaaaaaaaaaaaaaa 2013-11-07 09:30:30 1 0
46 SSM11 SSM5130 testing 2013-12-09 15:16:25 1 1
47 SSM5130 SSM11 testing 2013-12-09 15:16:25 1 1
答案 0 :(得分:1)
您需要按to_id对每一行进行排序,并为每个to_id组选择第一行。
SELECT
t.mes_id,
t.to_id,
t.from_id,
t.message,
t.date,
t.read_status,
t.message_status
FROM
(SELECT
@row_num := IF(@prev_value=o.to_id, @row_num + 1, 1) AS RowNumber,
@prev_value := o.to_id,
o.*
FROM
my_table o,
(SELECT @row_num := 1) X, (SELECT @prev_value := '') Y
ORDER BY
o.to_id) t
WHERE RowNumber = 1
答案 1 :(得分:0)
我的猜测是你现有的from_id包含尾随空格。
使用此查询:
select distinct (ltrim(rtrim(from_id))), to_id,message,sent_date,status,message_status
from messages
where to_id='$mid'
答案 2 :(得分:0)
更新:如果理解正确,请尝试这种方式
SELECT m.*
FROM
(
SELECT to_id, from_id, MAX(date) date
FROM messages
WHERE to_id='SSM11' -- if you need it for a specific to_id
GROUP BY to_id, from_id
) q JOIN messages m
ON q.to_id = m.to_id
AND q.froM_id = m.from_id
AND q.date = m.date
输出:
+--------+-------+---------+------------------------+---------------------+-------------+----------------+ | mes_id | to_id | from_id | message | date | read_status | message_status | +--------+-------+---------+------------------------+---------------------+-------------+----------------+ | 1 | SSM11 | SSM13 | dfsdfsfsfsdfsdfsd | 2013-12-06 10:49:44 | 1 | 0 | | 41 | SSM11 | SSM12 | Hai | 2013-12-07 12:50:13 | 1 | 0 | | 44 | SSM11 | SSM100 | aaaaaaaaaaaaaaaaaaaaaa | 2013-11-07 09:30:30 | 1 | 0 | | 46 | SSM11 | SSM5130 | testing | 2013-12-09 15:16:25 | 1 | 1 | | 51 | SSM11 | SSM4228 | testing | 2013-12-09 15:03:51 | 0 | 1 | +--------+-------+---------+------------------------+---------------------+-------------+----------------+
这是 SQLFiddle 演示