sql选择默认顺序

时间:2016-02-03 14:48:05

标签: mysql sql

所以我有这个sql请求(通过外部ID选择产品):

SELECT p.product_id, p.external_id 
FROM oc_product p 
LEFT JOIN oc_product_description pd 
    ON (p.product_id = pd.product_id) 
LEFT JOIN oc_product_to_store p2s 
    ON (p.product_id = p2s.product_id) 
WHERE pd.language_id = '2' 
    AND p.status = '1' 
    AND p.date_available <= NOW()
    AND p2s.store_id = '0' 
    AND p.external_id IN ( 38291, 21472, ... ,10)
LIMIT 0,20

它返回我的ID列表:

enter image description here

返回列表的顺序是ASC。但是我想要的顺序与我在查询中编写external_ids的顺序相同。 (38291,21472,21473,35229,35030,......)

知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

除非最外层查询中有order by,否则结果集的顺序是不确定的。

除非最外层查询中有order by,否则结果集的顺序是不确定的。

除非最外层查询中有order by,否则结果集的顺序是不确定的。

现在我们已经完成了这项工作,您可以将field()用于此目的:

order by field(p.external_id, 38291,21472,21473,35229,35030,40537,1,46936,46937,46938,46939,46940,46941,13691,37104,11574,11177,27416,15951,11178,27417,25567,37110,34597,5406,5270,37111,30033,9,40301,10)

您也可以find_in_set()

order by find_in_set(p.external_id, '38291,21472,21473,35229,35030,40537,1,46936,46937,46938,46939,46940,46941,13691,37104,11574,11177,27416,15951,11178,27417,25567,37110,34597,5406,5270,37111,30033,9,40301,10')