- Learning PostgreSQL 10(Second Edition)
- Salahaldin Juba Andrey Volkov
- 395字
- 2021-07-02 22:42:04
The cartesian product operation
The cartesian product operation is used to combine tuples from two relations into a single one. The number of attributes in single relation equals the sum of the number of attributes of the two relations. The number of tuples in the single relation equals the product of the number of tuples in the two relations. Let's assume that A and B are two relations, and C = A × B:
The number of attribute of C = the number of attribute in A + the number of attribute of B
The number of tuples of C = the number of tuples of A * The number of tuples of B
The following image shows the cross join of customer and customer service:

The equivalent SQL join for Cartesian product is CROSS JOIN, the query for the customer with customer_id equal to 1, retrieve the customer id, name and the customer service IDs can be written in SQL as follows:
SELECT DISTINCT customer_id, first_name, last_name, service_id FROM customer AS c CROSS JOIN customer_service AS cs WHERE c.customer_id=cs.customer_id AND c.customer_id = 1;
In the preceding example, one can see the relationship between relational algebra and the SQL language. For example, we have used select, rename, project, and Cartesian product. The preceding example shows how relational algebra could be used to optimize query execution. This example could be executed in several ways:
Execution plan 1:
- Select the customer where customer_id = 1.
- Select the customer service where customer_id = 1.
- Cross JOIN the relations resulting from steps 1 and 2.
- Project customer_id, first_name, last_name, and service_id from the relation resulting from step 3.
Execution plan 2:
- Cross JOIN customer and customer_service.
- Select all the tuples where Customer_service.customer_id=customer.customer_id and customer.customer_id = 1.
- Project customer_id, first_name, last_name, and service_id from the relation resulting from step 2.
The SELECT query is written in this way to show how to translate relational algebra to SQL. In modern SQL code, we can project attributes without using DISTINCT. In addition to that, one should use a proper join instead of cross join.
Each execution plan has a cost in terms of CPU, random access memory (RAM), and hard disk operations. The RDBMS picks the one with the lowest cost. In the preceding execution plans, the rename as well as distinct operator were ignored for simplicity.
- GNU-Linux Rapid Embedded Programming
- Circos Data Visualization How-to
- Dreamweaver CS3網(wǎng)頁(yè)設(shè)計(jì)50例
- Photoshop CS4經(jīng)典380例
- 控制系統(tǒng)計(jì)算機(jī)仿真
- 完全掌握AutoCAD 2008中文版:機(jī)械篇
- Learning C for Arduino
- PostgreSQL 10 Administration Cookbook
- Deep Reinforcement Learning Hands-On
- 邊緣智能:關(guān)鍵技術(shù)與落地實(shí)踐
- Azure PowerShell Quick Start Guide
- Mastering OpenStack(Second Edition)
- PHP求職寶典
- 從祖先到算法:加速進(jìn)化的人類文化
- 天才與算法:人腦與AI的數(shù)學(xué)思維