2017-10-21 94 views
1

我需要計算列A中有重複記錄的行數,而列B必須是1並且也要被複制。MySQL查詢顯示兩列中的重複信息

SELECT COUNT(*) as num 
FROM myTable 
WHERE (columnB = 1 GROUP BY columnB HAVING COUNT(id_myTable) > 1) AND (columnA IN (SELECT columnA FROM myTable GROUP BY columnA HAVING COUNT(id_myTable) > 1)) 
ORDER BY columnC ASC` 

假設你有這些表在MySQL爲myTable:

/---------------------------------/ 
|  id | ColumnA | Column B | 
|---------------------------------| 
|   1 | Andre |  1 | 
|   2 | Joao |  2 | 
|   3 | Maria |  1 | 
|   4 | Joao |  1 | 
|   5 | Andre |  1 | 
|   6 | Maria |  1 | 
|   7 | Andre |  2 | 
/---------------------------------/ 

的結果必須是4,因爲只有ID 1,3,5和6的重複兩列和columnB的條件必須總是等於1

我的PHP代碼給結果:

$query = "select sum(c) from (select count(1) as c from myTable group by columnA, columnB having count(1) > 1 and columnB = 1) t"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[c]; $total_rows = $total_pages;

+2

您的查詢在語法上不正確的。您應該提供樣本數據和期望的結果。 –

+0

我@GordonLinoff,我盡力解釋我的問題。 – MSimoes

回答

1
select sum(c) from (
        select count(1) as c from myTable 
        group by ColumnA, ColumnB 
        having count(1) > 1 and ColumnB=1 
        ) t 
+0

感謝@jophab爲您的答覆,它的工作。它給出了預期的結果。 – MSimoes

+0

我發現了一個問題,我用表中的2個新行編輯了我的問題。在我的數據庫中,例如,我更改了id 6的狀態(columnB),結果必須是4,並且您的查詢會給我2個。 – MSimoes

+1

@MSimoes我已更新我的答案。查詢是從內部查詢獲得的結果的別名。一些別名是必須的。 – jophab

1

我相信你想:

select sum(cnt) 
from (select columnA, columnB, count(*) as cnt 
     from myTable 
     where columnB = 1 
     group by columnA, columnB 
     having count(*) > 1 -- or do you mean `count(*) = 2`? 
    ) ab; 
+0

謝謝@GordonLinoff。我的意思是> 1不等於2,我需要那個columnB總是等於1,因爲它是一個活躍的狀態。順便說一下,我不明白ab;在查詢結束時。 – MSimoes

+0

我注意到你已經改變了你的回覆,謝謝,我想我的問題和jophab的代碼一樣。你可以看到我的回覆。 – MSimoes