我有以下数据库结构(用于消息传递):
id from_userid to_userid time_stamp message
让我说我是id为1的用户,我希望得到一个我一直在与之交互的所有user_id的列表,按时间戳排序 - 任何想法如何做?
感谢
答案 0 :(得分:3)
也许是这样的事情?
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
答案 1 :(得分:1)
SELECT *
FROM your_table
WHERE from_userid = 1 OR to_userid = 1
ORDER by time_stamp
答案 2 :(得分:1)
我会这样做:
在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)
答案 3 :(得分:0)
由于所有其他方式都使用多个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