Only join if the above query returns records

Asked

Viewed 83 times

4

Good staff,

I would like to know what approach they would take to make a union only if the above query of the union returns values. Consider that the tables are compatible EX:

SELECT * FROM Tabela1
UNION
SELECT * FROM Tabela2 
/*Esta query so deve ser executada apenas se a query acima, select * from Tabela1, tiver devolvido algum valor*/

Regards, Leandro

  • As far as I know you can’t.

  • @Ricardo Directly I think there really is nothing like it. But there will be some way to "provoke" this behavior?

  • It worked the query below?

  • @Dotnet I’m sorry but I haven’t been able to test it yet. I am without access to the database. However I have seen the proposal and I have understood your thinking. However I have a question. The table data type exists in mysql?

  • If you refer to the creation "declare @Tabela2 table", not exactly this way.

  • The table type exists in any database, now the temporary table creation varies in some databases, the way I used is for SQLSERVER, but select itself works in mysql without problem.

Show 1 more comment

4 answers

0

Hello, please try the following code:

SELECT * FROM (
  SELECT * FROM Tabela1
  UNION
  SELECT * FROM Tabela2
) a
WHERE EXISTS(
  SELECT 1 FROM Tabela1
)

0

Only if you use the table above to filter the second

declare @Tabela1 table
(
    id int
)

declare @Tabela2 table
(
    id int
)

--insert into @Tabela1 values (1),(2),(3),(4)
insert into @Tabela2 values (1),(2),(3),(5)


SELECT * FROM @Tabela1
UNION
SELECT * FROM @Tabela2 
where exists (SELECT top 1 id FROM @Tabela1)

0

I did a test with the instruction below and it worked (I think it’s easy to understand):

select * from bairro where id = 1
   union
   select * from bairro where id > 15 and
     EXISTS (select FIRST 1 * from bairro where id = 1)

-1

SELECT
*
FROM(
    SELECT * FROM Tabela1
    UNION ALL
    SELECT * from Tabela2) as aux
WHERE (SELECT COUNT(*) FROM Tabela1) > 0

Browser other questions tagged

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