tblParents
parentId | childId
---------+-----
102 | 1
102 | 3
102 | 4
104 | 3
...
tblPopularity
Id | popularityScore
---+-----
1 | 4000
2 | 8000
3 | 3000
4 | 2000
...
我有一个查询,在给定parentId的情况下找到最受欢迎的childId。我想将几个查询组合在一起以获得一组parentItemId中最受欢迎的项目,例如(102, 104, ...)
。
所需的输出
parentId | mostPopularChildId
| i.e. the childId with the maximum popularityScore for the given parentId
-----------+-----
102 | 1
104 | 3
...
答案 0 :(得分: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 . . .
答案 1 :(得分:1)
在SQLite 3.7.11或更高版本中,可以从记录中获取与MIN
/ MAX
匹配的其他列:
SELECT parentId,
childId AS mostPopularChildId,
MAX(popularityScore)
FROM tblParents
JOIN tblPopularity ON tblParents.childId = tblPopularity.Id
GROUP BY parentId