MYSQL,按顺序排序

时间:2012-02-19 21:15:38

标签: mysql sql select search sql-like

我有2个表帖子和帖子,我想搜索我的帖子并按大多数匹配的帖子订购。

现在我有了这个:

SELECT Threads.* 
FROM Posts 
INNER JOIN Threads ON Posts.ThreadID=Threads.ThreadID 
WHERE Posts.Content LIKE '%" . $search .  "%' 
     OR Posts.User LIKE '%" . $search ."%'

1 个答案:

答案 0 :(得分:0)

您可以添加联接来计算每个帖子的帖子数。由于您没有从帖子中选择任何列,这是您唯一需要的连接。

select  t.* 
from    Threads t
join    (
        select  ThreadID
        ,       count(*) as PostCount
        from    Posts
        where   p.Content LIKE '%" . $search .  "%' 
                or p.User LIKE '%" . $search ."%'
        group by
                ThreadID
        ) PostCount
on      PostCount.ThreadID = t.ThreadID
order by
        PostCount.PostCount desc