2017-02-21 108 views
0

有没有什么办法来缩短这个查询就像使用案例,例如?如何缩短这个SQL查询?

 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) 
+0

查找公用部分,如'o.lsnr不为空'和'o.ords_id = orderid',你只需要它们一次。 – jarlh

回答

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)) 
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)); 
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); 

虽然去除一些重复,我想你实际上是想实现什么东西?

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) 
; 
+0

这很好。谢谢! –