|
我有一个名为private_messages的SQL表,带有字段(id,from,to,message,stamp)。标记字段对应于消息的日期0 Q3 P8 a4 ?- }, A. f [: b, a
所以我需要什么查询:! f0 H* }. Q9 [/ E
1)得到两个用户之间的对话(按日期排序)?9 ?) ~1 }$ y3 }& p4 ?! N) w
我已经尝试过查询 P( x. L/ S5 l$ G( k5 Y4 P2 t7 ~# T
(SELECT * FROM private_messages WHERE from=$my_id AND to=$other_id)
4 z" n2 k, B5 W& Y' i5 tUNION
! f) H6 s. f5 x8 M(SELECT * FROM private_messages WHERE from=$other_id AND to=$my_id) 8 x: f2 p+ f0 I' F4 a# l
ORDER BY stamp
/ Q2 |$ D1 r1 C& J% Q( O v3 W7 \;2 j2 F7 w. P) T0 {! p
但不起作用…! m+ V% ?: X- `6 [5 ~
2)获取我和其他用户之间的最后一条消息,每个消息都有一个不同的用户,按日期排序(例如,像在faceebook中构建收件箱)?; I6 L5 f( q* i; K' W/ Z& Z5 z
; ?8 z& B8 }* P* M- c5 ?
解决方案:. H) J' z5 z, c: ?% _
! q4 P/ q$ E* C5 E" o+ }, E
[+ ]& V- g! t4 V7 q$ T
, P5 g2 t8 W# u I3 s5 E
1.)8 T$ w: D, C$ e/ N d: A
SELECT *
! p% N& n% }# a- E, s, d RFROM private_messages a
, P5 \ ?' R& S+ I9 jWHERE (a.from = $my_id AND a.to = $other_id) OR) Y( m$ r- f9 U, U0 D! E
(a.from = $other_id AND a.to = $my_id), x0 [, ?2 W/ F$ {/ S7 C7 M* l' Q
ORDER BY stamp DESC
Y: K( i( K& s* }; m; h' Y7 L: R2.); K" V! C, f7 y. N
SELECT f.*% {2 T# |* q/ L* R
FROM+ u2 q1 z0 {7 r! O
( P* c% k' ] ]" w: L9 K3 N" M c
SELECT *' A8 P! J0 ?9 i. z" j5 r' L/ Q
FROM private_messages a+ `( h( \: t- ]9 x# ^- U" I
WHERE (LEAST(a.from, a.to), GREATEST(a.from, a.to), a.stamp)
( A; P" J/ c$ h# X. G' v; u2 z IN ( 8 Z$ e4 @8 X+ P
SELECT LEAST(b.from, b.to) AS x,
% K7 Y \3 g; x: i9 n/ B GREATEST(b.from, b.to) AS y,# `% J5 ?- M: W
MAX(b.stamp) AS msg_time
3 c6 W* P$ M$ h$ | FROM private_messages b
+ x& d1 M K* N! e GROUP BY x, y
$ I' L! E& Y$ H# Q; _5 e9 Y )3 L4 {/ F2 P7 t- ?4 {
) f
$ E5 g, U3 d3 m! @WHERE $my_id IN (f.from, f.to)6 G) F8 g* m$ \, y* k A
ORDER BY f.stamp DESC |
|