我有一个样本表,加入时打错了字。但这会产生一些我无法理解的结果。您能用简单的英文解释为什么SQL会乘行吗?
我知道如何解决问题:
INNER JOIN @temp tfo ON t.id_StatiOnDeparture= tfo.id_StationDeparture AND t.id_StatiOnDestination= tfo.id_StationDestination AND t.id_City = tfo.id_City AND t.id_District = tfo.id_District AND t.id_Street = tfo.id_Street AND t.Amount = tfo.Amount
但是,我真的很想知道为什么会这样。
请不要关闭我的问题
样本数据:
DECLARE @temp TABLE ( id_StationDeparture INT, id_StationDestination INT, id_City INT, id_District INT, id_Street INT, Amount DECIMAL(15, 2) ) INSERT INTO @temp ( id_StationDeparture, id_StationDestination, id_City, id_District, id_Street, Amount ) VALUES ( 10, 11, 1, 1, 1, 0) , ( 12, 14, 1, 1, 0,0) , ( 16, 18, 1, 1, 0,0)
而我的查询:
SELECT t.id_StationDeparture , t.id_StationDestination , t.id_City , t.id_District , t.id_Street , t.Amount FROM @temp t INNER JOIN @temp tfo ON t.id_StatiOnDeparture= t.id_StationDeparture AND t.id_StatiOnDestination= t.id_StationDestination AND t.id_City = t.id_City AND t.id_District = t.id_District AND t.id_Street = t.id_Street AND t.Amount = t.Amount
我期望得到以下结果,因为我要加入不同的行:
但是,我得到的是:
您需要更改表别名,因为对于不可为空的列t.id_StatiOnDeparture= t.id_StationDeparture
,您的条件始终为true,并且工作方式与CROSS JOIN
:
SELECT t.id_StationDeparture , t.id_StationDestination , t.id_City , t.id_District , t.id_Street , t.Amount FROM @temp t INNER JOIN @temp tfo ON t.id_StatiOnDeparture= tfo.id_StationDeparture AND t.id_StatiOnDestination= tfo.id_StationDestination AND t.id_City = tfo.id_City AND t.id_District = tfo.id_District AND t.id_Street = tfo.id_Street AND t.Amount = tfo.Amount;
db <> fiddle演示
编辑:
结果集有9行,因为CROSS JOIN
它是笛卡尔积,并且3乘以3等于9
集合的基数是集合中元素的数量。输出集的基数等于所有输入集的基数的乘积
| A×B | = | A | ·| B |