简体   繁体   English

为什么这个 sql 片段总是返回 8 或 1?

[英]Why does this sql snippet return 8 or 1 always?

What is the result of:结果是什么:

WITH Tbl AS (SELECT 5 AS A UNION SELECT 6 AS A) 
SELECT COUNT(*) AS Tbl FROM Tbl AS A, Tbl AS B, Tbl AS C;

I know the result is supposed to be 8 but I don't know why.我知道结果应该是 8 但我不知道为什么。 Also when I change both values (the 5 or 6) to the same thing it returns a table with the value 1 instead of 8 but all other instances it returns 8 no matter what numbers if they are different.此外,当我将两个值(5 或 6)更改为相同的值时,它返回一个值为 1 而不是 8 的表,但所有其他实例无论数字不同,它都返回 8。 I tested it out with an online sql executor.我用在线 sql 执行器对其进行了测试。

Here is what the query does:这是查询的作用:

  • the common table expression (the subquery within the with clause) generates a derived table made of two rows公共表表达式( with子句中的子查询)生成由两行组成的派生表

  • then, in the outer query, the from clause generates a cartesian product of this resultset twice: that's a total of 8 rows ( 2 * 2 * 2 )然后,在外部查询中, from子句两次生成此结果集的笛卡尔积:总共 8 行 ( 2 * 2 * 2 )

  • the select clause counts the number of rows - that's 8 select子句计算行数 - 即8

The content of the rows in the with clause does not matter: this 5 and 6 could very well be foo and bar , or null and null , the result would be the same. with子句中行的内容无关紧要:这个56很可能是foobar ,或者nullnull ,结果将是相同的。

What makes a difference is the number of rows that the with clause generates.区别在于with子句生成的数。 If it was generating just one row, you would get 1 as a result ( 1 * 1 * 1 ).如果它只是产生一个行,你会得到1结果( 1 * 1 * 1 )。 If it was generating 3 rows, you would get 27 - and so on.如果它生成 3 行,你会得到27 - 等等。

This expression:这个表达:

WITH Tbl AS (SELECT 5 AS A UNION SELECT 6 AS A) 

creates a (derived) table with two rows.创建一个包含两行的(派生)表。

This expression:这个表达:

WITH Tbl AS (SELECT 5 AS A UNION SELECT 5 AS A) 

creates a (derived) table with one row, because UNION removes duplicates.创建一个只有一行的(派生)表,因为UNION删除了重复项。

The rest of the query just counts the number of rows in the 3-way Cartesian product, which is either 1 1 1 or 2 2 2.查询的其余部分只计算 3 路笛卡尔积中的行数,即 1 1 1 或 2 2 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM