简体   繁体   中英

Sort MySQL query result according to best match(number of columns match)

How to sort MySQL query result according to number of columns matched using multiple tables..

select tbl_user.*, tbl_user_personal.*, tbl_user_physical.*, tbl_user_education.*, tbl_user_lifestyle.* 
        from
        tbl_user, tbl_user_personal, tbl_user_physical, tbl_user_education, tbl_user_lifestyle 
        where
        tbl_user.user_id = tbl_user_personal.user_id and 
        tbl_user.user_id = tbl_user_physical.user_id and 
        tbl_user.user_id = tbl_user_education.user_id and 
        tbl_user.user_id = tbl_user_lifestyle.user_id and 
        (
            tbl_user_personal.user_community = 'some-text..' or
            tbl_user_personal.user_sub_caste = 'some-text..' or
            tbl_user_personal.user_marital_status = 'some-text..' or
            tbl_user_personal.user_children = 'some-text..' or
            tbl_user.user_age in ('some-text..', 'some-text..') or
            tbl_user.user_country = 'some-text..' or
            tbl_user_physical.user_height in('some-text..', 'some-text..') or
            tbl_user_physical.user_physical_status = 'some-text..' or
            tbl_user_education.user_education_category = 'some-text..' or
            tbl_user_education.user_occupation = 'some-text..' or
            tbl_user_lifestyle.user_eating_habits = 'some-text..'
        )

First, you should learn proper join syntax. Simple rule: Never use commas in the from clause.

But that is not your question. MySQL will treat boolean expressions as numbers in a numeric context, with 1 for true and 0 for false. So, you can just add the values together:

order by ((tbl_user_personal.user_community = 'some-text..') +
          (tbl_user_personal.user_sub_caste = 'some-text..') +
          (tbl_user_personal.user_marital_status = 'some-text..') +
          (tbl_user_personal.user_children = 'some-text..') +
          (tbl_user.user_age in ('some-text..', 'some-text..')) +
          (tbl_user.user_country = 'some-text..') +
          (tbl_user_physical.user_height in('some-text..', 'some-text..')) +
          (tbl_user_physical.user_physical_status = 'some-text..') +
          (tbl_user_education.user_education_category = 'some-text..') +
          (tbl_user_education.user_occupation = 'some-text..') +
          (tbl_user_lifestyle.user_eating_habits = 'some-text..')
         ) desc

You can also put this expression in the select clause, give it a name, and use that for the order by :

order by NumMatches desc;

Use ORDER BY

ORDER BY table1.column_name ASC|DESC, table2.column_name ASC|DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM