mysql order by with union doesn't seem to work

前端 未结 4 2077
一生所求
一生所求 2020-12-14 19:15

Here is my query

(SELECT * FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE \"%only three doors%\" OR `joke` LIKE \"%only three doors%\") ORDER BY `ups`          


        
4条回答
  •  醉梦人生
    2020-12-14 19:57

    I got solution for this:

    SELECT *
    FROM (
        (SELECT 1 as SortRank, uid, title, state, zip, region,cantone FROM company WHERE city=".$city." AND region=".$region." AND cantone=".$cantone.")
         UNION
        (SELECT 2 as SortRank, uid, title, state, zip, region,cantone FROM company WHERE region=".$region." AND cantone=".$cantone.")
        union all
        (SELECT 3 as SortRank, uid, title, state, zip, region,cantone FROM company WHERE cantone=".$cantone.")
    ) As u
    GROUP BY uid 
    ORDER BY SortRank,state=2, title ASC
    LIMIT 0,10
    

    In above query i want result eg. first show all records with city, region and cantone then if city not available then show all records with region and cantone and then all records with cantone of city. So, removing repeating records i used GROUP BY clause, it will sort all records based on query group then all records with state=2.

提交回复
热议问题