Do not fill in field if it does not exist

Asked

Viewed 160 times

5

I have a question on 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'

Upshot

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

The 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 or put a 0 or ''

I did:

SELECT * FROM tabela1, tabela2;

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

3 answers

3


You can use the 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

0

Use the function Coalesce or Isnull if it is 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 have a restructured database. You will have many similar problems.

  • If did Select id, coalesce(tabela1.tipoA, 0) as tipoA, coalesce(tabela.tipoB, 0) as tipoB From tabela1, tabela2 But, I think this command is simply asking each table separately if it has the null field, and it will never happen.

  • Does this query work? I mean, if the two tables have the fields id and data, Mysql will choke because the references to id and data are ambiguous.

  • I forced the error in the query.

0

When you create a table, perform the following commands:

Create table ( id number(Qt desired), Obs:varchar for names, int for numbers.

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

  • I’m using a database that wasn’t created by me, it’s already a few years old.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.