Order results to match the order of values in a WHERE IN expression

前端 未结 6 757
孤街浪徒
孤街浪徒 2021-02-13 03:06

Is there a way I can make mysql return results from a Member database by the order I ask it by in the WHERE command?

SELECT * 
FROM Members 
WHERE MemberID = \"6         


        
相关标签:
6条回答
  • 2021-02-13 03:28

    Try this:

    SELECT * FROM Members
    ORDER BY CASE MemberId
        WHEN 6 THEN 1
        WHEN 3 THEN 2
        WHEN 5 THEN 3
        ELSE 999
    END
    
    0 讨论(0)
  • 2021-02-13 03:32

    Try this

    Select * from Members WHERE MemberID = "6" or MemberId="3" or MemberID="5" order by 
    MemberID = "6" desc 
    MemberId="3" desc
    MemberID="5" desc
    

    See this post once

    How to make MYSQL query results ORDER BY conditions order?

    0 讨论(0)
  • 2021-02-13 03:39

    no.

    you must specify an ORDER BY clause to get things into any repeatable order.

    If you can construct some logic that specifies the order then you can include that in the ORDER BY otherwise, you cannot.

    You may consider adding another data construct to map your 'random' values to a sequence or other ordering value, then using that.

    0 讨论(0)
  • 2021-02-13 03:44
    SELECT 
      * 
    FROM 
      Members 
    WHERE 
      MemberID IN ("6","3","5")
    ORDER BY 
      FIELD(MemberID,"6","3","5");
    
    0 讨论(0)
  • 2021-02-13 03:44

    Try selecting the data using 3 UNION ALL queries:

    SELECT * FROM Members WHERE MemberID = "6"
    UNION ALL
    SELECT * FROM Members WHERE MemberId = "3"
    UNION ALL
    SELECT * FROM Members WHERE MemberID = "5"
    

    or maybe you need to simply add a new column to hold the sort order ?

    0 讨论(0)
  • 2021-02-13 03:49
    Select * from Members
    WHERE MemberID = "6" or MemberId="3" or MemberID="5"
    ORDER BY MemberID = "6" DESC, MemberId="3" DESC, MemberID="5" DESC;
    
    0 讨论(0)
提交回复
热议问题