在DB2“ IN”查询中维护订单

时间:2018-11-29 22:35:07

标签: db2

该问题基于this one。我正在寻找一个适用于DB2的问题的解决方案。这是原始问题:

我有下表

DROP TABLE IF EXISTS `test`.`foo`;
CREATE TABLE  `test`.`foo` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

然后我尝试根据主键获取记录

SELECT * FROM foo f where f.id IN (2, 3, 1);

然后我得到以下结果

+----+--------+
| id | name   |
+----+--------+
|  1 | first  |
|  2 | second |
|  3 | third  |
+----+--------+
3 rows in set (0.00 sec)

可以看到,结果按ID排序。我试图实现的结果是按照查询中提供的顺序对结果进行排序。给定这个例子,它应该返回

+----+--------+
| id | name   |
+----+--------+
|  2 | second |
|  3 | third  |
|  1 | first  |
+----+--------+
3 rows in set (0.00 sec)

3 个答案:

答案 0 :(得分:2)

您可以使用具有所需ID和所需顺序的派生表,然后将表加入其中,例如...

SELECT ...
FROM   mcscb.mcs_premise prem
JOIN   mcscb.mcs_serv_deliv_id serv 
  ON   prem.prem_nb = serv.prem_nb 
 AND   prem.tech_col_user_id = serv.tech_col_user_id 
 AND   prem.tech_col_version = serv.tech_col_version 
JOIN (
    SELECT 1, '9486154876' FROM SYSIBM.SYSDUMMY1 UNION ALL
    SELECT 2, '9403149581' FROM SYSIBM.SYSDUMMY1 UNION ALL
    SELECT 3, '9465828230' FROM SYSIBM.SYSDUMMY1 
) B (ORD, ID)
ON    serv.serv_deliv_id = B.ID
WHERE serv.tech_col_user_id = 'CRSSJEFF' 
  AND serv.tech_col_version = '00'
ORDER BY B.ORD

答案 1 :(得分:1)

您可以使用派生列进行自定义排序。

select case when serv.SERV_DELIV_ID = '9486154876' then 1 ELSE when serv.SERV_DELIV_ID = '9403149581' then 2 ELSE 3 END END as custom_order, ... ... ORDER BY custom_order

答案 2 :(得分:1)

要使逻辑更加明显,您可以像这样修改solution provided by bhamby

WITH ordered_in_list (ord, id) as (
  VALUES (1, '9486154876'), (2, '9403149581'), (3, '9465828230')
)
SELECT ...
FROM   mcscb.mcs_premise prem
JOIN   mcscb.mcs_serv_deliv_id serv 
  ON   prem.prem_nb = serv.prem_nb 
 AND   prem.tech_col_user_id = serv.tech_col_user_id 
 AND   prem.tech_col_version = serv.tech_col_version 
JOIN   ordered_in_list il 
  ON   serv.serv_deliv_id = il.ID
WHERE serv.tech_col_user_id = 'CRSSJEFF' 
  AND serv.tech_col_version = '00'
ORDER BY il.ORD