用子查询排序奇数
Ordering oddity with sub queries
我有 SQL:
select
sub.id,
corr
from
(
select
m.id,
m.sent_time,
(case when m.to_user = '58' then m.from_user else m.to_user end) as corr
from
messages m
where
(
from_user = '58' OR
to_user = '58'
)
order by
m.sent_time desc
) as sub
group by
sub.corr
order by
sent_time DESC
在我继承的网站源代码中。
SQL 检索消息 ID 和与之通信的另一方的用户 ID,消息已发送到登录用户或从登录用户接收(在本例中为用户 ID 58。
目前查询总是returns用户(58)和其他用户之间最早的消息ID。
将顺序更改为使用 sent_time DESC 并没有改变这一点。
我可能遗漏了一些明显的东西 - 但是如何通过更改此查询来获取最新消息而不是最旧消息的消息 ID?
如果我明白你的意思,你可以尝试以下sql:
select
max(sub.id),
sub.corr
from
(
select
m.id,
m.sent_time,
(case when m.to_user = '58' then m.from_user else m.to_user end) as corr
from
messages m
where
(
from_user = '58' OR
to_user = '58'
)
order by
m.sent_time desc
) as sub
group by
sub.corr
您的查询没有给出您想要的结果,因为一旦您使用 GROUP BY
,它就会为所有未聚合的列选择随机值。我想你可以简化你的查询来避免这个问题:
SELECT id,
CASE WHEN to_user = '58' THEN from_user ELSE to_user END AS corr
FROM messages m
WHERE (to_user = 58 OR from_user = 58) AND
sent_time = (SELECT MAX(sent_time)
FROM messages m1
WHERE m1.to_user = 58 OR m1.from_user = 58)
我有 SQL:
select
sub.id,
corr
from
(
select
m.id,
m.sent_time,
(case when m.to_user = '58' then m.from_user else m.to_user end) as corr
from
messages m
where
(
from_user = '58' OR
to_user = '58'
)
order by
m.sent_time desc
) as sub
group by
sub.corr
order by
sent_time DESC
在我继承的网站源代码中。 SQL 检索消息 ID 和与之通信的另一方的用户 ID,消息已发送到登录用户或从登录用户接收(在本例中为用户 ID 58。
目前查询总是returns用户(58)和其他用户之间最早的消息ID。 将顺序更改为使用 sent_time DESC 并没有改变这一点。
我可能遗漏了一些明显的东西 - 但是如何通过更改此查询来获取最新消息而不是最旧消息的消息 ID?
如果我明白你的意思,你可以尝试以下sql:
select
max(sub.id),
sub.corr
from
(
select
m.id,
m.sent_time,
(case when m.to_user = '58' then m.from_user else m.to_user end) as corr
from
messages m
where
(
from_user = '58' OR
to_user = '58'
)
order by
m.sent_time desc
) as sub
group by
sub.corr
您的查询没有给出您想要的结果,因为一旦您使用 GROUP BY
,它就会为所有未聚合的列选择随机值。我想你可以简化你的查询来避免这个问题:
SELECT id,
CASE WHEN to_user = '58' THEN from_user ELSE to_user END AS corr
FROM messages m
WHERE (to_user = 58 OR from_user = 58) AND
sent_time = (SELECT MAX(sent_time)
FROM messages m1
WHERE m1.to_user = 58 OR m1.from_user = 58)