0

当我使用子句运行以下查询或指定子查询中的SQL_CALC_FOUND_ROWS所有颜色时,我得到的记录计数为. 但是当我单独做每种颜色时,我得到的加起来是. 额外的 50 行从何而来?我原以为如果我单独做然后把它们加起来,我会得到,但我得到了。我是否正在查看 IN 子句的工作方式不正确?我更喜欢使用而不是因为我发现要慢得多(+3 秒)RED,BLUE,YELLOWIN198COUNT248 (72 + 59 + 118)198248COUNTSQL_CALC_FOUND_ROWSSQL_CALC_FOUND_ROWS

以下是一些统计数据:

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;
4

1 回答 1

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';

您的结果将是John Doe 下每种颜色的p.*一行:

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

如果您COUNT DISTINCT对此应用 a ,您最终会得到1.

如果您分别计算RedYellow则每个查询都会得到一个。把它们加起来,你会得到2.


以这种方式看待它:如果你扔掉了COUNTSELECT DISTINCT Persons.*你就会得到这些结果:

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', '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

黄色仅适用于 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
于 2013-08-05T14:33:05.677 回答