如何按顺序命令mysql结果我在“IN”条件中指定行id

时间:2015-03-16 14:52:53

标签: php mysql sql database

查询是:

   SELECT * FROM `stock` WHERE `stockid` IN (33, 12,53,4,99,88)

但是当我运行查询时,它不会按33,12,53等顺序返回行

我正在使用php。以上是一个简化的例子。

3 个答案:

答案 0 :(得分:4)

您可以按字段使用

SELECT * FROM `stock` WHERE `stockid` IN (33, 12,53,4,99,88)
order by field(stockid,33, 12,53,4,99,88)

答案 1 :(得分:0)

也许您可以创建一个包含两列的临时表('stockIdColumn','orderColumn')。

| STOCKID | ORDER |
|      33 |     1 |
|      12 |     2 |
|      53 |     3 |
|       4 |     4 |
|      99 |     5 |
!      88 |     6 |

将此表与您的订单和订单[订单]

联系起来
SELECT s.*
FROM stock s JOIN temp t ON t.stockId = s.id
ORDER BY t.order

答案 2 :(得分:0)

不要认为这是真正的答案,而是另一种方式:

SELECT * FROM stock WHERE stockid IN (33)
UNION SELECT * FROM stock WHERE stockid IN (12)
UNION SELECT * FROM stock WHERE stockid IN (53)
UNION SELECT * FROM stock WHERE stockid IN (4)
UNION SELECT * FROM stock WHERE stockid IN (99)
UNION SELECT * FROM stock WHERE stockid IN (88)
;