How to set SQL condition precedence for two different conditions

I'm having two different tables ' TABLE1 ' and ' TABLE2 '. Both of these tables have same column name - ' IS_PDF '.

RE TABLE1.IS_PDF value, I retrieved the required details using select statement where I added where clause like below.

select * from TABLE1 where TABLE1.IS_PDF = 'Y';

Similarly, I can get the values for TABLE2 as well where TABLE2.IS_PDF = 'Y'

Now, my task is to have one select statement to get the details from both tables ' TABLE1 ' and ' TABLE2 ' by setting a precedence on below condition # 1 .

  • If TABLE1.IS_PDF = 'Y' , return records matching same condition.
  • If TABLE1.IS_PDF = 'N' but TABLE2.IS_PDF = 'Y' then return records matching same condition.
  • If both have IS_PDF = 'N', return nothing.
  • I used below Select statement but getting Above conditions # 1 and 2 at the same time only.

    select * from TABLE1, TABLE2
    where
    (TABLE1.IS_PDF = 'Y') or (TABLE2.IS_PDF = 'Y' and TABLE1.IS_PDF = 'N' )
    

    Please guide on the same. Thanks


    You seem to want something like this:

    select t1.*
    from table1 t1
    where t1.is_pdf = 'Y'
    union all
    select t2.*
    from table2 t2
    where t2.is_pdf = 'Y' and
          not exists (select 1 from table1 t1 where t1.is_pdf = 'Y' and t1.?? = t2.??);
    

    The ?? represents the column(s) used for matching between the two tables.


    Thanks for the quick response.

    Sample code-

    select TABLE1.IS_PDF, TABLE2.IS_PDF, TABLE1.ID, TABLE1.GLOBAL_ID, TABLE1.title, 
    from TABLE1, TABLE2
    where TABLE1.USER_ID = 82340
    and TABLE1.NAME = 'INDIA'
    and (TABLE1.IS_PDF = 'Y') or (TABLE2.IS_PDF = 'Y' and TABLE1.IS_PDF = 'N' )
    

    I need to set a precedence on below condition # 1. If condition # 1 meets, it's fine. Otherwise go for #2 then #3.

  • If TABLE1.IS_PDF = 'Y', return records matching same condition.
  • If TABLE1.IS_PDF = 'N' but TABLE2.IS_PDF = 'Y' then return records matching same condition.
  • If both have IS_PDF = 'N', return nothing.
  • 链接地址: http://www.djcxy.com/p/71112.html

    上一篇: WinForms中的数据绑定执行异步数据导入

    下一篇: 如何为两种不同的条件设置SQL条件优先级