从两个表中按两列排序

时间:2013-11-18 23:17:26

标签: mysql sql

我有以下选择查询,我想通过desc从每个表中使用列idthread_id.对结果进行排序.where子句仅适用于messages表。我需要order by id, thread_id desc有人可以帮帮我吗?  我想我需要先从两个表中选择。

 $stmt = $msg->prepare("
     SELECT * FROM messages
     where to_user = ?
           and deleted != ?
           and del2 != ?
           or from_user = ?
           and conversation = 'true'
           and deleted != ?
           and del2 != ?
     order by id desc");

我的thread表看起来像是:

thread_id(INT)   
thread_to_user   
thread_from_user
thread_message....

我的messages表看起来像是:

id(INT)   
to_user   
from_user
message
deleted
del2
date
conversation....

目前我只从messages表中选择并回显新消息。第二个表用于线程消息,因此如果用户开始对话,那么msg将转到thread表,我想要做的是在messages表中按thread_id对消息进行排序}和id所以,如果有新的回复,那么它就会排到最前面。

1 个答案:

答案 0 :(得分:0)

我不确切地知道你想要什么,但是如果你想展示threadorder by ID那么你可以试试这个:

SELECT id, m.to_user, m.from_user, message, deleted, del2, date, conversation, 
thread_id, thread_to_user, thread_from_user, thread_message 
FROM messages m
LEFT JOIN thread t
ON m.from_user = t.thread_from_user
where (to_user = ?
      or from_user = ?)
      and deleted != ?
      and del2 != ?
      and conversation = 'true'
      and deleted != ?
      and del2 != ?
order by thread_id

我在OR

分组的同时更改了to_user.的顺序