I need to pull data based on its exact sequence in an array

后端 未结 1 874
清酒与你
清酒与你 2021-01-21 22:54

Below is my code and I want to pull the data based on the sequence 3, 10 then 7, how can I do that? so far it pulls first 10, then 7, then 3.


              


        
相关标签:
1条回答
  • 2021-01-21 23:01

    The idea is to order the result by their respective position in the array. In this case MySQL FIND_IN_SET function can help you.

    You may add the following order by statement:

    ORDER BY FIND_IN_SET(car.id,'3,10,7')
    

    Note: You need convert this order by statement in your equivalent cake php mysql query.

    MySQL FIND_IN_SET() returns the position of a string if it is present (as a substring) within a list of strings. The string list itself is a string contains substrings separated by ‘,’ (comma) character.

    This function returns 0 when search string does not exist in the string list and returns NULL if either of the arguments is NULL.

    FIND_IN_SET

    Sample Input:

    query:

    SELECT *
    FROM cars
    

    id
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    

    Output:

    query:

    SELECT *
    FROM cars
    WHERE cars.id IN (3,10,7)
    ORDER BY FIND_IN_SET(cars.id,'3,10,7')
    

    id
    3
    10
    7
    

    Check the SQLFIDDLE DEMO here

    Edit:

    I don't know CAKE PHP syntax in building mysql query.

    But The equivalent query in cake php mysql may be something like that:

    $cars = $this->car->find('all', array(
            'conditions' => array(
                'car.id' => array(3, 10, 7)
            ),
            'limit' => 3, 
            'order' => array(FIND_IN_SET('car.id' , '3,10,7'))
        ));
    
    0 讨论(0)
提交回复
热议问题