我有一个简单的脚本,该脚本获取四个随机数(1到4),然后重新加入以获取匹配的database_id数。当我使用LEFT JOIN运行脚本时,每次都会返回四行(预期结果)。但是,当我使用INNER JOIN运行它时,我得到的行数不尽相同-有时是两行,有时是八行。
从逻辑上讲,应该没有什么区别,因为我知道sys.databases中存在具有database_ids 1-4的行。并且由于我们从具有四行的随机数表中选择(而不是与之连接),因此返回的行数绝不能超过四行。
SQL Server 2012和2014中都会发生这种情况。是什么导致INNER JOIN返回不同数量的行?
/* Works as expected -- always four rows */
SELECT rando.RandomNumber, d.database_id
FROM
(SELECT 1 + ABS(CHECKSUM(NEWID())) % (4) AS RandomNumber
FROM sys.databases WHERE database_id <= 4) AS rando
LEFT JOIN sys.databases d ON rando.RandomNumber = d.database_id;
/* Returns a varying number of rows */
SELECT rando.RandomNumber, d.database_id
FROM
(SELECT 1 + ABS(CHECKSUM(NEWID())) % (4) AS RandomNumber
FROM sys.databases WHERE database_id <= 4) AS rando
INNER JOIN sys.databases d ON rando.RandomNumber = d.database_id;
/* Also returns a varying number of rows */
WITH rando AS (
SELECT 1 + ABS(CHECKSUM(NEWID())) % (4) AS RandomNumber
FROM sys.databases WHERE database_id <= 4
)
SELECT r.RandomNumber, d.database_id
FROM rando AS r
INNER JOIN sys.databases d ON r.RandomNumber = d.database_id;
SELECT TOP (4) d.database_id FROM sys.databases AS d CROSS JOIN (VALUES (1),(2),(3),(4)) AS multi (i) WHERE d.database_id <= 4 ORDER BY CHECKSUM(NEWID()) ;
我猜它很好用,因为不确定性函数的值没有连接。