简体   繁体   English

联合中的订单列由另一列选择

[英]order column from union select by another column

I have a table: 我有一张桌子:

Message 信息

id, user_from_id, user_to_id, send_date, message, is_readed

and I would like to select all the users that I chat with, so my query looks like this: 并且我想选择所有与我聊天的用户,因此我的查询如下所示:

SELECT user_from_id as user_id
FROM message
WHERE user_to_id=xxx
UNION
SELECT user_to_id
FROM message
WHERE user_from_id=xxx

..and I have a list of user_id's, the problem is that I can't find a way to order those id's by send_data, so that at the beginning of that list i would have a user that i lately chat with ..并且我有一个user_id的列表,问题是我找不到通过send_data来订购这些ID的方法,因此在该列表的开头,我会有一个我最近与之聊天的用户

Can someone help me? 有人能帮我吗?

How about dispensing with the union ? union会怎么样?

SELECT (CASE WHEN m.user_to_id = xxx THEN m.user_from_id
             ELSE m.user_to_id
        END) as user_id
FROM message m
WHERE xxx IN (m.user_to_id, m.user_from_id)
ORDER BY m.send_date DESC;

This is probably not what you really want, because users will appear multiple times in the list. 这可能不是您真正想要的,因为用户将在列表中出现多次。 What you really want is: 您真正想要的是:

SELECT (CASE WHEN m.user_to_id = xxx THEN m.user_from_id
             ELSE m.user_to_id
        END) as user_id
FROM message m
WHERE xxx IN (m.user_to_id, m.user_from_id)
GROUP BY m.user_id
ORDER BY MAX(m.send_date) DESC;
with x as(
SELECT user_from_id as user_id, send_date
FROM message
WHERE user_to_id=xxx
UNION
SELECT user_to_id, send_date
FROM message
WHERE user_from_id=xxx
) select user_id 
from x 
order by send_date

This wraps the UNION query up with the send_date column into a single variable, from which you can then SELECT and ORDER BY send_date . send_date UNION查询和send_date列一起包装到一个变量中,然后您可以从中SELECTORDER BY send_date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM