ORDER BY an equal value in MySQL

后端 未结 3 1725
情深已故
情深已故 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

    0 讨论(0)
  • 2020-12-30 16:07
    SELECT ...
    FROM   ...
    ORDER BY (meta_key='featured' AND meta_value='yes') DESC, postid ASC;
    

    If (meta_key='featured' AND meta_value='yes') for a row, that row will have a 1/TRUE. Otherwise, it will have a 0/FALSE. Hence, sorting descending puts the rows that have TRUE first.

    0 讨论(0)
  • 2020-12-30 16:16

    Also, you can use MySQL function named

    FIELD(HAYSTACK, value[, ...values]).
    

    This function returns index of haystack in values (FROM 1 to n, 0 - if not found).

    Example

    ORDER BY FIELD(wp_postmeta.meta_key, 'featured', wp_postmeta.meta_key), 
    FIELD(wp_postmeta.meta_value, 'yes', wp_postmeta.meta_value), wp_posts.post_date DESC
    

    But, in your case, use the mathematical.coffee example. In my example you need to repeat the field name in the end of list, because if you don't - it will return 0 (zero) and elements than not in list will be first in result statement.

    0 讨论(0)
提交回复
热议问题