Search code examples
mysqlsqlselectsearchsql-like

MYSQL, ORDER BY LIKE


I have 2 tables Thread and Posts, i would like to search my posts and order by thread with most matches.

Right now i have this:

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

Solution

  • You could add a join to calculate the number of posts per thread. Since you're not selecting any columns from Posts, that's the only join you'll need.

    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