2013-08-05 76 views
0

當我使用SQL_CALC_FOUND_ROWS運行以下查詢或使用IN子句在子查詢中指定所有顏色RED,BLUE,YELLOW時,我得到的記錄數爲198。但是,當我單獨執行每種顏色時,我會得到一個COUNT,合計爲248 (72 + 59 + 118)。額外的50行從哪裏來?我會想,如果我單獨做了他們,然後加上他們,我會得到198,但我得到248。我是否查看IN子句如何正確工作?我寧願用COUNT代替SQL_CALC_FOUND_ROWS因爲我發現SQL_CALC_FOUND_ROWS要慢得多(+3秒),在mysql查詢中計數不同的原因是什麼?

這裏有一些數據:

1. I am running MySQL Version: 5.5.2 
2. The tables engine is INNODB. 
3. All the `CHECK TABLE .... EXTENDED` return OK. 

-- Returns 198 
SELECT SQL_CALC_FOUND_ROWS DISTINCT p.* FROM Persons AS p 
INNER JOIN Colors AS c ON c.PersonId = p.Id 
WHERE p.Name = 'John Doe' AND c.ColorName IN ('YELLOW','RED','BLUE'); 
SELECT FOUND_ROWS(); 

-- Returns 198 
SELECT COUNT(1) as MyCount FROM (SELECT DISTINCT p.* FROM Persons AS p 
INNER JOIN Colors AS c ON c.PersonId = p.Id 
WHERE p.Name = 'John Doe' AND c.ColorName IN ('YELLOW','RED','BLUE')) all; 

-- Returns 72 
SELECT COUNT(1) as MyCount FROM (SELECT DISTINCT p.* FROM Persons AS p 
INNER JOIN Colors AS c ON c.PersonId = p.Id 
WHERE p.Name = 'John Doe' AND c.ColorName IN ('RED')) red; 

-- Returns 59 
SELECT COUNT(1) as MyCount FROM (SELECT DISTINCT p.* FROM Persons AS p 
INNER JOIN Colors AS c ON c.PersonId = p.Id 
WHERE p.Name = 'John Doe' AND c.ColorName IN ('BLUE')) blue; 

-- Returns 118 
SELECT COUNT(1) as MyCount FROM (SELECT DISTINCT p.* FROM Persons AS p 
INNER JOIN Colors AS c ON c.PersonId = p.Id 
WHERE p.Name = 'John Doe' AND c.ColorName IN ('YELLOW')) yellow; 
+0

http://stackoverflow.com/questions/18025315/no-mysql-records-return-when-past-a-certain-limit –

+0

@MitchWheat - 是的,它被擱置了,這樣做更有意義,更清晰。 – Xaisoft

回答

1

像這樣的事情正在發生:

Persons

ID Name 
-- ------------ 
1 John Doe 
2 Xaisoft 

Colors

PersonID ColorName 
-------- --------- 
     1 Red 
     1 Yellow 
     2 Yellow 

現在查詢Persons.*John Doe同時加入到Colors

SELECT p.* 
FROM Persons p 
INNER JOIN Colors C ON c.PersonID = p.ID 
WHERE p.Name = 'John Doe'; 

你的結果會是下李四一個p.*每種顏色行:

​​

如果應用COUNT DISTINCT對此,您將以1結束。

如果分別計算RedYellow,則每個查詢都會得到一個。把它們加起來,你會得到2


看看這樣說:如果你扔出去的COUNT,只是SELECT DISTINCT Persons.*你得到這些結果:

紅色或黃色的李四

SELECT DISTINCT p.* 
FROM Persons p 
INNER JOIN Colors C ON c.PersonID = p.ID 
WHERE p.Name = 'John Doe' 
    AND c.ColorName IN ('RED', 'YELLOW'); 

ID Name 
-- ---------- 
1 John Doe 

只紅對於John Doe

SELECT DISTINCT p.* 
FROM Persons p 
INNER JOIN Colors C ON c.PersonID = p.ID 
WHERE p.Name = 'John Doe' 
    AND c.ColorName IN ('RED'); 

ID Name 
-- ---------- 
1 John Doe 

只爲李四黃色:

SELECT DISTINCT p.* 
FROM Persons p 
INNER JOIN Colors C ON c.PersonID = p.ID 
WHERE p.Name = 'John Doe' 
    AND c.ColorName IN ('YELLOW'); 

ID Name 
-- ---------- 
1 John Doe 
+0

但我正在應用一個DISTINCT COUNT到個別的。 – Xaisoft

+0

但是,您的不同計數僅基於「人員」表格,而不是基於人員和顏色。我爲我的答案增加了一個例子。看一看。如果沒有任何意義,請嘗試運行上面的第二個到第五個查詢,以'SELECT * FROM'開始,而不是'SELECT COUNT(1)'作爲MyCount FROM'。您將在查詢3,4和5中獲得重複名稱。由於「DISTINCT」,這些名稱對於查詢2而言*不重複。 –

+0

我在這裏修改了我的查詢來查看實際從內部表返回的內容,並且我確實注意到可能會解釋額外行的重複或非重複值。感謝您指點我正確的方向。說實話,我還是不太明白它的100%,但我有一半在那裏:) – Xaisoft

相關問題