使用id为不同的列排序

时间:2013-11-16 05:04:48

标签: php mysql

我创建了一个具有私人消息功能的社交网站。当一个用户发送私人消息时,数据将以下列格式插入名为“pm”的表中,默认值为read = 0.

_________________________________
| id | sender  | receiver | text | time | read |
+++++++++++++++++++++++++++++++++
| 1  |   A      |    B     |  abc |  x   |   0   |
| 2  |   B      |    A     |  abc |  y   |   1   |
| 3  |   A     |    C     |  abc |  z   |   0   |
| 4  |   C     |    B     |  abc |  a   |   1    |
| 5  |   B     |    A     |  abc |  b   |   0   |
| 6  |   A     |    D     |  abc |  c   |   0   |
| 7  |   D     |    A     |  abc |  d   |   1   |
| 8  |   A     |    B     |  abc |  e   |   0   |
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

我使用了以下一些mysql代码来列出与用户A进行过私人消息的用户。

SELECT DISTINCT sender from pm where receiver='A'
UNION
SELECT DISTINCT receiver from pm where sender='A'

此代码工作正常,但实际上我想按ID降序排列数据,以便最新发件人显示在列表顶部,依此类推。

我使用了id desc的ORDER但返回了UNKNOWN COLUMN id。

注意:列'id'是主键。

希望有人能解决这个问题。

问候。

3 个答案:

答案 0 :(得分:1)

试试这段代码..

SELECT distinct sender from ((SELECT DISTINCT pm.id,pm.sender from pm where receiver='A')
UNION
(SELECT DISTINCT pm.id,pm.receiver from pm where sender='A')
order by id desc) as abc

答案 1 :(得分:0)

select sender,receiver from ((SELECT DISTINCT pm.id,pm.sender from pm where receiver='A'
     UNION
     SELECT DISTINCT pm.id,pm.receiver from pm where sender='A')) as abc ORDER BY pm.id;

试试这个......

答案 2 :(得分:0)

如果发件人和收件人的用户名都是唯一的,那么您可以这样做:

SELECT COALESCE(t1.id, t2.id) as UserId, UserName FROM
(
 SELECT DISTINCT sender as UserName from pm where receiver='A'
 UNION
 SELECT DISTINCT receiver as UserName from pm where sender='A'
) tbl
INNER JOIN pm t1
ON tbl.UserName = t1.Sender
INNER JOIN pm t2 
ON tlb.UserName = t2.Receiver
ORDER BY id