-
What is Relation Algebra?
- Relational algebra is a kind of abstract query language. It uses the operation of relation to express the query, as a mathematical tool to study the relation data language. The operation object of relational algebra is relation, and the operation result is relation.
-
Why the repo?
- For skill learning:books:, experimenting:wrench: after class.
- More for fun!:happy:
-
Selection, 选择运算
-
By calling the
selection(lambda)
method. -
Define a
lambda
to choose the rows you want, and useRow.index()
to locate a field, just like the follow.relation = r.selection( lambda row: row[row.index('YOUR_FIELD_NAME')] == YOUR_FIELD_VALUE )
-
-
Projection, 投影运算
-
Use the
projection
method. -
Choose some of the columns you need in the relation object.
relation = r.projection(['id', 'name'])
-
-
Extended Cartesian Product, 广义笛卡尔积
-
By using the
*
operator. -
The
__mul__
method return a Cartesian Product (object of Relation) from two relation operands. -
Quick and easy, just like the follow.
relation = r1 * r2
-
-
Union, 并运算
-
By using the
+
operator. -
The
__add__
method return a Union from two relation operands.relation = r1 + r2
-
-
Difference, 差运算
-
By using the
-
operator. -
The
__sub__
method return Difference from two relation operands.relation = r1 - r2
-
-
Intersection, 交运算
-
The
intersection
method operate the self and the other object and return a intersection (object of Relation).relation = r1.intersection(r2)
-
-
Natural Join, 自然连接
-
The "Natural Join" picks the some-named fields and make special connection between two relation objects.
relation = r1.natural_join(r2)
-
-
Division, 除运算
-
The most magical operation in all over.
-
By using the operator
/
.relation = r1 / r2
-
- Clone this repo.
- Or, download the zip package.
-
Create a python file in your project directory, or open a Python Console.
-
Import necessary modules.
>>> from entity.relation import Relation
-
Create an instance of Relation, setting its fields to make init.
>>> relation = Relation(['id', 'name', 'score']) # Just like this!
-
Append rows, by calling the
add_row()
method.>>> relation.add_row([1, 'John', 98]) # id: 1, name: John, score: 98 >>> relation.add_row([2, 'Tom', 80]) # id: 2, name: Tom, score: 80
-
Try your expressions!
>>> relation.show() # Print the relation object your just created. id name score 1 John 98 2 Tom 80
-
Define a
lambda
to make a selection.>>> # Select the rows whose 'id' == 2. >>> relation.selection( >>> lambda x: x.fields[x.index('id')] == 2 >>> ).show() id name score 2 Tom 80
>>> relation.selection( >>> lambda x: x.fields[x.index('id')] == 2 >>> or x.fields[x.index('score')] == 98 >>> ).show() id name score 1 John 98 2 Tom 80
-
Push your fields in, and get projection return.
>>> relation.projection(['name', 'score']).show() name score John 98 Tom 80
-
- You can also open the file
src/playground.py
in your IDE to get a Quick Start.
- Some bugs in
__mul__
, when the method operate the relations with same-name fields.