-1

我尝试在data.stackexchange.com上编写一个查询,它可以回答我写过帖子且被查看超过 1000 次并且拥有某个类别的徽章的用户的百分比是多少。

问题:如果我写AND ViewCount > 1000,我会得到相同的结果,因为WHERE ViewCount > 1000 我不明白为什么会发生

带有 WHERE 的查询:

SELECT 
TOP 1000 
Class, (Count(Badges.UserId)* 100 / (SELECT COUNT(*) From Badges)) AS Percentage 
FROM Badges 
WHERE Badges.UserId IN (SELECT Posts.OwnerUserId FROM Posts 
INNER JOIN 
Badges ON Posts.OwnerUserId = Badges.UserId 
WHERE ViewCount > 1000) 
GROUP BY Class 
ORDER BY Class

带有 AND 的查询:

SELECT 
TOP 1000 
Class, (Count(Badges.UserId)* 100 / (SELECT COUNT(*) From Badges)) AS Percentage 
FROM Badges 
WHERE Badges.UserId IN (SELECT Posts.OwnerUserId FROM Posts 
INNER JOIN 
Badges ON Posts.OwnerUserId = Badges.UserId 
AND ViewCount > 1000) 
GROUP BY Class 
ORDER BY Class

输出(由于某种原因在两种情况下都是相同的):

1 级 - 2%

2 级 - 15%

3 级 - 45%

4

2 回答 2

1

您正在使用AND连接ON条件中的两个表达式JOIN。关注内部查询:

SELECT Posts.OwnerUserId FROM Posts 
INNER JOIN Badges ON Posts.OwnerUserId = Badges.UserId 
WHERE ViewCount > 1000

相对:

SELECT Posts.OwnerUserId FROM Posts 
INNER JOIN Badges
ON (
    Posts.OwnerUserId = Badges.UserId 
    AND ViewCount > 1000
)

这两个查询在逻辑上是等价的。

于 2016-12-10T11:12:44.787 回答
0

如果您对以下相同的情况感到困惑,请检查一下: 在 SQL SERVER中

CREATE TABLE #a(catId INT, catName VARCHAR(50))
CREATE TABLE #b(productId INT, catId INT)

INSERT INTO #a VALUES 
(1, 'Test1'),
(2, 'Test2'),
(3, 'Test3'),
(4, 'Test4')

INSERT INTO #b VALUES 
(5, 1),
(6, 2),
(7, 3),
(8, 1)

--Return data what exists in both tables
SELECT a.*, b.productId
FROM #a a
INNER JOIN #b b ON b.catId = a.catId
AND b.catId < 3

--Same as above
SELECT a.*, b.productId
FROM #a a
INNER JOIN #b b ON b.catId = a.catId
WHERE b.catId < 3

--Same as above
SELECT a.*, b.productId
FROM #a a
LEFT JOIN #b b ON b.catId = a.catId
WHERE b.catId < 3

--Return all exists in first table though not exist in second table
SELECT a.*, b.productId
FROM #a a
LEFT JOIN #b b ON b.catId = a.catId
AND b.catId < 3
于 2016-12-10T11:24:56.287 回答