我尝试在 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%
答案 0 :(得分: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
)
这两个查询在逻辑上是等价的。
答案 1 :(得分: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