我有下表:
CREATE TABLE sample (
id INT
);
假设我有 x 行。
我这样做SELECT COUNT(1) FROM sample
并得到 x 回来。
现在说我这样做:
SELECT COUNT(1)
FROM sample AS s1
JOIN sample AS s2
ON s2.id < s1.id;
这让我 (x*(x-1))/2 行回来了。
现在说我这样做:
SELECT COUNT(1)
FROM sample AS s1
JOIN sample AS s2
ON s2.id < s1.id
LEFT JOIN sample AS s3
ON s3.id < s2.id;
这让我明白了x*(x-1)*(x-2)/6+(x-1)
。如果我做了一个 JOIN 而不是一个 LEFT JOIN 我会得到回x*(x-1)*(x-2)/6
行。
SELECT COUNT(1)
FROM sample AS s1
JOIN sample AS s2
ON s2.id < s1.id
LEFT JOIN sample AS s3
ON s3.id < s2.id
LEFT JOIN sample AS s4
ON s4.id > s2.id
AND s4.id < s1.id;
我不知道我会回来多少行。
顺便说一句,最终查询的目的是为您提供第二个 id。例如。
SELECT s1.id
FROM sample AS s1
JOIN sample AS s2
ON s2.id < s1.id
LEFT JOIN sample AS s3
ON s3.id < s2.id
LEFT JOIN sample AS s4
ON s4.id > s2.id
AND s4.id < s1.id
WHERE s3.id IS NULL
AND s4.id IS NULL;
当 id 有与之关联的用户并且您尝试为特定用户或所有用户查找第二个 id 时,它会更有用。我只是想了解它是如何渐近执行的。
有任何想法吗?谢谢!