2017-05-04 49 views
1

我有一些麻煩,一個SQL查詢來發現雙項:SQL查詢發現複式

MYTABLE

id(int), eid(int), date(date), pid(int) 

一些刀片:

1, 10, '2017-05-04', 1 
2, 20, '2017-05-04', 1 
3, 10, '2017-05-04', 5 

我想找到雙項eid到一個日期 結果:

1, 10, '2017-05-04', 1 
3, 10, '2017-05-04', 5 

我的第一個想法是GROUP BY和HAVING,但它不起作用。

SELECT id, eid, date, pid, COUNT(pid) AS NumOccurrences 
FROM `mytable` 
HAVING (COUNT(pid) > 1) 

如果你試圖幫助我,我已經做了我的一天,感謝先進!

回答

2

使用exists()

select * 
from mytable t 
where exists (
    select 1 
    from mytable i 
    where t.eid = i.eid 
    and t.date = i.date 
    and t.id <> i.id 
    ) 

inner join版本,雖然你可能取決於你有多少重複對每一對獲得額外的行。如果是這樣,你可以添加distinct

select t.* 
from mytable t 
    inner join mytable i 
    on t.eid = i.eid 
    and t.date = i.date 
    and t.id <> i.id 
+0

完美!感謝您的快速行動! – Korty

+0

@Korty樂意幫忙! – SqlZim

+0

exists()是正確的解決方案 – Korty

0

你應該嘗試這種解決方案:SELECT DISTINCT id, eid, date, pid, COUNT(pid) AS NumOccurrences FROM mytable