【问题标题】:Selection of rows related to a set of other rows选择与一组其他行相关的行
【发布时间】:2010-03-06 11:27:27
【问题描述】:

假设我有两个表,“实体”和“标签”。它们之间的关系由第三个表“entity_tags”表示,该表具有字段:entity_id 和 tag_id。我想选择所有按与给定标签集的相关性排序的实体。例如,有“banana”、“orange”、“potato”、“pen”和“car”作为实体,我想过滤与 至少 2 个标签相关的所有实体“水果”、“有机”和“物品”。最好的方法是什么?

首先要想到的是使用类似查询

select entity.*
     , count(*) as relevance 
  from entities
     , tags
     , entity_tags
 where entities.id=entity_tags.entity_id 
   and tags.id=entity_tags.tag_id
   and tags.name in ('fruit', 'organic', 'item')
group by entity.id 
order by relevance

但不可能将and relevance > 1 添加到where,sqlite 正在报告“滥用聚合”。 结果应如下所示:

1|banana|3
2|orange|3
3|potato|2

顺便说一句,在计算这些行时是否可以避免嵌套选择?

select count(*) 
  from (<previous select>)

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    试试这个(未经测试)

    select entity.*
         , count(*) as relevance 
      from entities
         , tags
         , entity_tags
     where entities.id=entity_tags.entity_id 
       and tags.id=entity_tags.tag_id
       and tags.name in ('fruit', 'organic', 'item')
    group by entity.id  having count(entities.id) > 1
    order by relevance
    

    还可以查看 here 以获取有关 SQLite 的帮助,并在 this 页面中搜索“有”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      相关资源
      最近更新 更多