我有一个表格,如短信,其中包含from
,to
,message
和time
列(以及其他内容)。我试图询问两个号码(from
和to
)之间的最新记录,而不考虑方向。
以下是该表的示例:
+--------------+-----------------+--------------------+--------------+
| from | to | message | time |
+--------------+-----------------+--------------------+--------------+
| 555-1234 | 555-9876 | I'll be there. | 06:00 |
| 555-9876 | 555-5555 | message3 | 05:30 |
| 555-9876 | 555-1234 | Bring beer | 05:00 |
| 555-9876 | 555-1234 | My place at 8pm | 04:00 |
| 555-9876 | 555-5555 | message2 | 03:45 |
| 555-5555 | 555-9876 | message1 | 03:30 |
| 555-9876 | 555-1234 | Are you coming? | 03:00 |
| 555-1234 | 555-9876 | Yeah, what's up? | 02:00 |
| 555-9876 | 555-1234 | Are you there? | 01:00 |
+--------------+-----------------+--------------------+--------------+
我想从这个例子中得到以下记录:
+--------------+-----------------+--------------------+--------------+
| from | to | message | time |
+--------------+-----------------+--------------------+--------------+
| 555-1234 | 555-9876 | I'll be there. | 06:00 |
| 555-9876 | 555-5555 | message3 | 05:30 |
+--------------+-----------------+--------------------+--------------+
我如何要求这些?
答案 0 :(得分:0)
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT LEAST(`from`, `to`) AS `from`,
GREATEST(`from`, `to`) AS `to`,
MAX(`time`) AS `max_time`
FROM yourTable
GROUP BY LEAST(`from`, `to`),
GREATEST(`from`, `to`)
) t2
ON LEAST(t1.`from`, t1.`to`) = t2.`from` AND
GREATEST(t1.`from`, t1.`to`) = t2.`to` AND
t1.`time` = t2.`max_time`
顺便说一下,命名列from
(MySQL关键字)的原因是什么?请使用其他名称。
答案 1 :(得分:0)
你coynd使用带有max和tuple的子查询
select * from my_table
where (from, to, time) in ( select from, to, max(time)
from my_table
group by from, to)
答案 2 :(得分:0)
<ul class="nav nav-tabs" id="sortable" data-bind="foreach: pcsList">
<li>
<a data-bind="attr: {href: '#' + id}, text: pcName"></a>
</li>
</ul>