0

tbl父母

parentId | childId
---------+-----
102      |  1
102      |  3
102      |  4
104      |  3
...

tbl人气

Id | popularityScore
---+-----
1  | 4000
2  | 8000
3  | 3000
4  | 2000
...

我有一个查询,可以找到最流行的 childId,给定一个 parentId。我想将几个查询组合在一起以获得一组 parentItemId 中最受欢迎的项目,例如(102, 104, ...)

期望的输出

parentId   | mostPopularChildId
           | i.e. the childId with the maximum popularityScore for the given parentId
-----------+-----
102        | 1
104        | 3
...
  • 我怎样才能做到这一点?
  • 它会比运行单个查询快得多吗?
4

2 回答 2

1

要在 SQLite 中进行这样的查询,您可以计算最大分数,然后连接回表以获取 id:

select pp.ParentId, po.Id, pp.maxscore
from (select pa.ParentID, max(PopularityScore) as maxscore
      from tblParent pa join
           tblPopularity po
           on pa.ChildId = po.Id
     ) pp join
     tblParent pa
     on pa.ParentId = pp.ParentId join
     tblPopularity po
     on pa.ChildId = po.Id and
        po.PopularityScore = pp.maxscore
where . . .
于 2013-05-24T10:37:19.930 回答
1

MIN在 SQLite 3.7.11 或更高版本中,可以从匹配/的记录中获取其他列MAX

SELECT parentId,
       childId AS mostPopularChildId,
       MAX(popularityScore)
FROM tblParents
JOIN tblPopularity ON tblParents.childId = tblPopularity.Id
GROUP BY parentId
于 2013-05-24T10:39:47.627 回答