2010-09-08 110 views
2

我有一個SQL查詢向我提供數據庫中的雙記錄列表。從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) 

當然,這並不工作,給我的錯誤:

Column 'periodscore.PeriodScoreID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我怎樣才能檢索到在此查詢的附加字段?

回答

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 
+0

謝謝!這個查詢也給我216記錄,而不是原來的103​​ – Sam 2010-09-08 11:41:24

+1

@Sam - 第一個查詢告訴你的組。這會爲您提供屬於這些組的行。當然,所有的組將至少有2行,因爲這是查詢的目的!如果你只想每組返回一行,那麼哪一行? – 2010-09-08 11:48:54

+0

嗯,好點:)謝謝你的答案! – Sam 2010-09-08 11:53:38

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或項目有快速的答案空值,那麼

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)) 
+0

感謝您的快速答案!然而,這個查詢似乎給我關於從原始的一個記錄的雙倍數...原始的一個給了我103條記錄,這一個216 ... – Sam 2010-09-08 11:39:26

+0

@Same,當periodid或itemid爲null時添加IFNULL – 2010-09-08 11:46:48

+0

我猜你的意思是ISNULL? ID實際上是唯一標識符,但您無法知道這一點。 – Sam 2010-09-08 11:49:01