我有一个名为private_messages的SQL表,其中包含字段(id,from,to,message,stamp)。 戳记字段对应于消息的日期
那么我需要什么查询:
1)在两个用户之间进行对话(按日期排序)?
我已经尝试了查询
(SELECT * FROM private_messages WHERE from=$my_id AND to=$other_id)
UNION
(SELECT * FROM private_messages WHERE from=$other_id AND to=$my_id)
ORDER BY stamp
;
但不起作用......
2)获取我和其他用户之间的最后一条消息,每个消息都有一个不同的用户,按日期排序(例如构建一个像faceebook这样的收件箱)?
答案 0 :(得分:9)
1)
SELECT *
FROM private_messages a
WHERE (a.from = $my_id AND a.to = $other_id) OR
(a.from = $other_id AND a.to = $my_id)
ORDER BY stamp DESC
2)。
SELECT f.*
FROM
(
SELECT *
FROM private_messages a
WHERE (LEAST(a.from, a.to), GREATEST(a.from, a.to), a.stamp)
IN (
SELECT LEAST(b.from, b.to) AS x,
GREATEST(b.from, b.to) AS y,
MAX(b.stamp) AS msg_time
FROM private_messages b
GROUP BY x, y
)
) f
WHERE $my_id IN (f.from, f.to)
ORDER BY f.stamp DESC
答案 1 :(得分:1)
你能试试吗?
SELECT x.*
FROM (SELECT * FROM private_messages
WHERE `to`='$my_id' OR `from`='$my_id' GROUP BY `to`, `from`) AS x
ORDER BY x.stamp DESC ;
To
,From
可以是保留字。注意到x
是表别名。
答案 2 :(得分:0)
我过去做过这个,但是查询简单。可能这对你有用
SELECT * FROM private_messages WHERE (from=$my_id AND to=$other_id) OR (from=$other_id AND to=$my_id) ORDER BY stamp
答案 3 :(得分:0)
1)非常确定您需要围绕PHP变量引用,例如:
(SELECT * FROM private_messages WHERE from='$my_id' AND to='$other_id') UNION (SELECT * FROM private_messages WHERE from='$other_id' AND to='$my_id') ORDER BY stamp DESC
2)尝试类似:
SELECT * FROM (SELECT * FROM private_messages WHERE to='$my_id' OR from='$my_id' GROUP BY to, from) AS tmp_table ORDER BY stamp DESC