How to do a select within a condition?

5

How can I do to create a script in SQL where a SELECT runs, and according to the result of a column of this first, a certain condition of another table?

example:

select * from tabela as t
SE t.saldo = 0 entao WHERE t2.outracondicao = 'condicao'
    
asked by anonymous 14.09.2018 / 13:19

3 answers

5
SELECT * 
FROM tabela AS t
WHERE (t.saldo = 0 
       AND EXISTS (SELECT 1 
                   FROM tabela2 AS t2 
                   WHERE t2.outracondicao = 'condicao'))
  -- OR t.saldo <> 0 

When the balance is equal to zero, the search will only be performed if the condition of the second table is met (as you did not show the structure of the tables, I kept the "information" in the question). The commented passage ( --OR t.saldo <> 0 ) can be used if you need to. It will execute the query if the balance is nonzero.

Another alternative is that the before query should be validated. If the validation in tabela2 is independent of tabela , it can be done like this:

IF EXISTS (SELECT 1 FROM tabela2 AS t2 WHERE t2.outracondicao = 'condicao')
BEGIN
    SELECT * 
    FROM tabela AS t
    WHERE t.saldo = 0 
END

As suggested by @rbz , I've created a example online for validation.

    
14.09.2018 / 14:27
3

In this case, if you have two fields in common within the two tables, you can use WHERE IN

Let's say there is the ID field in table2 that is also present in table1. You could do this:

SELECT * FROM tabela2 WHERE id IN (SELECT id FROM tabela1 WHERE saldo='0')

This query will fetch all records from table2 that are also present in table1, but only with balance 0.

    
14.09.2018 / 13:25
2

This mode may help you:

SELECT t.* FROM tabela t
JOIN tabela2 t2
    ON t2.id = t.id
WHERE 
    t2.outracondicao = (CASE
                        WHEN t.saldo = 0
                            THEN 'condicao'
                        END)
    
14.09.2018 / 15:28