2017-06-16 54 views
0
CREATE TABLE users (
    id INT, 
    name TEXT 
); 

INSERT INTO users VALUES 
    (1, "John"), 
    (2, "Susan"), 
    (3, "Timothy"), 
    (4, "Robert"), 
    (5, "Jim"), 
    (6, "Patricia"); 

$var = $db->prepare(" 
    SELECT name 
     FROM users 
     WHERE id IN (3, 2, 4, 6) 
"); 
$var->execute(); 

返回結果的順序是id出現在表中,所以「2,3,4,6」。有沒有辦法按WHERE ... IN條款中指定的順序訂購?使用WHERE IN子句按順序抓取行

預期的結果將是:

+----+ 
| id | 
+----+ 
| 3 | 
| 2 | 
| 4 | 
| 6 | 
+----+ 

回答

4

你需要一個order by得到的東西秩序。一種方法是使用field()

SELECT name 
FROM users 
WHERE id IN (3, 2, 4, 6) 
ORDER BY field(id, 3, 2, 4, 6); 
2
SELECT name 
FROM users 
WHERE id IN (3, 2, 4, 6) 
order by find_in_set(id, '3,2,4,6')