ulquiorra ulquiorra - 16 days ago 5
SQL Question

SQL : transform union query to a single query

I have a database schema like this

User

id

matricule

Document

id

title

user_id(foreign key to user)

mode( can accept PUBLIC or PRIVATE)

I want to retrieve all document which are public and all documents which belongs to a given user(matricule)

I did a union query like this :

select * document d
Inner join user u ON u.id = d.user_id
and u.matricule ='matricule1'
UNION
select * from document d
Inner join user u ON u.id = d.user_id
where d.mode ='PUBLIC'


which works well but can i achieve the same result with another way( i read somewhere that union queries are bad for performance) like subquery for example ?

Thank you very much

Answer
select distinct *
from document d
Inner join user u ON u.id = d.user_id 
where u.matricule = 'matricule1' or d.mode ='PUBLIC' 

SELECT DISTINCT to remove duplicates just as UNION does. (Perhaps you want just SELECT?)