如何缩短此SQL查询?

时间:2017-02-21 08:38:52

标签: sql oracle

有没有办法缩短这个查询,比如使用例如?

     SELECT ords_id
FROM orders o
JOIN stocks s ON o.ords_stks_id = s.stks_id
WHERE (s.stks_print_btn_status LIKE '%901%'
       AND o.ords_stas_id = 90
       AND o.lsnr IS NOT NULL
       AND o.ords_id = orderid)
  OR (s.stks_print_btn_status LIKE '%1001%'
      AND o.ords_stas_id = 100
      AND o.lsnr IS NOT NULL
      AND o.ords_id = orderid)
  OR (s.stks_print_btn_status LIKE '%801%'
      AND o.ords_stas_id = 80
      AND o.lsnr IS NOT NULL
      AND o.ords_id = orderid)
  OR (s.stks_print_btn_status LIKE '%231%'
      AND o.ords_stas_id = 23
      AND o.lsnr IS NOT NULL
      AND o.ords_id = orderid)

4 个答案:

答案 0 :(得分:1)

首先,您可以避免为每种情况重复o.lsnr is not null and o.ords_id = orderid

SELECT ords_id
FROM orders o
JOIN stocks s ON o.ords_stks_id = s.stks_id
WHERE o.lsnr IS NOT NULL
  AND o.ords_id = orderid
  AND ( (s.stks_print_btn_status LIKE '%901%'
         AND o.ords_stas_id = 90)
       OR (s.stks_print_btn_status LIKE '%1001%'
           AND o.ords_stas_id = 100)
       OR (s.stks_print_btn_status LIKE '%801%'
           AND o.ords_stas_id = 80)
       OR (s.stks_print_btn_status LIKE '%231%'
           AND o.ords_stas_id = 23) )

答案 1 :(得分:1)

这会从字面上理解您的查询 - 我假设s.STKS_PRINT_BTN_STATUS将包含带有' 1'的订单ID。所附...

select ords_id
 from orders o
     join stocks s on o.ords_stks_id = s.stks_id
 where 1=1
 and o.lsnr is not null
 and o.ords_id = orderid
 and s.STKS_PRINT_BTN_STATUS LIKE '%'||o.ords_stas_id||'1%'
 and o.ords_stas_id IN (90,100,80,23)
;

答案 2 :(得分:0)

刚刚删除了一些重复:

SELECT ords_id
FROM orders o
JOIN stocks s ON o.ords_stks_id = s.stks_id
WHERE o.lsnr IS NOT NULL
  AND o.ords_id = orderid
  AND ((s.stks_print_btn_status LIKE '%901%'
        AND o.ords_stas_id = 90)
       OR (s.stks_print_btn_status LIKE '%1001%'
           AND o.ords_stas_id = 100)
       OR (s.stks_print_btn_status LIKE '%801%'
           AND o.ords_stas_id = 80)
       OR (s.stks_print_btn_status LIKE '%231%'
           AND o.ords_stas_id = 23));

答案 3 :(得分:0)

你想要达到什么目的?这纯粹缩短了查询吗?您可以将WHERE的重复部分移动到这样的内容:

select ords_id
 from orders o join stocks s on o.ords_stks_id = s.stks_id
where 
(o.lsnr is not null and o.ords_id = orderid)
 AND 
(s.STKS_PRINT_BTN_STATUS like '%901%' and o.ords_stas_id = 90) or
(s.STKS_PRINT_BTN_STATUS like '%1001%' and o.ords_stas_id = 100) or
(s.STKS_PRINT_BTN_STATUS like '%801%' and o.ords_stas_id = 80) or
(s.STKS_PRINT_BTN_STATUS like '%231%' and o.ords_stas_id = 23);

虽然这会消除一些重复,但我希望你真的想要实现其他目的吗?