sql >> Base de Datos >  >> RDS >> PostgreSQL

Consulta SQL de muchos a muchos para seleccionar todas las imágenes etiquetadas con ciertas palabras

Aquí está la consulta de trabajo que escribí:

SELECT i.id, i.relative_url, count(*) as number_of_tags_matched
FROM   images i
    join tags_image_relations ti on i.id = ti.image_id
    join tags t on t.id = ti.tag_id
    where t.name in ('google','microsoft','apple')
    group by i.id having count(i.id) <= 3
    order by count(i.id)

Esta consulta mostrará primero las imágenes que coincidan con las tres etiquetas, luego las imágenes que coincidan con al menos 2 de las 3 etiquetas y finalmente con al menos 1 etiqueta.