Skip to content
Advertisement

How to write SQL for combination of AND?

Please check the attached table.

enter image description here

I need to write a query to get documents which have both tage_id of say 32 and 26.

Something like select * from doc_tags where tag_id = 32 or tag_id = 26 is not going to work as I will get both documents with 32, 26, and ( 32, 26 ).

I need documents which only have tag id 32 **and 26 not individual.**

NOTE I can’t use the document_id as a reference.

Advertisement

Answer

select * from doc_tags dt1
where (
    select count(distinct tag_id) from doc_tags dt2
    where dt2.document_id = dt1.document_id and tag_id in (26, 32)
) = 2 and dt1.tag_id in (26, 32)

or

with data as (
    select *,
        count(distinct tag_id) over (partition by document_id) as matches
    from doc_tags where tag_id in (26, 32)
)
select * from data where matches = 2
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement