我有以下数据库结构(用于消息传递):
id from_userid to_userid time_stamp message
假设我是 id 1 的用户,我想获取我一直在与之交互的所有 user_ids 的列表,按时间戳排序 - 知道该怎么做吗?
谢谢
我有以下数据库结构(用于消息传递):
id from_userid to_userid time_stamp message
假设我是 id 1 的用户,我想获取我一直在与之交互的所有 user_ids 的列表,按时间戳排序 - 知道该怎么做吗?
谢谢
大概是这样的吧?
SELECT *
FROM (
SELECT from_id AS id, time_stamp
FROM <table>
WHERE to_id=<user id>
UNION
SELECT to_id AS id, time_stamp
FROM <table>
WHERE from_id=<user id>
) AS t
ORDER BY time_stamp
我会这样做:
在sql中它会是这样的:
select rel_user, min(time_stamp) as first_contact from
(
select time_stamp, to_userid as rel_user where from_userid=my_ID
union all
select time_stamp, from_userid as rel_user where to_userid=my_ID
)
group by rel_user
order by min(time_stamp)
SELECT *
FROM your_table
WHERE from_userid = 1 OR to_userid = 1
ORDER by time_stamp
由于所有其他方式都使用多个 SELECT 这里的一个使用 CASE
SELECT CASE
WHEN to_userid=1 THEN from_userid
ELSE to_userid
FROM table WHERE to_userid=1 OR from_userid=1 ORDER BY time_stamp