Doubt regarding the IN in Oracle

Asked

Viewed 28 times

1

I’m putting together a query and bumped into a question.

My query is like this:

SELECT BASI_030.NIVEL_ESTRUTURA NIVEL,
       BASI_030.REFERENCIA GRUPO,
       BASI_030.DESCR_REFERENCIA,
       BASI_030.CONTA_ESTOQUE,
       BASI_020.TIPO_PRODUTO
  FROM BASI_030
  JOIN BASI_020
    ON BASI_030.NIVEL_ESTRUTURA = BASI_020.BASI030_NIVEL030
   AND BASI_030.REFERENCIA = BASI_020.BASI030_REFERENC
 WHERE BASI_030.NIVEL_ESTRUTURA = 2
   AND BASI_030.CONTA_ESTOQUE IN (77, 87, 92)
   AND BASI_030.REFERENCIA IN ( SELECT MCREF.REFERENCIA
                                  FROM MARK_CAMPANHA_REF MCREF
                                 WHERE MCREF.ID_CAMPANHA = 16 )

It is working, but when the MARK_CAMPANHA_REF table has no REFERENCE, I would have to bring all references contained in the BASI_030 table

As it is, when the MARK_CAMPANHA_REF table has no records for ID_CAMPANHA, the query returns no value.

Could you help me?

1 answer

2


It would be a mix of LEFT JOIN with CTE to realize the logic.

WITH sql AS (
    SELECT BASI_030.NIVEL_ESTRUTURA NIVEL,
           BASI_030.REFERENCIA GRUPO,
           BASI_030.DESCR_REFERENCIA,
           BASI_030.CONTA_ESTOQUE,
           BASI_020.TIPO_PRODUTO,
           MCREF.REFERENCIA REFERENCIA_MCREF   
    FROM BASI_030   
    JOIN BASI_020
       ON BASI_030.NIVEL_ESTRUTURA = BASI_020.BASI030_NIVEL030    
      AND BASI_030.REFERENCIA = BASI_020.BASI030_REFERENC  
    LEF JOIN MARK_CAMPANHA_REF MCREF
        ON MCREF.ID_CAMPANHA = 16
       AND MCREF.REFERENCIA = BASI_030.REFERENCIA
    WHERE BASI_030.NIVEL_ESTRUTURA = 2    
      AND BASI_030.CONTA_ESTOQUE IN (77, 87, 92) 
)
  , test AS (
    SELECT count(*) qtd
    FROM sql
    WHERE REFERENCIA_MCREF IS NOT NULL
)
SELECT *
FROM sql
WHERE  (
        CASE
        WHEN ((SELECT qtd
               FROM test) > 0)
          THEN
            REFERENCIA_MCREF IS NOT NULL
        ELSE
          1 = 1
        END)
  • Hi @Rafael, yeah, that’s right. But what I need is... if it exists in MARK_CAMPANHA_REF, show only those that exist in both, what my code is doing. But if there is no record in the MARK_CAMPANHA_REF table, show all BASI_030 records. It would be something like the subquery that is in the IN not returning anything, show all references of BASI_030. I don’t know if I made myself clear.

  • 1

    I changed to include possibility to use logic. It’s LEFT JOIN with CTE.

  • Finally I made more changes and I didn’t need to use it, but it works great. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.