Do not fill field if it does not exist

5

I have a question about how to ask a question to the database.

Suppose I have two tables with slightly different structures

Table1

id      tipoA    data
0        A       '21/12/14'

Table2

id      tipoB    data
1        B       '24/12/14'

Result

id      tipoA    tipoB    data
0        A         B      '21/12/14'
1        A         B      '24/12/14'

Expected

   id      tipoA    tipoB    data
    0        A         0      '21/12/14'
    1        0         B      '24/12/14'

I simply want that if the field does not exist to not fill it out or put a 0 or ''

I did:

SELECT * FROM tabela1, tabela2;

but this command does not return the expected result. How should I do?

    
asked by anonymous 16.06.2015 / 16:26

3 answers

3

You can use UNION and make 2 selects, example:

SELECT id, tipoA, 0 as tipoB, data FROM tabela1
UNION ALL
SELECT id, 0 as tipoA, tipoB, data FROM tabela2

SqlFiddle Demo

    
16.06.2015 / 17:16
0

Use the Coalesce or IsNull function if SQL. If it is MySQL use IFNull .

Select id, coalesce(tipoA, 0) as tipoA, coalesce(tipoB, 0) as tipoB From tabela1, tabela2

But it is good to give a restructured database. You will have many problems of the same kind.

    
16.06.2015 / 16:40
0

When you create a table, perform the following commands:

Create table ( id number (desired qt),   Note: varchar for names, int for numbers.

Do not put auto-increment, or not null in the columns, only in id.

    
16.06.2015 / 17:00