Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check if a table exists before join?

Tags:

mysql

I have the following problem. I have Table A and would like to join to table B if table B exists. Can this be done? I am only writing SQL in WorkBench to try achieve it.

I am aware I cannot use the EXISTS option as I have tried typing it out but it prompts for an error.

Any suggestions would be greatly appreciated.

Thanks.

like image 788
Nora Avatar asked Sep 29 '15 15:09

Nora


People also ask

How do you check if a table exists in a schema?

How to check whether a table (or view) exists, and the current user has access to it? SELECT EXISTS ( SELECT FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' ); The information schema is mainly useful to stay portable across major versions and across different RDBMS.

How do you know if data exists in one table and not in another?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.


1 Answers

I managed to do this using EXECUTE, so using a query that is only prepared at runtime:

SET @sqlCommand = IF(
    EXISTS (SELECT column_name FROM information_schema.columns WHERE table_schema = '{{yourschemaname}}' AND table_name = '{{yourtablename}}' AND column_name = '{{yourcolumnname}}'), 
    'SELECT \'Yes! Good to go!\' as ColumnExists',
    'SELECT \'Nope!\' as ColumnExists');
PREPARE executable FROM @sqlCommand;
EXECUTE executable;

Note that the two selects at the center (Yes!/No!) are the custom statements that are to be executed conditionally. So if the column exists, the first command is executed (select 'yes!'), otherwise the second one (select 'nope').

I got the hint from this discussion here.. have a look if you're looking for the MSSQL equivalent: https://ask.sqlservercentral.com/questions/97579/check-if-table-exists-in-join.html

like image 194
Efrain Avatar answered Nov 10 '22 08:11

Efrain