简体   繁体   English

SQL笛卡尔联接/不带Where子句的交叉联接/使用自联接的谓词

[英]SQL Cartesian Join / Cross Join with no Where clause / predicate using self join

I have a simple table: 我有一个简单的表:

Cartesian
+--------+
| letter |
+--------+
| A      |
| B      |
| C      |
+--------+

Self Join query 1: 自加入查询1:

SELECT t1.letter, t2.letter
FROM cartesian t1, cartesian t2;

Result: 结果:

+--------+--------+
| letter | letter |
+--------+--------+
| A      | A      |
| B      | A      |
| C      | A      |
| A      | B      |
| B      | B      |
| C      | B      |
| A      | C      |
| B      | C      |
| C      | C      |
+--------+--------+

Self Join query 2: 自加入查询2:

SELECT t1.letter, t2.letter
FROM cartesian t2, cartesian t1;

Result: 结果:

+--------+--------+
| letter | letter |
+--------+--------+
| A      | A      |
| A      | B      |
| A      | C      |
| B      | A      |
| B      | B      |
| B      | C      |
| C      | A      |
| C      | B      |
| C      | C      |
+--------+--------+

Why are the results different? 为什么结果不同? I am selecting the same columns and from the same tables. 我从相同的表中选择相同的列。 Only thing different is the ordering of tables in the FROM clause. 唯一不同的是FROM子句中的表顺序。

But the two results are not different at all if you disregard the ordering - the two sets contain the exact same pairs of tuples and therefore are exactly the same. 但是,如果不考虑顺序,则两个结果根本不会有所不同-两组包含完全相同的元组对,因此也完全相同。

Any result that is returned and not explicitly ordered using an order by clause will not be guaranteed to be ordered in any way. 返回的任何结果,但未使用order by子句显式排序的结果,均不保证以任何方式进行排序。 The fact that the order does not appear to be random is due to the internal workings of the query processing component of the database and not something that can or should be relied on. 顺序似乎不是随机的,这是由于数据库的查询处理组件的内部工作所致,而不是可以或不应依赖的事物。

If you want order you have to state it. 如果要订购,则必须注明。

The results aren't different. 结果没有不同。 The same data exists in both results. 两个结果中存在相同的数据。

Without an order by clause its doing it itself, and for what ever reason its decided that t2 will be ordered alphabetically where t1 wont in both cases. 如果没有order by子句,它本身就会执行操作,并且无论出于何种原因,它都决定将t2按字母顺序进行排序,而在两种情况下t1都不会。

Same results, different order. 结果相同,顺序不同。

Actually the simple thing is as long as there is not order by the output order can differ each time , even when using group by to be sure you are getting the order you want you need to give the order-by. 其实简单的事情是,只要输出顺序没有顺序,每次都可以不同 ,即使在使用分组依据时,也要确保获得要订购的订单。 This is a vendor specific implementation and has nothing to do with sql language. 这是特定于供应商的实现,与sql语言无关。 (Even though most db implementations give the order by embedded in the group by.) (即使大多数数据库实现都通过group by嵌入来给出顺序。)

除非您明确使用order by,否则不能保证订购。

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

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