ORDER BY an equal value in MySQL

后端 未结 3 1739
情深已故
情深已故 2020-12-30 15:52

All, I\'ve got the following SQL query as of now:

SELECT * FROM $wpdb->posts
JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id=$         


        
3条回答
  •  暖寄归人
    2020-12-30 16:01

    It is straightforward like this:

    ...
    ORDER BY featured = 'yes'
    

    featured = 'yes' is evaluates as boolean true or false, for items that featured = "yes" is true will come first then items that has featured = "yes" is false i.e featured = "no" come later.

    Update:

    You can use CASE statement in the order by clause to sort your data on a sepecific field, something like:

    ORDER BY 
            CASE WHEN postmeta.meta_key = 'featured' 
                 THEN meta_value = 'yes' DESC  
            END
    

    OR:

    ORDER BY ( postmeta.meta_key = 'featured' AND meta_value = 'yes') DESC
    

    You might need to add another order by criteria in the ELSE part of the CASE statement to order the items that have meta_key = 'featured is false to order them by.

    If the field metadata_key is always = "featured" then you can get rid of the case statement and use just ORDER BY meta_value = 'yes' DESC

提交回复
热议问题