Select from table if record found in another table

后端 未结 2 1025
独厮守ぢ
独厮守ぢ 2020-12-21 08:19

I need to select some rows from Table 1 lets say if a value is found in Table 2. So I want to check if the value (I will enter the value from command line) is found in Table

相关标签:
2条回答
  • 2020-12-21 08:54

    This query will select from Table1 if :id exists in Table3, and from Table2 otherwise:

    select  *
    from    Table1
    where   exists
            (
            select  *
            from    Table3
            where   id = :id
            )
    union all
    select  *
    from    Table2
    where   not exists
            (
            select  *
            from    Table3
            where   id = :id
            )
    
    0 讨论(0)
  • 2020-12-21 09:02

    You can do something like this:

    -- If value is found in table2, select from table1
    select * -- <- use padding if necessary 
      from table1
     where exists (select 1
                     from table2
                    where myField = value)
    
    union all
    
    -- If value is not found in table2, select from another_Table
    select * -- <- use padding if necessary
      from another_Table
     where not exists (select 1
                         from table2
                        where myField = value)
    
    0 讨论(0)
提交回复
热议问题