Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from table if record found in another table

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 and then select rows from Table1, if not I want to select rows from another table. I tried CASE but from what I got that works only if you want to check for value within one table. Any idea?

like image 573
Noah Martin Avatar asked Dec 12 '25 17:12

Noah Martin


1 Answers

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)
like image 172
Dmitry Bychenko Avatar answered Dec 15 '25 10:12

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!