我有一个SQL查询,为我提供了一个包含数据库中双记录的列表。
select periodid, itemid from periodscore
group by periodid, itemid
having count(*) > 1
这可以按预期工作,但现在我想检索这些记录的其他字段(例如上次更新的日期等)。所以我试过了:
select * from periodscore where periodscoreid in
(select periodscoreid from periodscore
group by periodid, itemid
having count(*) > 1)
当然这不起作用并给我错误:
列'periodscore.PeriodScoreID'是 因为它在选择列表中无效 不包含在任何一个 聚合函数或GROUP BY 子句。
如何检索此查询中的额外字段?
答案 0 :(得分:2)
select ps.*
from periodscore ps
inner join (
select periodid, itemid
from periodscore
group by periodid, itemid
having count(*) > 1
) psm on ps.periodid = psm.periodid and ps.itemid = psm.itemid
答案 1 :(得分:1)
select p1.* from periodscore p1 JOIN
(select periodid, itemid from periodscore
group by periodid, itemid
having count(*) > 1) p2
ON (p1.periodId = p2.periodId
AND p1.itemid = p2.itemid)
如果periodid或item具有空值,则
select p1.* from periodscore p1 JOIN
(select periodid, itemid from periodscore
group by periodid, itemid
having count(*) > 1) p2
ON (IFNULL(p1.periodId,0) = IFNULL(p2.periodId,0))
AND IFNULL(p1.itemid,0) = IFNULL(p2.itemid,0))