1

我想我误解了 SQL。当我尝试以下矛盾的查询时:

SELECT id, key, value FROM Things WHERE value > 1 AND key = 'key' AND id IN (
    SELECT id 
    FROM Things 
    WHERE key = 'key' AND value < 1
) GROUP BY id, key, value LIMIT 2;

我得到以下结果:

  id    | key        | value
--------+------------+-----------
  92    |         18 |         2
   4    |         18 |         2

同样,当我尝试此查询时:

SELECT id, key, value FROM Things a WHERE value > 1 AND key = 'key' AND EXISTS (
    SELECT * 
    FROM Things b 
    WHERE a.id = b.id AND a.key = b.key AND b.value < 1
) GROUP BY id, key, value LIMIT 2;

我得到相同的结果:

  id    | key        | value
--------+------------+-----------
  92    |         18 |         2
   4    |         18 |         2

最后,当我尝试这个时,我得到了正确的结果:

SELECT X.id, X.key, X.value FROM (
    SELECT id, key, value   
    FROM Things   
    WHERE key = 'key' and value < 1
) AS X WHERE X.key = 'key' AND X.value > 1 GROUP BY id, key, value LIMIT 2;

  id    | key        | value
--------+------------+-----------

我想也许索引在弄乱我,但我确保没有索引并且它仍然表现得像这样。

有人可以解释为什么会发生这种情况以及我误解了什么吗?

4

1 回答 1

1

此查询说明了什么:

SELECT id, key, value FROM Things WHERE value > 1 AND key = 'key' AND id IN (
    SELECT id FROM Things WHERE key = 'key' AND value < 1
) GROUP BY id, key, value LIMIT 2;

即,查找所有具有键key的事物,其中行value < 1和行都value > 1存在。这并不矛盾。

您的第二个查询做同样的事情,除了它要求两行id除了key.

您的最后一个查询查找具有两个属性的单行。这将返回一个空集,因为没有值既小于又大于一。

于 2013-05-06T11:26:49.893 回答